_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q15100
FakedHbaManager.add
train
def add(self, properties): """ Add a faked HBA resource. Parameters: properties (dict): Resource properties. Special handling and requirements for certain properties: * 'element-id' will be auto-generated with a unique value across all instances of this resource type, if not specified. * 'element-uri' will be auto-generated based upon the element ID, if not specified. * 'class' will be auto-generated to 'hba', if not specified. * 'adapter-port-uri' identifies the backing FCP port for this HBA and is required to be specified. * 'device-number' will be auto-generated with a unique value within the partition in the range 0x8000 to 0xFFFF, if not specified. This method also updates the 'hba-uris' property in the parent faked Partition resource, by adding the URI for the faked HBA resource. Returns: :class:`~zhmcclient_mock.FakedHba`: The faked HBA resource. Raises: :exc:`zhmcclient_mock.InputError`: Some issue with the input properties. """ new_hba = super(FakedHbaManager, self).add(properties) partition = self.parent # Reflect the new NIC in the partition assert 'hba-uris' in partition.properties partition.properties['hba-uris'].append(new_hba.uri) # Create a default device-number if not specified if 'device-number' not in new_hba.properties: devno = partition.devno_alloc() new_hba.properties['device-number'] = devno # Create a default wwpn if not specified if 'wwpn' not in new_hba.properties: wwpn = partition.wwpn_alloc() new_hba.properties['wwpn'] = wwpn return new_hba
python
{ "resource": "" }
q15101
FakedHbaManager.remove
train
def remove(self, oid): """ Remove a faked HBA resource. This method also updates the 'hba-uris' property in the parent Partition resource, by removing the URI for the faked HBA resource. Parameters: oid (string): The object ID of the faked HBA resource. """ hba = self.lookup_by_oid(oid) partition = self.parent devno = hba.properties.get('device-number', None) if devno: partition.devno_free_if_allocated(devno) wwpn = hba.properties.get('wwpn', None) if wwpn: partition.wwpn_free_if_allocated(wwpn) assert 'hba-uris' in partition.properties hba_uris = partition.properties['hba-uris'] hba_uris.remove(hba.uri) super(FakedHbaManager, self).remove(oid)
python
{ "resource": "" }
q15102
FakedNicManager.add
train
def add(self, properties): """ Add a faked NIC resource. Parameters: properties (dict): Resource properties. Special handling and requirements for certain properties: * 'element-id' will be auto-generated with a unique value across all instances of this resource type, if not specified. * 'element-uri' will be auto-generated based upon the element ID, if not specified. * 'class' will be auto-generated to 'nic', if not specified. * Either 'network-adapter-port-uri' (for backing ROCE adapters) or 'virtual-switch-uri'(for backing OSA or Hipersockets adapters) is required to be specified. * 'device-number' will be auto-generated with a unique value within the partition in the range 0x8000 to 0xFFFF, if not specified. This method also updates the 'nic-uris' property in the parent faked Partition resource, by adding the URI for the faked NIC resource. This method also updates the 'connected-vnic-uris' property in the virtual switch referenced by 'virtual-switch-uri' property, and sets it to the URI of the faked NIC resource. Returns: :class:`zhmcclient_mock.FakedNic`: The faked NIC resource. Raises: :exc:`zhmcclient_mock.InputError`: Some issue with the input properties. """ new_nic = super(FakedNicManager, self).add(properties) partition = self.parent # For OSA-backed NICs, reflect the new NIC in the virtual switch if 'virtual-switch-uri' in new_nic.properties: vswitch_uri = new_nic.properties['virtual-switch-uri'] # Even though the URI handler when calling this method ensures that # the vswitch exists, this method can be called by the user as # well, so we have to handle the possibility that it does not # exist: try: vswitch = self.hmc.lookup_by_uri(vswitch_uri) except KeyError: raise InputError("The virtual switch specified in the " "'virtual-switch-uri' property does not " "exist: {!r}".format(vswitch_uri)) connected_uris = vswitch.properties['connected-vnic-uris'] if new_nic.uri not in connected_uris: connected_uris.append(new_nic.uri) # Create a default device-number if not specified if 'device-number' not in new_nic.properties: devno = partition.devno_alloc() new_nic.properties['device-number'] = devno # Reflect the new NIC in the partition assert 'nic-uris' in partition.properties partition.properties['nic-uris'].append(new_nic.uri) return new_nic
python
{ "resource": "" }
q15103
FakedNicManager.remove
train
def remove(self, oid): """ Remove a faked NIC resource. This method also updates the 'nic-uris' property in the parent Partition resource, by removing the URI for the faked NIC resource. Parameters: oid (string): The object ID of the faked NIC resource. """ nic = self.lookup_by_oid(oid) partition = self.parent devno = nic.properties.get('device-number', None) if devno: partition.devno_free_if_allocated(devno) assert 'nic-uris' in partition.properties nic_uris = partition.properties['nic-uris'] nic_uris.remove(nic.uri) super(FakedNicManager, self).remove(oid)
python
{ "resource": "" }
q15104
FakedPartition.devno_alloc
train
def devno_alloc(self): """ Allocates a device number unique to this partition, in the range of 0x8000 to 0xFFFF. Returns: string: The device number as four hexadecimal digits in upper case. Raises: ValueError: No more device numbers available in that range. """ devno_int = self._devno_pool.alloc() devno = "{:04X}".format(devno_int) return devno
python
{ "resource": "" }
q15105
FakedPartition.wwpn_alloc
train
def wwpn_alloc(self): """ Allocates a WWPN unique to this partition, in the range of 0xAFFEAFFE00008000 to 0xAFFEAFFE0000FFFF. Returns: string: The WWPN as 16 hexadecimal digits in upper case. Raises: ValueError: No more WWPNs available in that range. """ wwpn_int = self._wwpn_pool.alloc() wwpn = "AFFEAFFE0000" + "{:04X}".format(wwpn_int) return wwpn
python
{ "resource": "" }
q15106
FakedPortManager.add
train
def add(self, properties): """ Add a faked Port resource. Parameters: properties (dict): Resource properties. Special handling and requirements for certain properties: * 'element-id' will be auto-generated with a unique value across all instances of this resource type, if not specified. * 'element-uri' will be auto-generated based upon the element ID, if not specified. * 'class' will be auto-generated to 'network-port' or 'storage-port', if not specified. This method also updates the 'network-port-uris' or 'storage-port-uris' property in the parent Adapter resource, by adding the URI for the faked Port resource. Returns: :class:`zhmcclient_mock.FakedPort`: The faked Port resource. """ new_port = super(FakedPortManager, self).add(properties) adapter = self.parent if 'network-port-uris' in adapter.properties: adapter.properties['network-port-uris'].append(new_port.uri) if 'storage-port-uris' in adapter.properties: adapter.properties['storage-port-uris'].append(new_port.uri) return new_port
python
{ "resource": "" }
q15107
FakedPortManager.remove
train
def remove(self, oid): """ Remove a faked Port resource. This method also updates the 'network-port-uris' or 'storage-port-uris' property in the parent Adapter resource, by removing the URI for the faked Port resource. Parameters: oid (string): The object ID of the faked Port resource. """ port = self.lookup_by_oid(oid) adapter = self.parent if 'network-port-uris' in adapter.properties: port_uris = adapter.properties['network-port-uris'] port_uris.remove(port.uri) if 'storage-port-uris' in adapter.properties: port_uris = adapter.properties['storage-port-uris'] port_uris.remove(port.uri) super(FakedPortManager, self).remove(oid)
python
{ "resource": "" }
q15108
FakedVirtualFunctionManager.add
train
def add(self, properties): """ Add a faked Virtual Function resource. Parameters: properties (dict): Resource properties. Special handling and requirements for certain properties: * 'element-id' will be auto-generated with a unique value across all instances of this resource type, if not specified. * 'element-uri' will be auto-generated based upon the element ID, if not specified. * 'class' will be auto-generated to 'virtual-function', if not specified. * 'device-number' will be auto-generated with a unique value within the partition in the range 0x8000 to 0xFFFF, if not specified. This method also updates the 'virtual-function-uris' property in the parent Partition resource, by adding the URI for the faked Virtual Function resource. Returns: :class:`zhmcclient_mock.FakedVirtualFunction`: The faked Virtual Function resource. """ new_vf = super(FakedVirtualFunctionManager, self).add(properties) partition = self.parent assert 'virtual-function-uris' in partition.properties partition.properties['virtual-function-uris'].append(new_vf.uri) if 'device-number' not in new_vf.properties: devno = partition.devno_alloc() new_vf.properties['device-number'] = devno return new_vf
python
{ "resource": "" }
q15109
FakedVirtualFunctionManager.remove
train
def remove(self, oid): """ Remove a faked Virtual Function resource. This method also updates the 'virtual-function-uris' property in the parent Partition resource, by removing the URI for the faked Virtual Function resource. Parameters: oid (string): The object ID of the faked Virtual Function resource. """ virtual_function = self.lookup_by_oid(oid) partition = self.parent devno = virtual_function.properties.get('device-number', None) if devno: partition.devno_free_if_allocated(devno) assert 'virtual-function-uris' in partition.properties vf_uris = partition.properties['virtual-function-uris'] vf_uris.remove(virtual_function.uri) super(FakedVirtualFunctionManager, self).remove(oid)
python
{ "resource": "" }
q15110
FakedMetricsContextManager.add_metric_group_definition
train
def add_metric_group_definition(self, definition): """ Add a faked metric group definition. The definition will be used: * For later addition of faked metrics responses. * For returning the metric-group-info objects in the response of the Create Metrics Context operations. For defined metric groups, see chapter "Metric groups" in the :term:`HMC API` book. Parameters: definition (:class:~zhmcclient.FakedMetricGroupDefinition`): Definition of the metric group. Raises: ValueError: A metric group definition with this name already exists. """ assert isinstance(definition, FakedMetricGroupDefinition) group_name = definition.name if group_name in self._metric_group_defs: raise ValueError("A metric group definition with this name " "already exists: {}".format(group_name)) self._metric_group_defs[group_name] = definition self._metric_group_def_names.append(group_name)
python
{ "resource": "" }
q15111
FakedMetricsContextManager.get_metric_group_definition
train
def get_metric_group_definition(self, group_name): """ Get a faked metric group definition by its group name. Parameters: group_name (:term:`string`): Name of the metric group. Returns: :class:~zhmcclient.FakedMetricGroupDefinition`: Definition of the metric group. Raises: ValueError: A metric group definition with this name does not exist. """ if group_name not in self._metric_group_defs: raise ValueError("A metric group definition with this name does " "not exist: {}".format(group_name)) return self._metric_group_defs[group_name]
python
{ "resource": "" }
q15112
FakedMetricsContextManager.add_metric_values
train
def add_metric_values(self, values): """ Add one set of faked metric values for a particular resource to the metrics response for a particular metric group, for later retrieval. For defined metric groups, see chapter "Metric groups" in the :term:`HMC API` book. Parameters: values (:class:`~zhmclient.FakedMetricObjectValues`): The set of metric values to be added. It specifies the resource URI and the targeted metric group name. """ assert isinstance(values, FakedMetricObjectValues) group_name = values.group_name if group_name not in self._metric_values: self._metric_values[group_name] = [] self._metric_values[group_name].append(values) if group_name not in self._metric_value_names: self._metric_value_names.append(group_name)
python
{ "resource": "" }
q15113
FakedMetricsContextManager.get_metric_values
train
def get_metric_values(self, group_name): """ Get the faked metric values for a metric group, by its metric group name. The result includes all metric object values added earlier for that metric group name, using :meth:`~zhmcclient.FakedMetricsContextManager.add_metric_object_values` i.e. the metric values for all resources and all points in time that were added. Parameters: group_name (:term:`string`): Name of the metric group. Returns: iterable of :class:`~zhmclient.FakedMetricObjectValues`: The metric values for that metric group, in the order they had been added. Raises: ValueError: Metric values for this group name do not exist. """ if group_name not in self._metric_values: raise ValueError("Metric values for this group name do not " "exist: {}".format(group_name)) return self._metric_values[group_name]
python
{ "resource": "" }
q15114
FakedMetricsContext.get_metric_group_definitions
train
def get_metric_group_definitions(self): """ Get the faked metric group definitions for this context object that are to be returned from its create operation. If a 'metric-groups' property had been specified for this context, only those faked metric group definitions of its manager object that are in that list, are included in the result. Otherwise, all metric group definitions of its manager are included in the result. Returns: iterable of :class:~zhmcclient.FakedMetricGroupDefinition`: The faked metric group definitions, in the order they had been added. """ group_names = self.properties.get('metric-groups', None) if not group_names: group_names = self.manager.get_metric_group_definition_names() mg_defs = [] for group_name in group_names: try: mg_def = self.manager.get_metric_group_definition(group_name) mg_defs.append(mg_def) except ValueError: pass # ignore metric groups without metric group defs return mg_defs
python
{ "resource": "" }
q15115
FakedMetricsContext.get_metric_group_infos
train
def get_metric_group_infos(self): """ Get the faked metric group definitions for this context object that are to be returned from its create operation, in the format needed for the "Create Metrics Context" operation response. Returns: "metric-group-infos" JSON object as described for the "Create Metrics Context "operation response. """ mg_defs = self.get_metric_group_definitions() mg_infos = [] for mg_def in mg_defs: metric_infos = [] for metric_name, metric_type in mg_def.types: metric_infos.append({ 'metric-name': metric_name, 'metric-type': metric_type, }) mg_info = { 'group-name': mg_def.name, 'metric-infos': metric_infos, } mg_infos.append(mg_info) return mg_infos
python
{ "resource": "" }
q15116
FakedMetricsContext.get_metric_values
train
def get_metric_values(self): """ Get the faked metrics, for all metric groups and all resources that have been prepared on the manager object of this context object. Returns: iterable of tuple (group_name, iterable of values): The faked metrics, in the order they had been added, where: group_name (string): Metric group name. values (:class:~zhmcclient.FakedMetricObjectValues`): The metric values for one resource at one point in time. """ group_names = self.properties.get('metric-groups', None) if not group_names: group_names = self.manager.get_metric_values_group_names() ret = [] for group_name in group_names: try: mo_val = self.manager.get_metric_values(group_name) ret_item = (group_name, mo_val) ret.append(ret_item) except ValueError: pass # ignore metric groups without metric values return ret
python
{ "resource": "" }
q15117
FakedMetricsContext.get_metric_values_response
train
def get_metric_values_response(self): """ Get the faked metrics, for all metric groups and all resources that have been prepared on the manager object of this context object, as a string in the format needed for the "Get Metrics" operation response. Returns: "MetricsResponse" string as described for the "Get Metrics" operation response. """ mv_list = self.get_metric_values() resp_lines = [] for mv in mv_list: group_name = mv[0] resp_lines.append('"{}"'.format(group_name)) mo_vals = mv[1] for mo_val in mo_vals: resp_lines.append('"{}"'.format(mo_val.resource_uri)) resp_lines.append( str(timestamp_from_datetime(mo_val.timestamp))) v_list = [] for n, v in mo_val.values: if isinstance(v, six.string_types): v_str = '"{}"'.format(v) else: v_str = str(v) v_list.append(v_str) v_line = ','.join(v_list) resp_lines.append(v_line) resp_lines.append('') resp_lines.append('') resp_lines.append('') return '\n'.join(resp_lines) + '\n'
python
{ "resource": "" }
q15118
StorageVolume.update_properties
train
def update_properties(self, properties, email_to_addresses=None, email_cc_addresses=None, email_insert=None): """ Update writeable properties of this storage volume on the HMC, and optionally send emails to storage administrators requesting modification of the storage volume on the storage subsystem and of any resources related to the storage volume. This method performs the "Modify Storage Group Properties" operation, requesting modification of the volume. Authorization requirements: * Object-access permission to the storage group owning this storage volume. * Task permission to the "Configure Storage - System Programmer" task. Parameters: properties (dict): New property values for the volume. Allowable properties are the fields defined in the "storage-volume-request-info" nested object for the "modify" operation. That nested object is described in section "Request body contents" for operation "Modify Storage Group Properties" in the :term:`HMC API` book. The properties provided in this parameter will be copied and then amended with the `operation="modify"` and `element-uri` properties, and then used as a single array item for the `storage-volumes` field in the request body of the "Modify Storage Group Properties" operation. email_to_addresses (:term:`iterable` of :term:`string`): Email addresses of one or more storage administrator to be notified. If `None` or empty, no email will be sent. email_cc_addresses (:term:`iterable` of :term:`string`): Email addresses of one or more storage administrator to be copied on the notification email. If `None` or empty, nobody will be copied on the email. Must be `None` or empty if `email_to_addresses` is `None` or empty. email_insert (:term:`string`): Additional text to be inserted in the notification email. The text can include HTML formatting tags. If `None`, no additional text will be inserted. Must be `None` or empty if `email_to_addresses` is `None` or empty. Raises: :exc:`~zhmcclient.HTTPError` :exc:`~zhmcclient.ParseError` :exc:`~zhmcclient.AuthError` :exc:`~zhmcclient.ConnectionError` """ volreq_obj = copy.deepcopy(properties) volreq_obj['operation'] = 'modify' volreq_obj['element-uri'] = self.uri body = { 'storage-volumes': [volreq_obj], } if email_to_addresses: body['email-to-addresses'] = email_to_addresses if email_cc_addresses: body['email-cc-addresses'] = email_cc_addresses if email_insert: body['email-insert'] = email_insert else: if email_cc_addresses: raise ValueError("email_cc_addresses must not be specified if " "there is no email_to_addresses: %r" % email_cc_addresses) if email_insert: raise ValueError("email_insert must not be specified if " "there is no email_to_addresses: %r" % email_insert) self.manager.session.post( self.manager.storage_group.uri + '/operations/modify', body=body) self.properties.update(copy.deepcopy(properties))
python
{ "resource": "" }
q15119
VirtualFunctionManager.list
train
def list(self, full_properties=False, filter_args=None): """ List the Virtual Functions of this Partition. Authorization requirements: * Object-access permission to this Partition. Parameters: full_properties (bool): Controls whether the full set of resource properties should be retrieved, vs. only the short set as returned by the list operation. filter_args (dict): Filter arguments that narrow the list of returned resources to those that match the specified filter arguments. For details, see :ref:`Filtering`. `None` causes no filtering to happen, i.e. all resources are returned. Returns: : A list of :class:`~zhmcclient.VirtualFunction` objects. Raises: :exc:`~zhmcclient.HTTPError` :exc:`~zhmcclient.ParseError` :exc:`~zhmcclient.AuthError` :exc:`~zhmcclient.ConnectionError` """ resource_obj_list = [] uris = self.partition.get_property('virtual-function-uris') if uris: for uri in uris: resource_obj = self.resource_class( manager=self, uri=uri, name=None, properties=None) if self._matches_filters(resource_obj, filter_args): resource_obj_list.append(resource_obj) if full_properties: resource_obj.pull_full_properties() self._name_uri_cache.update_from(resource_obj_list) return resource_obj_list
python
{ "resource": "" }
q15120
PortManager.list
train
def list(self, full_properties=False, filter_args=None): """ List the Ports of this Adapter. If the adapter does not have any ports, an empty list is returned. Authorization requirements: * Object-access permission to this Adapter. Parameters: full_properties (bool): Controls whether the full set of resource properties should be retrieved, vs. only the short set as returned by the list operation. filter_args (dict): Filter arguments that narrow the list of returned resources to those that match the specified filter arguments. For details, see :ref:`Filtering`. `None` causes no filtering to happen, i.e. all resources are returned. Returns: : A list of :class:`~zhmcclient.Port` objects. Raises: :exc:`~zhmcclient.HTTPError` :exc:`~zhmcclient.ParseError` :exc:`~zhmcclient.AuthError` :exc:`~zhmcclient.ConnectionError` """ uris_prop = self.adapter.port_uris_prop if not uris_prop: # Adapter does not have any ports return [] uris = self.adapter.get_property(uris_prop) assert uris is not None # TODO: Remove the following circumvention once fixed. # The following line circumvents a bug for FCP adapters that sometimes # causes duplicate URIs to show up in this property: uris = list(set(uris)) resource_obj_list = [] for uri in uris: resource_obj = self.resource_class( manager=self, uri=uri, name=None, properties=None) if self._matches_filters(resource_obj, filter_args): resource_obj_list.append(resource_obj) if full_properties: resource_obj.pull_full_properties() self._name_uri_cache.update_from(resource_obj_list) return resource_obj_list
python
{ "resource": "" }
q15121
User.add_user_role
train
def add_user_role(self, user_role): """ Add the specified User Role to this User. This User must not be a system-defined or pattern-based user. Authorization requirements: * Task permission to the "Manage Users" task to modify a standard user or the "Manage User Templates" task to modify a template user. Parameters: user_role (:class:`~zhmcclient.UserRole`): User Role to be added. Must not be `None`. Raises: :exc:`~zhmcclient.HTTPError` :exc:`~zhmcclient.ParseError` :exc:`~zhmcclient.AuthError` :exc:`~zhmcclient.ConnectionError` """ body = { 'user-role-uri': user_role.uri } self.manager.session.post( self.uri + '/operations/add-user-role', body=body)
python
{ "resource": "" }
q15122
User.remove_user_role
train
def remove_user_role(self, user_role): """ Remove the specified User Role from this User. This User must not be a system-defined or pattern-based user. Authorization requirements: * Task permission to the "Manage Users" task to modify a standard user or the "Manage User Templates" task to modify a template user. Parameters: user_role (:class:`~zhmcclient.UserRole`): User Role to be removed. Must not be `None`. Raises: :exc:`~zhmcclient.HTTPError` :exc:`~zhmcclient.ParseError` :exc:`~zhmcclient.AuthError` :exc:`~zhmcclient.ConnectionError` """ body = { 'user-role-uri': user_role.uri } self.manager.session.post( self.uri + '/operations/remove-user-role', body=body)
python
{ "resource": "" }
q15123
FakedSession.get
train
def get(self, uri, logon_required=True): """ Perform the HTTP GET method against the resource identified by a URI, on the faked HMC. Parameters: uri (:term:`string`): Relative URI path of the resource, e.g. "/api/session". This URI is relative to the base URL of the session (see the :attr:`~zhmcclient.Session.base_url` property). Must not be `None`. logon_required (bool): Boolean indicating whether the operation requires that the session is logged on to the HMC. Because this is a faked HMC, this does not perform a real logon, but it is still used to update the state in the faked HMC. Returns: :term:`json object` with the operation result. Raises: :exc:`~zhmcclient.HTTPError` :exc:`~zhmcclient.ParseError` (not implemented) :exc:`~zhmcclient.AuthError` (not implemented) :exc:`~zhmcclient.ConnectionError` """ try: return self._urihandler.get(self._hmc, uri, logon_required) except HTTPError as exc: raise zhmcclient.HTTPError(exc.response()) except ConnectionError as exc: raise zhmcclient.ConnectionError(exc.message, None)
python
{ "resource": "" }
q15124
FakedSession.post
train
def post(self, uri, body=None, logon_required=True, wait_for_completion=True, operation_timeout=None): """ Perform the HTTP POST method against the resource identified by a URI, using a provided request body, on the faked HMC. HMC operations using HTTP POST are either synchronous or asynchronous. Asynchronous operations return the URI of an asynchronously executing job that can be queried for status and result. Examples for synchronous operations: * With no response body: "Logon", "Update CPC Properties" * With a response body: "Create Partition" Examples for asynchronous operations: * With no ``job-results`` field in the completed job status response: "Start Partition" * With a ``job-results`` field in the completed job status response (under certain conditions): "Activate a Blade", or "Set CPC Power Save" The `wait_for_completion` parameter of this method can be used to deal with asynchronous HMC operations in a synchronous way. Parameters: uri (:term:`string`): Relative URI path of the resource, e.g. "/api/session". This URI is relative to the base URL of the session (see the :attr:`~zhmcclient.Session.base_url` property). Must not be `None`. body (:term:`json object`): JSON object to be used as the HTTP request body (payload). `None` means the same as an empty dictionary, namely that no HTTP body is included in the request. logon_required (bool): Boolean indicating whether the operation requires that the session is logged on to the HMC. For example, the "Logon" operation does not require that. Because this is a faked HMC, this does not perform a real logon, but it is still used to update the state in the faked HMC. wait_for_completion (bool): Boolean controlling whether this method should wait for completion of the requested HMC operation, as follows: * If `True`, this method will wait for completion of the requested operation, regardless of whether the operation is synchronous or asynchronous. This will cause an additional entry in the time statistics to be created for the asynchronous operation and waiting for its completion. This entry will have a URI that is the targeted URI, appended with "+completion". * If `False`, this method will immediately return the result of the HTTP POST method, regardless of whether the operation is synchronous or asynchronous. operation_timeout (:term:`number`): Timeout in seconds, when waiting for completion of an asynchronous operation. The special value 0 means that no timeout is set. `None` means that the default async operation timeout of the session is used. For `wait_for_completion=True`, a :exc:`~zhmcclient.OperationTimeout` is raised when the timeout expires. For `wait_for_completion=False`, this parameter has no effect. Returns: :term:`json object`: If `wait_for_completion` is `True`, returns a JSON object representing the response body of the synchronous operation, or the response body of the completed job that performed the asynchronous operation. If a synchronous operation has no response body, `None` is returned. If `wait_for_completion` is `False`, returns a JSON object representing the response body of the synchronous or asynchronous operation. In case of an asynchronous operation, the JSON object will have a member named ``job-uri``, whose value can be used with the :meth:`~zhmcclient.Session.query_job_status` method to determine the status of the job and the result of the original operation, once the job has completed. See the section in the :term:`HMC API` book about the specific HMC operation and about the 'Query Job Status' operation, for a description of the members of the returned JSON objects. Raises: :exc:`~zhmcclient.HTTPError` :exc:`~zhmcclient.ParseError` (not implemented) :exc:`~zhmcclient.AuthError` (not implemented) :exc:`~zhmcclient.ConnectionError` """ try: return self._urihandler.post(self._hmc, uri, body, logon_required, wait_for_completion) except HTTPError as exc: raise zhmcclient.HTTPError(exc.response()) except ConnectionError as exc: raise zhmcclient.ConnectionError(exc.message, None)
python
{ "resource": "" }
q15125
_NotificationListener.on_disconnected
train
def on_disconnected(self): """ Event method that gets called when the JMS session has been disconnected. It hands over a termination notification (headers and message are None). """ with self._handover_cond: # Wait until receiver has processed the previous notification while len(self._handover_dict) > 0: self._handover_cond.wait(self._wait_timeout) # Indicate to receiver that there is a termination notification self._handover_dict['headers'] = None # terminate receiver self._handover_dict['message'] = None self._handover_cond.notifyAll()
python
{ "resource": "" }
q15126
Console.restart
train
def restart(self, force=False, wait_for_available=True, operation_timeout=None): """ Restart the HMC represented by this Console object. Once the HMC is online again, this Console object, as well as any other resource objects accessed through this HMC, can continue to be used. An automatic re-logon will be performed under the covers, because the HMC restart invalidates the currently used HMC session. Authorization requirements: * Task permission for the "Shutdown/Restart" task. * "Remote Restart" must be enabled on the HMC. Parameters: force (bool): Boolean controlling whether the restart operation is processed when users are connected (`True`) or not (`False`). Users in this sense are local or remote GUI users. HMC WS API clients do not count as users for this purpose. wait_for_available (bool): Boolean controlling whether this method should wait for the HMC to become available again after the restart, as follows: * If `True`, this method will wait until the HMC has restarted and is available again. The :meth:`~zhmcclient.Client.query_api_version` method will be used to check for availability of the HMC. * If `False`, this method will return immediately once the HMC has accepted the request to be restarted. operation_timeout (:term:`number`): Timeout in seconds, for waiting for HMC availability after the restart. The special value 0 means that no timeout is set. `None` means that the default async operation timeout of the session is used. If the timeout expires when `wait_for_available=True`, a :exc:`~zhmcclient.OperationTimeout` is raised. Raises: :exc:`~zhmcclient.HTTPError` :exc:`~zhmcclient.ParseError` :exc:`~zhmcclient.AuthError` :exc:`~zhmcclient.ConnectionError` :exc:`~zhmcclient.OperationTimeout`: The timeout expired while waiting for the HMC to become available again after the restart. """ body = {'force': force} self.manager.session.post(self.uri + '/operations/restart', body=body) if wait_for_available: time.sleep(10) self.manager.client.wait_for_available( operation_timeout=operation_timeout)
python
{ "resource": "" }
q15127
Console.shutdown
train
def shutdown(self, force=False): """ Shut down and power off the HMC represented by this Console object. While the HMC is powered off, any Python resource objects retrieved from this HMC may raise exceptions upon further use. In order to continue using Python resource objects retrieved from this HMC, the HMC needs to be started again (e.g. by powering it on locally). Once the HMC is available again, Python resource objects retrieved from that HMC can continue to be used. An automatic re-logon will be performed under the covers, because the HMC startup invalidates the currently used HMC session. Authorization requirements: * Task permission for the "Shutdown/Restart" task. * "Remote Shutdown" must be enabled on the HMC. Parameters: force (bool): Boolean controlling whether the shutdown operation is processed when users are connected (`True`) or not (`False`). Users in this sense are local or remote GUI users. HMC WS API clients do not count as users for this purpose. Raises: :exc:`~zhmcclient.HTTPError` :exc:`~zhmcclient.ParseError` :exc:`~zhmcclient.AuthError` :exc:`~zhmcclient.ConnectionError` """ body = {'force': force} self.manager.session.post(self.uri + '/operations/shutdown', body=body)
python
{ "resource": "" }
q15128
Console._time_query_parms
train
def _time_query_parms(begin_time, end_time): """Return the URI query paramterer string for the specified begin time and end time.""" query_parms = [] if begin_time is not None: begin_ts = timestamp_from_datetime(begin_time) qp = 'begin-time={}'.format(begin_ts) query_parms.append(qp) if end_time is not None: end_ts = timestamp_from_datetime(end_time) qp = 'end-time={}'.format(end_ts) query_parms.append(qp) query_parms_str = '&'.join(query_parms) if query_parms_str: query_parms_str = '?' + query_parms_str return query_parms_str
python
{ "resource": "" }
q15129
Console.get_audit_log
train
def get_audit_log(self, begin_time=None, end_time=None): """ Return the console audit log entries, optionally filtered by their creation time. Authorization requirements: * Task permission to the "Audit and Log Management" task. Parameters: begin_time (:class:`~py:datetime.datetime`): Begin time for filtering. Log entries with a creation time older than the begin time will be omitted from the results. If `None`, no such filtering is performed (and the oldest available log entries will be included). end_time (:class:`~py:datetime.datetime`): End time for filtering. Log entries with a creation time newer than the end time will be omitted from the results. If `None`, no such filtering is performed (and the newest available log entries will be included). Returns: :term:`json object`: A JSON object with the log entries, as described in section 'Response body contents' of operation 'Get Console Audit Log' in the :term:`HMC API` book. Raises: :exc:`~zhmcclient.HTTPError` :exc:`~zhmcclient.ParseError` :exc:`~zhmcclient.AuthError` :exc:`~zhmcclient.ConnectionError` """ query_parms = self._time_query_parms(begin_time, end_time) uri = self.uri + '/operations/get-audit-log' + query_parms result = self.manager.session.post(uri) return result
python
{ "resource": "" }
q15130
Console.list_unmanaged_cpcs
train
def list_unmanaged_cpcs(self, name=None): """ List the unmanaged CPCs of this HMC. For details, see :meth:`~zhmcclient.UnmanagedCpc.list`. Authorization requirements: * None Parameters: name (:term:`string`): Regular expression pattern for the CPC name, as a filter that narrows the list of returned CPCs to those whose name property matches the specified pattern. `None` causes no filtering to happen, i.e. all unmanaged CPCs discovered by the HMC are returned. Returns: : A list of :class:`~zhmcclient.UnmanagedCpc` objects. Raises: :exc:`~zhmcclient.HTTPError` :exc:`~zhmcclient.ParseError` :exc:`~zhmcclient.AuthError` :exc:`~zhmcclient.ConnectionError` """ filter_args = dict() if name is not None: filter_args['name'] = name cpcs = self.unmanaged_cpcs.list(filter_args=filter_args) return cpcs
python
{ "resource": "" }
q15131
Cpc.feature_info
train
def feature_info(self): """ Returns information about the features available for this CPC. Authorization requirements: * Object-access permission to this CPC. Returns: :term:`iterable`: An iterable where each item represents one feature that is available for this CPC. Each item is a dictionary with the following items: * `name` (:term:`unicode string`): Name of the feature. * `description` (:term:`unicode string`): Short description of the feature. * `state` (bool): Enablement state of the feature (`True` if the enabled, `False` if disabled). Raises: :exc:`ValueError`: Features are not supported on the HMC. :exc:`~zhmcclient.HTTPError` :exc:`~zhmcclient.ParseError` :exc:`~zhmcclient.AuthError` :exc:`~zhmcclient.ConnectionError` """ feature_list = self.prop('available-features-list', None) if feature_list is None: raise ValueError("Firmware features are not supported on CPC %s" % self.name) return feature_list
python
{ "resource": "" }
q15132
Cpc.start
train
def start(self, wait_for_completion=True, operation_timeout=None): """ Start this CPC, using the HMC operation "Start CPC". Authorization requirements: * Object-access permission to this CPC. * Task permission for the "Start (start a single DPM system)" task. Parameters: wait_for_completion (bool): Boolean controlling whether this method should wait for completion of the requested asynchronous HMC operation, as follows: * If `True`, this method will wait for completion of the asynchronous job performing the operation. * If `False`, this method will return immediately once the HMC has accepted the request to perform the operation. operation_timeout (:term:`number`): Timeout in seconds, for waiting for completion of the asynchronous job performing the operation. The special value 0 means that no timeout is set. `None` means that the default async operation timeout of the session is used. If the timeout expires when `wait_for_completion=True`, a :exc:`~zhmcclient.OperationTimeout` is raised. Returns: `None` or :class:`~zhmcclient.Job`: If `wait_for_completion` is `True`, returns `None`. If `wait_for_completion` is `False`, returns a :class:`~zhmcclient.Job` object representing the asynchronously executing job on the HMC. Raises: :exc:`~zhmcclient.HTTPError` :exc:`~zhmcclient.ParseError` :exc:`~zhmcclient.AuthError` :exc:`~zhmcclient.ConnectionError` :exc:`~zhmcclient.OperationTimeout`: The timeout expired while waiting for completion of the operation. """ result = self.manager.session.post( self.uri + '/operations/start', wait_for_completion=wait_for_completion, operation_timeout=operation_timeout) return result
python
{ "resource": "" }
q15133
Cpc.get_free_crypto_domains
train
def get_free_crypto_domains(self, crypto_adapters=None): """ Return a list of crypto domains that are free for usage on a list of crypto adapters in this CPC. A crypto domain is considered free for usage if it is not assigned to any defined partition of this CPC in access mode 'control-usage' on any of the specified crypto adapters. For this test, all currently defined partitions of this CPC are checked, regardless of whether or not they are active. This ensures that a crypto domain that is found to be free for usage can be assigned to a partition for 'control-usage' access to the specified crypto adapters, without causing a crypto domain conflict when activating that partition. Note that a similar notion of free domains does not exist for access mode 'control', because a crypto domain on a crypto adapter can be in control access by multiple active partitions. This method requires the CPC to be in DPM mode. **Example:** .. code-block:: text crypto domains adapters 0 1 2 3 +---+---+---+---+ c1 |A,c|a,c| | C | +---+---+---+---+ c2 |b,c|B,c| B | C | +---+---+---+---+ In this example, the CPC has two crypto adapters c1 and c2. For simplicity of the example, we assume these crypto adapters support only 4 crypto domains. Partition A uses only adapter c1 and has domain 0 in 'control-usage' access (indicated by an upper case letter 'A' in the corresponding cell) and has domain 1 in 'control' access (indicated by a lower case letter 'a' in the corresponding cell). Partition B uses only adapter c2 and has domain 0 in 'control' access and domains 1 and 2 in 'control-usage' access. Partition C uses both adapters, and has domains 0 and 1 in 'control' access and domain 3 in 'control-usage' access. The domains free for usage in this example are shown in the following table, for each combination of crypto adapters to be investigated: =============== ====================== crypto_adapters domains free for usage =============== ====================== c1 1, 2 c2 0 c1, c2 (empty list) =============== ====================== **Experimental:** This method has been added in v0.14.0 and is currently considered experimental. Its interface may change incompatibly. Once the interface remains stable, this experimental marker will be removed. Authorization requirements: * Object-access permission to this CPC. * Object-access permission to all of its Partitions. * Object-access permission to all of its crypto Adapters. Parameters: crypto_adapters (:term:`iterable` of :class:`~zhmcclient.Adapter`): The crypto :term:`Adapters <Adapter>` to be investigated. `None` means to investigate all crypto adapters of this CPC. Returns: A sorted list of domain index numbers (integers) of the crypto domains that are free for usage on the specified crypto adapters. Returns `None`, if ``crypto_adapters`` was an empty list or if ``crypto_adapters`` was `None` and the CPC has no crypto adapters. Raises: :exc:`~zhmcclient.HTTPError` :exc:`~zhmcclient.ParseError` :exc:`~zhmcclient.AuthError` :exc:`~zhmcclient.ConnectionError` """ if crypto_adapters is None: crypto_adapters = self.adapters.findall(type='crypto') if not crypto_adapters: # No crypto adapters were specified or defaulted. return None # We determine the maximum number of crypto domains independently # of the partitions, because (1) it is possible that no partition # has a crypto configuration and (2) further down we want the inner # loop to be on the crypto adapters because accessing them multiple # times does not drive additional HMC operations. max_domains = None # maximum number of domains across all adapters for ca in crypto_adapters: if max_domains is None: max_domains = ca.maximum_crypto_domains else: max_domains = min(ca.maximum_crypto_domains, max_domains) used_domains = set() # Crypto domains used in control-usage mode partitions = self.partitions.list(full_properties=True) for partition in partitions: crypto_config = partition.get_property('crypto-configuration') if crypto_config: adapter_uris = crypto_config['crypto-adapter-uris'] domain_configs = crypto_config['crypto-domain-configurations'] for ca in crypto_adapters: if ca.uri in adapter_uris: used_adapter_domains = list() for dc in domain_configs: if dc['access-mode'] == 'control-usage': used_adapter_domains.append(dc['domain-index']) used_domains.update(used_adapter_domains) all_domains = set(range(0, max_domains)) free_domains = all_domains - used_domains return sorted(list(free_domains))
python
{ "resource": "" }
q15134
Cpc.set_power_save
train
def set_power_save(self, power_saving, wait_for_completion=True, operation_timeout=None): """ Set the power save setting of this CPC. The current power save setting in effect for a CPC is described in the "cpc-power-saving" property of the CPC. This method performs the HMC operation "Set CPC Power Save". It requires that the feature "Automate/advanced management suite" (FC 0020) is installed and enabled, and fails otherwise. This method will also fail if the CPC is under group control. Whether a CPC currently allows this method is described in the "cpc-power-save-allowed" property of the CPC. Authorization requirements: * Object-access permission to this CPC. * Task permission for the "Power Save" task. Parameters: power_saving (:term:`string`): The new power save setting, with the possible values: * "high-performance" - The power consumption and performance of the CPC are not reduced. This is the default setting. * "low-power" - Low power consumption for all components of the CPC enabled for power saving. * "custom" - Components may have their own settings changed individually. No component settings are actually changed when this mode is entered. wait_for_completion (bool): Boolean controlling whether this method should wait for completion of the requested asynchronous HMC operation, as follows: * If `True`, this method will wait for completion of the asynchronous job performing the operation. * If `False`, this method will return immediately once the HMC has accepted the request to perform the operation. operation_timeout (:term:`number`): Timeout in seconds, for waiting for completion of the asynchronous job performing the operation. The special value 0 means that no timeout is set. `None` means that the default async operation timeout of the session is used. If the timeout expires when `wait_for_completion=True`, a :exc:`~zhmcclient.OperationTimeout` is raised. Returns: `None` or :class:`~zhmcclient.Job`: If `wait_for_completion` is `True`, returns `None`. If `wait_for_completion` is `False`, returns a :class:`~zhmcclient.Job` object representing the asynchronously executing job on the HMC. Raises: :exc:`~zhmcclient.HTTPError`: See the HTTP status and reason codes of operation "Set CPC Power Save" in the :term:`HMC API` book. :exc:`~zhmcclient.ParseError` :exc:`~zhmcclient.AuthError` :exc:`~zhmcclient.ConnectionError` :exc:`~zhmcclient.OperationTimeout`: The timeout expired while waiting for completion of the operation. """ body = {'power-saving': power_saving} result = self.manager.session.post( self.uri + '/operations/set-cpc-power-save', body, wait_for_completion=wait_for_completion, operation_timeout=operation_timeout) if wait_for_completion: # The HMC API book does not document what the result data of the # completed job is. It turns out that the completed job has this # dictionary as its result data: # {'message': 'Operation executed successfully'} # We transform that to None. return None return result
python
{ "resource": "" }
q15135
Cpc.set_power_capping
train
def set_power_capping(self, power_capping_state, power_cap=None, wait_for_completion=True, operation_timeout=None): """ Set the power capping settings of this CPC. The power capping settings of a CPC define whether or not the power consumption of the CPC is limited and if so, what the limit is. Use this method to limit the peak power consumption of a CPC, or to remove a power consumption limit for a CPC. The current power capping settings in effect for a CPC are described in the "cpc-power-capping-state" and "cpc-power-cap-current" properties of the CPC. This method performs the HMC operation "Set CPC Power Capping". It requires that the feature "Automate/advanced management suite" (FC 0020) is installed and enabled, and fails otherwise. This method will also fail if the CPC is under group control. Whether a CPC currently allows this method is described in the "cpc-power-cap-allowed" property of the CPC. Authorization requirements: * Object-access permission to this CPC. * Task permission for the "Power Capping" task. Parameters: power_capping_state (:term:`string`): The power capping state to be set, with the possible values: * "disabled" - The power cap of the CPC is not set and the peak power consumption is not limited. This is the default setting. * "enabled" - The peak power consumption of the CPC is limited to the specified power cap value. * "custom" - Individually configure the components for power capping. No component settings are actually changed when this mode is entered. power_cap (:term:`integer`): The power cap value to be set, as a power consumption in Watt. This parameter is required not to be `None` if `power_capping_state="enabled"`. The specified value must be between the values of the CPC properties "cpc-power-cap-minimum" and "cpc-power-cap-maximum". wait_for_completion (bool): Boolean controlling whether this method should wait for completion of the requested asynchronous HMC operation, as follows: * If `True`, this method will wait for completion of the asynchronous job performing the operation. * If `False`, this method will return immediately once the HMC has accepted the request to perform the operation. operation_timeout (:term:`number`): Timeout in seconds, for waiting for completion of the asynchronous job performing the operation. The special value 0 means that no timeout is set. `None` means that the default async operation timeout of the session is used. If the timeout expires when `wait_for_completion=True`, a :exc:`~zhmcclient.OperationTimeout` is raised. Returns: `None` or :class:`~zhmcclient.Job`: If `wait_for_completion` is `True`, returns `None`. If `wait_for_completion` is `False`, returns a :class:`~zhmcclient.Job` object representing the asynchronously executing job on the HMC. Raises: :exc:`~zhmcclient.HTTPError`: See the HTTP status and reason codes of operation "Set CPC Power Save" in the :term:`HMC API` book. :exc:`~zhmcclient.ParseError` :exc:`~zhmcclient.AuthError` :exc:`~zhmcclient.ConnectionError` :exc:`~zhmcclient.OperationTimeout`: The timeout expired while waiting for completion of the operation. """ body = {'power-capping-state': power_capping_state} if power_cap is not None: body['power-cap-current'] = power_cap result = self.manager.session.post( self.uri + '/operations/set-cpc-power-capping', body, wait_for_completion=wait_for_completion, operation_timeout=operation_timeout) if wait_for_completion: # The HMC API book does not document what the result data of the # completed job is. Just in case there is similar behavior to the # "Set CPC Power Save" operation, we transform that to None. # TODO: Verify job result of a completed "Set CPC Power Capping". return None return result
python
{ "resource": "" }
q15136
Cpc.get_energy_management_properties
train
def get_energy_management_properties(self): """ Return the energy management properties of the CPC. The returned energy management properties are a subset of the properties of the CPC resource, and are also available as normal properties of the CPC resource. In so far, there is no new data provided by this method. However, because only a subset of the properties is returned, this method is faster than retrieving the complete set of CPC properties (e.g. via :meth:`~zhmcclient.BaseResource.pull_full_properties`). This method performs the HMC operation "Get CPC Energy Management Data", and returns only the energy management properties for this CPC from the operation result. Note that in non-ensemble mode of a CPC, the HMC operation result will only contain data for the CPC alone. It requires that the feature "Automate/advanced management suite" (FC 0020) is installed and enabled, and returns empty values for most properties, otherwise. Authorization requirements: * Object-access permission to this CPC. Returns: dict: A dictionary of properties of the CPC that are related to energy management. For details, see section "Energy management related additional properties" in the data model for the CPC resource in the :term:`HMC API` book. Raises: :exc:`~zhmcclient.HTTPError`: See the HTTP status and reason codes of operation "Get CPC Energy Management Data" in the :term:`HMC API` book. :exc:`~zhmcclient.ParseError`: Also raised by this method when the JSON response could be parsed but contains inconsistent data. :exc:`~zhmcclient.AuthError` :exc:`~zhmcclient.ConnectionError` """ result = self.manager.session.get(self.uri + '/energy-management-data') em_list = result['objects'] if len(em_list) != 1: uris = [em_obj['object-uri'] for em_obj in em_list] raise ParseError("Energy management data returned for no resource " "or for more than one resource: %r" % uris) em_cpc_obj = em_list[0] if em_cpc_obj['object-uri'] != self.uri: raise ParseError("Energy management data returned for an " "unexpected resource: %r" % em_cpc_obj['object-uri']) if em_cpc_obj['error-occurred']: raise ParseError("Errors occurred when retrieving energy " "management data for CPC. Operation result: %r" % result) cpc_props = em_cpc_obj['properties'] return cpc_props
python
{ "resource": "" }
q15137
Cpc.validate_lun_path
train
def validate_lun_path(self, host_wwpn, host_port, wwpn, lun): """ Validate if an FCP storage volume on an actual storage subsystem is reachable from this CPC, through a specified host port and using a specified host WWPN. This method performs the "Validate LUN Path" HMC operation. If the volume is reachable, the method returns. If the volume is not reachable (and no other errors occur), an :exc:`~zhmcclient.HTTPError` is raised, and its :attr:`~zhmcclient.HTTPError.reason` property indicates the reason as follows: * 484: Target WWPN cannot be reached. * 485: Target WWPN can be reached, but LUN cannot be reached. The CPC must have the "dpm-storage-management" feature enabled. Parameters: host_wwpn (:term:`string`): World wide port name (WWPN) of the host (CPC), as a hexadecimal number of up to 16 characters in any lexical case. This may be the WWPN of the physical storage port, or a WWPN of a virtual HBA. In any case, it must be the kind of WWPN that is used for zoning and LUN masking in the SAN. host_port (:class:`~zhmcclient.Port`): Storage port on the CPC that will be used for validating reachability. wwpn (:term:`string`): World wide port name (WWPN) of the FCP storage subsystem containing the storage volume, as a hexadecimal number of up to 16 characters in any lexical case. lun (:term:`string`): Logical Unit Number (LUN) of the storage volume within its FCP storage subsystem, as a hexadecimal number of up to 16 characters in any lexical case. Authorization requirements: * Object-access permission to the storage group owning this storage volume. * Task permission to the "Configure Storage - Storage Administrator" task. Raises: :exc:`~zhmcclient.HTTPError` :exc:`~zhmcclient.ParseError` :exc:`~zhmcclient.AuthError` :exc:`~zhmcclient.ConnectionError` """ # The operation requires exactly 16 characters in lower case host_wwpn_16 = format(int(host_wwpn, 16), '016x') wwpn_16 = format(int(wwpn, 16), '016x') lun_16 = format(int(lun, 16), '016x') body = { 'host-world-wide-port-name': host_wwpn_16, 'adapter-port-uri': host_port.uri, 'target-world-wide-port-name': wwpn_16, 'logical-unit-number': lun_16, } self.manager.session.post( self.uri + '/operations/validate-lun-path', body=body)
python
{ "resource": "" }
q15138
UserPatternManager.reorder
train
def reorder(self, user_patterns): """ Reorder the User Patterns of the HMC as specified. The order of User Patterns determines the search order during logon processing. Authorization requirements: * Task permission to the "Manage User Patterns" task. Parameters: user_patterns (list of :class:`~zhmcclient.UserPattern`): The User Patterns in the desired order. Must not be `None`. Raises: :exc:`~zhmcclient.HTTPError` :exc:`~zhmcclient.ParseError` :exc:`~zhmcclient.AuthError` :exc:`~zhmcclient.ConnectionError` """ # noqa: E501 body = { 'user-pattern-uris': [up.uri for up in user_patterns] } self.manager.session.post( '/api/console/operations/reorder-user-patterns', body=body)
python
{ "resource": "" }
q15139
TimeStats.reset
train
def reset(self): """ Reset the time statistics data for the operation. """ self._count = 0 self._sum = float(0) self._min = float('inf') self._max = float(0)
python
{ "resource": "" }
q15140
TimeStatsKeeper.get_stats
train
def get_stats(self, name): """ Get the time statistics for a name. If a time statistics for that name does not exist yet, create one. Parameters: name (string): Name of the time statistics. Returns: TimeStats: The time statistics for the specified name. If the statistics keeper is disabled, a dummy time statistics object is returned, in order to save resources. """ if not self.enabled: return self._disabled_stats if name not in self._time_stats: self._time_stats[name] = TimeStats(self, name) return self._time_stats[name]
python
{ "resource": "" }
q15141
UnmanagedCpcManager.list
train
def list(self, full_properties=False, filter_args=None): """ List the unmanaged CPCs exposed by the HMC this client is connected to. Because the CPCs are unmanaged, the returned :class:`~zhmcclient.UnmanagedCpc` objects cannot perform any operations and will have only the following properties: * ``object-uri`` * ``name`` Authorization requirements: * None Parameters: full_properties (bool): Ignored (exists for consistency with other list() methods). filter_args (dict): Filter arguments that narrow the list of returned resources to those that match the specified filter arguments. For details, see :ref:`Filtering`. `None` causes no filtering to happen, i.e. all resources are returned. Returns: : A list of :class:`~zhmcclient.UnmanagedCpc` objects. Raises: :exc:`~zhmcclient.HTTPError` :exc:`~zhmcclient.ParseError` :exc:`~zhmcclient.AuthError` :exc:`~zhmcclient.ConnectionError` """ resource_obj_list = [] resource_obj = self._try_optimized_lookup(filter_args) if resource_obj: resource_obj_list.append(resource_obj) else: query_parms, client_filters = self._divide_filter_args(filter_args) uri = self.parent.uri + '/operations/list-unmanaged-cpcs' + \ query_parms result = self.session.get(uri) if result: props_list = result['cpcs'] for props in props_list: resource_obj = self.resource_class( manager=self, uri=props[self._uri_prop], name=props.get(self._name_prop, None), properties=props) if self._matches_filters(resource_obj, client_filters): resource_obj_list.append(resource_obj) self._name_uri_cache.update_from(resource_obj_list) return resource_obj_list
python
{ "resource": "" }
q15142
parse_query_parms
train
def parse_query_parms(method, uri, query_str): """ Parse the specified query parms string and return a dictionary of query parameters. The key of each dict item is the query parameter name, and the value of each dict item is the query parameter value. If a query parameter shows up more than once, the resulting dict item value is a list of all those values. query_str is the query string from the URL, everything after the '?'. If it is empty or None, None is returned. If a query parameter is not of the format "name=value", an HTTPError 400,1 is raised. """ if not query_str: return None query_parms = {} for query_item in query_str.split('&'): # Example for these items: 'name=a%20b' if query_item == '': continue items = query_item.split('=') if len(items) != 2: raise BadRequestError( method, uri, reason=1, message="Invalid format for URI query parameter: {!r} " "(valid format is: 'name=value').". format(query_item)) name = unquote(items[0]) value = unquote(items[1]) if name in query_parms: existing_value = query_parms[name] if not isinstance(existing_value, list): query_parms[name] = list() query_parms[name].append(existing_value) query_parms[name].append(value) else: query_parms[name] = value return query_parms
python
{ "resource": "" }
q15143
check_required_fields
train
def check_required_fields(method, uri, body, field_names): """ Check required fields in the request body. Raises: BadRequestError with reason 3: Missing request body BadRequestError with reason 5: Missing required field in request body """ # Check presence of request body if body is None: raise BadRequestError(method, uri, reason=3, message="Missing request body") # Check required input fields for field_name in field_names: if field_name not in body: raise BadRequestError(method, uri, reason=5, message="Missing required field in request " "body: {}".format(field_name))
python
{ "resource": "" }
q15144
check_valid_cpc_status
train
def check_valid_cpc_status(method, uri, cpc): """ Check that the CPC is in a valid status, as indicated by its 'status' property. If the Cpc object does not have a 'status' property set, this function does nothing (in order to make the mock support easy to use). Raises: ConflictError with reason 1: The CPC itself has been targeted by the operation. ConflictError with reason 6: The CPC is hosting the resource targeted by the operation. """ status = cpc.properties.get('status', None) if status is None: # Do nothing if no status is set on the faked CPC return valid_statuses = ['active', 'service-required', 'degraded', 'exceptions'] if status not in valid_statuses: if uri.startswith(cpc.uri): # The uri targets the CPC (either is the CPC uri or some # multiplicity under the CPC uri) raise ConflictError(method, uri, reason=1, message="The operation cannot be performed " "because the targeted CPC {} has a status " "that is not valid for the operation: {}". format(cpc.name, status)) else: # The uri targets a resource hosted by the CPC raise ConflictError(method, uri, reason=6, message="The operation cannot be performed " "because CPC {} hosting the targeted resource " "has a status that is not valid for the " "operation: {}". format(cpc.name, status))
python
{ "resource": "" }
q15145
ensure_crypto_config
train
def ensure_crypto_config(partition): """ Ensure that the 'crypto-configuration' property on the faked partition is initialized. """ if 'crypto-configuration' not in partition.properties or \ partition.properties['crypto-configuration'] is None: partition.properties['crypto-configuration'] = {} crypto_config = partition.properties['crypto-configuration'] if 'crypto-adapter-uris' not in crypto_config or \ crypto_config['crypto-adapter-uris'] is None: crypto_config['crypto-adapter-uris'] = [] adapter_uris = crypto_config['crypto-adapter-uris'] if 'crypto-domain-configurations' not in crypto_config or \ crypto_config['crypto-domain-configurations'] is None: crypto_config['crypto-domain-configurations'] = [] domain_configs = crypto_config['crypto-domain-configurations'] return adapter_uris, domain_configs
python
{ "resource": "" }
q15146
PartitionManager.create
train
def create(self, properties): """ Create and configure a Partition in this CPC. Authorization requirements: * Object-access permission to this CPC. * Task permission to the "New Partition" task. Parameters: properties (dict): Initial property values. Allowable properties are defined in section 'Request body contents' in section 'Create Partition' in the :term:`HMC API` book. Returns: Partition: The resource object for the new Partition. The object will have its 'object-uri' property set as returned by the HMC, and will also have the input properties set. Raises: :exc:`~zhmcclient.HTTPError` :exc:`~zhmcclient.ParseError` :exc:`~zhmcclient.AuthError` :exc:`~zhmcclient.ConnectionError` """ result = self.session.post(self.cpc.uri + '/partitions', body=properties) # There should not be overlaps, but just in case there are, the # returned props should overwrite the input props: props = copy.deepcopy(properties) props.update(result) name = props.get(self._name_prop, None) uri = props[self._uri_prop] part = Partition(self, uri, name, props) self._name_uri_cache.update(name, uri) return part
python
{ "resource": "" }
q15147
Partition.feature_enabled
train
def feature_enabled(self, feature_name): """ Indicates whether the specified feature is enabled for the CPC of this partition. The HMC must generally support features, and the specified feature must be available for the CPC. For a list of available features, see section "Features" in the :term:`HMC API`, or use the :meth:`feature_info` method. Authorization requirements: * Object-access permission to this partition. Parameters: feature_name (:term:`string`): The name of the feature. Returns: bool: `True` if the feature is enabled, or `False` if the feature is disabled (but available). Raises: :exc:`ValueError`: Features are not supported on the HMC. :exc:`ValueError`: The specified feature is not available for the CPC. :exc:`~zhmcclient.HTTPError` :exc:`~zhmcclient.ParseError` :exc:`~zhmcclient.AuthError` :exc:`~zhmcclient.ConnectionError` """ feature_list = self.prop('available-features-list', None) if feature_list is None: raise ValueError("Firmware features are not supported on CPC %s" % self.manager.cpc.name) for feature in feature_list: if feature['name'] == feature_name: break else: raise ValueError("Firmware feature %s is not available on CPC %s" % (feature_name, self.manager.cpc.name)) return feature['state']
python
{ "resource": "" }
q15148
Partition.feature_info
train
def feature_info(self): """ Returns information about the features available for the CPC of this partition. Authorization requirements: * Object-access permission to this partition. Returns: :term:`iterable`: An iterable where each item represents one feature that is available for the CPC of this partition. Each item is a dictionary with the following items: * `name` (:term:`unicode string`): Name of the feature. * `description` (:term:`unicode string`): Short description of the feature. * `state` (bool): Enablement state of the feature (`True` if the enabled, `False` if disabled). Raises: :exc:`ValueError`: Features are not supported on the HMC. :exc:`~zhmcclient.HTTPError` :exc:`~zhmcclient.ParseError` :exc:`~zhmcclient.AuthError` :exc:`~zhmcclient.ConnectionError` """ feature_list = self.prop('available-features-list', None) if feature_list is None: raise ValueError("Firmware features are not supported on CPC %s" % self.manager.cpc.name) return feature_list
python
{ "resource": "" }
q15149
Partition.dump_partition
train
def dump_partition(self, parameters, wait_for_completion=True, operation_timeout=None): """ Dump this Partition, by loading a standalone dump program from a SCSI device and starting its execution, using the HMC operation 'Dump Partition'. Authorization requirements: * Object-access permission to this Partition. * Task permission to the "Dump Partition" task. Parameters: parameters (dict): Input parameters for the operation. Allowable input parameters are defined in section 'Request body contents' in section 'Dump Partition' in the :term:`HMC API` book. wait_for_completion (bool): Boolean controlling whether this method should wait for completion of the requested asynchronous HMC operation, as follows: * If `True`, this method will wait for completion of the asynchronous job performing the operation. * If `False`, this method will return immediately once the HMC has accepted the request to perform the operation. operation_timeout (:term:`number`): Timeout in seconds, for waiting for completion of the asynchronous job performing the operation. The special value 0 means that no timeout is set. `None` means that the default async operation timeout of the session is used. If the timeout expires when `wait_for_completion=True`, a :exc:`~zhmcclient.OperationTimeout` is raised. Returns: :class:`py:dict` or :class:`~zhmcclient.Job`: If `wait_for_completion` is `True`, returns an empty :class:`py:dict` object. If `wait_for_completion` is `False`, returns a :class:`~zhmcclient.Job` object representing the asynchronously executing job on the HMC. Raises: :exc:`~zhmcclient.HTTPError` :exc:`~zhmcclient.ParseError` :exc:`~zhmcclient.AuthError` :exc:`~zhmcclient.ConnectionError` :exc:`~zhmcclient.OperationTimeout`: The timeout expired while waiting for completion of the operation. """ result = self.manager.session.post( self.uri + '/operations/scsi-dump', wait_for_completion=wait_for_completion, operation_timeout=operation_timeout, body=parameters) return result
python
{ "resource": "" }
q15150
Partition.mount_iso_image
train
def mount_iso_image(self, image, image_name, ins_file_name): """ Upload an ISO image and associate it to this Partition using the HMC operation 'Mount ISO Image'. When the partition already has an ISO image associated, the newly uploaded image replaces the current one. Authorization requirements: * Object-access permission to this Partition. * Task permission to the "Partition Details" task. Parameters: image (:term:`byte string` or file-like object): The content of the ISO image. Images larger than 2GB cannot be specified as a Byte string; they must be specified as a file-like object. File-like objects must have opened the file in binary mode. image_name (:term:`string`): The displayable name of the image. This value must be a valid Linux file name without directories, must not contain blanks, and must end with '.iso' in lower case. This value will be shown in the 'boot-iso-image-name' property of this partition. ins_file_name (:term:`string`): The path name of the INS file within the file system of the ISO image. This value will be shown in the 'boot-iso-ins-file' property of this partition. Raises: :exc:`~zhmcclient.HTTPError` :exc:`~zhmcclient.ParseError` :exc:`~zhmcclient.AuthError` :exc:`~zhmcclient.ConnectionError` """ query_parms_str = '?image-name={}&ins-file-name={}'. \ format(quote(image_name, safe=''), quote(ins_file_name, safe='')) self.manager.session.post( self.uri + '/operations/mount-iso-image' + query_parms_str, body=image)
python
{ "resource": "" }
q15151
Partition.open_os_message_channel
train
def open_os_message_channel(self, include_refresh_messages=True): """ Open a JMS message channel to this partition's operating system, returning the string "topic" representing the message channel. Parameters: include_refresh_messages (bool): Boolean controlling whether refresh operating systems messages should be sent, as follows: * If `True`, refresh messages will be recieved when the user connects to the topic. The default. * If `False`, refresh messages will not be recieved when the user connects to the topic. Returns: :term:`string`: Returns a string representing the os-message-notification JMS topic. The user can connect to this topic to start the flow of operating system messages. Raises: :exc:`~zhmcclient.HTTPError` :exc:`~zhmcclient.ParseError` :exc:`~zhmcclient.AuthError` :exc:`~zhmcclient.ConnectionError` """ body = {'include-refresh-messages': include_refresh_messages} result = self.manager.session.post( self.uri + '/operations/open-os-message-channel', body) return result['topic-name']
python
{ "resource": "" }
q15152
Partition.send_os_command
train
def send_os_command(self, os_command_text, is_priority=False): """ Send a command to the operating system running in this partition. Parameters: os_command_text (string): The text of the operating system command. is_priority (bool): Boolean controlling whether this is a priority operating system command, as follows: * If `True`, this message is treated as a priority operating system command. * If `False`, this message is not treated as a priority operating system command. The default. Returns: None Raises: :exc:`~zhmcclient.HTTPError` :exc:`~zhmcclient.ParseError` :exc:`~zhmcclient.AuthError` :exc:`~zhmcclient.ConnectionError` """ body = {'is-priority': is_priority, 'operating-system-command-text': os_command_text} self.manager.session.post( self.uri + '/operations/send-os-cmd', body)
python
{ "resource": "" }
q15153
Partition.wait_for_status
train
def wait_for_status(self, status, status_timeout=None): """ Wait until the status of this partition has a desired value. Parameters: status (:term:`string` or iterable of :term:`string`): Desired partition status or set of status values to reach; one or more of the values defined for the 'status' property in the data model for partitions in the :term:`HMC API` book. status_timeout (:term:`number`): Timeout in seconds, for waiting that the status of the partition has reached one of the desired status values. The special value 0 means that no timeout is set. `None` means that the default status timeout will be used. If the timeout expires, a :exc:`~zhmcclient.StatusTimeout` is raised. Raises: :exc:`~zhmcclient.HTTPError` :exc:`~zhmcclient.ParseError` :exc:`~zhmcclient.AuthError` :exc:`~zhmcclient.ConnectionError` :exc:`~zhmcclient.StatusTimeout`: The status timeout expired while waiting for the desired partition status. """ if status_timeout is None: status_timeout = \ self.manager.session.retry_timeout_config.status_timeout if status_timeout > 0: end_time = time.time() + status_timeout if isinstance(status, (list, tuple)): statuses = status else: statuses = [status] while True: # Fastest way to get actual status value: parts = self.manager.cpc.partitions.list( filter_args={'name': self.name}) assert len(parts) == 1 this_part = parts[0] actual_status = this_part.get_property('status') if actual_status in statuses: return if status_timeout > 0 and time.time() > end_time: raise StatusTimeout( "Waiting for partition {} to reach status(es) '{}' timed " "out after {} s - current status is '{}'". format(self.name, statuses, status_timeout, actual_status), actual_status, statuses, status_timeout) time.sleep(1)
python
{ "resource": "" }
q15154
Partition.change_crypto_domain_config
train
def change_crypto_domain_config(self, crypto_domain_index, access_mode): """ Change the access mode for a crypto domain that is currently included in the crypto configuration of this partition. The access mode will be changed for the specified crypto domain on all crypto adapters currently included in the crypto configuration of this partition. For the general principle for maintaining crypto configurations of partitions, see :meth:`~zhmcclient.Partition.increase_crypto_config`. Authorization requirements: * Object-access permission to this Partition. * Task permission to the "Partition Details" task. Parameters: crypto_domain_index (:term:`integer`): Domain index of the crypto domain to be changed. For values, see :meth:`~zhmcclient.Partition.increase_crypto_config`. access_mode (:term:`string`): The new access mode for the crypto domain. For values, see :meth:`~zhmcclient.Partition.increase_crypto_config`. Raises: :exc:`~zhmcclient.HTTPError` :exc:`~zhmcclient.ParseError` :exc:`~zhmcclient.AuthError` :exc:`~zhmcclient.ConnectionError` """ body = {'domain-index': crypto_domain_index, 'access-mode': access_mode} self.manager.session.post( self.uri + '/operations/change-crypto-domain-configuration', body)
python
{ "resource": "" }
q15155
Partition.zeroize_crypto_domain
train
def zeroize_crypto_domain(self, crypto_adapter, crypto_domain_index): """ Zeroize a single crypto domain on a crypto adapter. Zeroizing a crypto domain clears the cryptographic keys and non-compliance mode settings in the crypto domain. The crypto domain must be attached to this partition in "control-usage" access mode. Supported CPC versions: z14 GA2 and above, and the corresponding LinuxOne systems. Authorization requirements: * Object-access permission to this Partition and to the Crypto Adapter. * Task permission to the "Zeroize Crypto Domain" task. Parameters: crypto_adapter (:class:`~zhmcclient.Adapter`): Crypto adapter with the crypto domain to be zeroized. crypto_domain_index (:term:`integer`): Domain index of the crypto domain to be zeroized. Raises: :exc:`~zhmcclient.HTTPError` :exc:`~zhmcclient.ParseError` :exc:`~zhmcclient.AuthError` :exc:`~zhmcclient.ConnectionError` """ body = { 'crypto-adapter-uri': crypto_adapter.uri, 'domain-index': crypto_domain_index } self.manager.session.post( self.uri + '/operations/zeroize-crypto-domain', body)
python
{ "resource": "" }
q15156
Partition.list_attached_storage_groups
train
def list_attached_storage_groups(self, full_properties=False): """ Return the storage groups that are attached to this partition. The CPC must have the "dpm-storage-management" feature enabled. Authorization requirements: * Object-access permission to this partition. * Task permission to the "Partition Details" task. Parameters: full_properties (bool): Controls that the full set of resource properties for each returned storage group is being retrieved, vs. only the following short set: "object-uri", "object-id", "class", "parent". TODO: Verify short list of properties. Returns: List of :class:`~zhmcclient.StorageGroup` objects representing the storage groups that are attached to this partition. Raises: :exc:`~zhmcclient.HTTPError` :exc:`~zhmcclient.ParseError` :exc:`~zhmcclient.AuthError` :exc:`~zhmcclient.ConnectionError` """ sg_list = [] sg_uris = self.get_property('storage-group-uris') if sg_uris: cpc = self.manager.cpc for sg_uri in sg_uris: sg = cpc.storage_groups.resource_object(sg_uri) sg_list.append(sg) if full_properties: sg.pull_full_properties() return sg_list
python
{ "resource": "" }
q15157
PasswordRule.update_properties
train
def update_properties(self, properties): """ Update writeable properties of this PasswordRule. The Password Rule must be user-defined. System-defined Password Rules cannot be updated. Authorization requirements: * Task permission to the "Manage Password Rules" task. Parameters: properties (dict): New values for the properties to be updated. Properties not to be updated are omitted. Allowable properties are the properties with qualifier (w) in section 'Data model' in section 'Password Rule object' in the :term:`HMC API` book. Raises: :exc:`~zhmcclient.HTTPError` :exc:`~zhmcclient.ParseError` :exc:`~zhmcclient.AuthError` :exc:`~zhmcclient.ConnectionError` """ self.manager.session.post(self.uri, body=properties) # The name of Password Rules cannot be updated. An attempt to do so # should cause HTTPError to be raised in the POST above, so we assert # that here, because we omit the extra code for handling name updates: assert self.manager._name_prop not in properties self.properties.update(copy.deepcopy(properties))
python
{ "resource": "" }
q15158
Client.version_info
train
def version_info(self): """ Returns API version information for the HMC. This operation does not require authentication. Returns: :term:`HMC API version`: The HMC API version supported by the HMC. Raises: :exc:`~zhmcclient.HTTPError` :exc:`~zhmcclient.ParseError` :exc:`~zhmcclient.ConnectionError` """ if self._api_version is None: self.query_api_version() return self._api_version['api-major-version'],\ self._api_version['api-minor-version']
python
{ "resource": "" }
q15159
Client.query_api_version
train
def query_api_version(self): """ The Query API Version operation returns information about the level of Web Services API supported by the HMC. This operation does not require authentication. Returns: :term:`json object`: A JSON object with members ``api-major-version``, ``api-minor-version``, ``hmc-version`` and ``hmc-name``. For details about these properties, see section 'Response body contents' in section 'Query API Version' in the :term:`HMC API` book. Raises: :exc:`~zhmcclient.HTTPError` :exc:`~zhmcclient.ParseError` :exc:`~zhmcclient.ConnectionError` """ version_resp = self._session.get('/api/version', logon_required=False) self._api_version = version_resp return self._api_version
python
{ "resource": "" }
q15160
Client.get_inventory
train
def get_inventory(self, resources): """ Returns a JSON object with the requested resources and their properties, that are managed by the HMC. This method performs the 'Get Inventory' HMC operation. Parameters: resources (:term:`iterable` of :term:`string`): Resource classes and/or resource classifiers specifying the types of resources that should be included in the result. For valid values, see the 'Get Inventory' operation in the :term:`HMC API` book. Element resources of the specified resource types are automatically included as children (for example, requesting 'partition' includes all of its 'hba', 'nic' and 'virtual-function' element resources). Must not be `None`. Returns: :term:`JSON object`: The resources with their properties, for the requested resource classes and resource classifiers. Example: resource_classes = ['partition', 'adapter'] result_dict = client.get_inventory(resource_classes) Raises: :exc:`~zhmcclient.HTTPError` :exc:`~zhmcclient.ParseError` :exc:`~zhmcclient.ConnectionError` """ uri = '/api/services/inventory' body = {'resources': resources} result = self.session.post(uri, body=body) return result
python
{ "resource": "" }
q15161
BaseResource.pull_full_properties
train
def pull_full_properties(self): """ Retrieve the full set of resource properties and cache them in this object. Authorization requirements: * Object-access permission to this resource. Raises: :exc:`~zhmcclient.HTTPError` :exc:`~zhmcclient.ParseError` :exc:`~zhmcclient.AuthError` :exc:`~zhmcclient.ConnectionError` """ full_properties = self.manager.session.get(self._uri) self._properties = dict(full_properties) self._properties_timestamp = int(time.time()) self._full_properties = True
python
{ "resource": "" }
q15162
BaseResource.get_property
train
def get_property(self, name): """ Return the value of a resource property. If the resource property is not cached in this object yet, the full set of resource properties is retrieved and cached in this object, and the resource property is again attempted to be returned. Authorization requirements: * Object-access permission to this resource. Parameters: name (:term:`string`): Name of the resource property, using the names defined in the respective 'Data model' sections in the :term:`HMC API` book. Returns: The value of the resource property. Raises: KeyError: The resource property could not be found (also not in the full set of resource properties). :exc:`~zhmcclient.HTTPError` :exc:`~zhmcclient.ParseError` :exc:`~zhmcclient.AuthError` :exc:`~zhmcclient.ConnectionError` """ try: return self._properties[name] except KeyError: if self._full_properties: raise self.pull_full_properties() return self._properties[name]
python
{ "resource": "" }
q15163
make_client
train
def make_client(zhmc, userid=None, password=None): """ Create a `Session` object for the specified HMC and log that on. Create a `Client` object using that `Session` object, and return it. If no userid and password are specified, and if no previous call to this method was made, userid and password are interactively inquired. Userid and password are saved in module-global variables for future calls to this method. """ global USERID, PASSWORD # pylint: disable=global-statement USERID = userid or USERID or \ six.input('Enter userid for HMC {}: '.format(zhmc)) PASSWORD = password or PASSWORD or \ getpass.getpass('Enter password for {}: '.format(USERID)) session = zhmcclient.Session(zhmc, USERID, PASSWORD) session.logon() client = zhmcclient.Client(session) print('Established logged-on session with HMC {} using userid {}'. format(zhmc, USERID)) return client
python
{ "resource": "" }
q15164
repr_list
train
def repr_list(_list, indent): """Return a debug representation of a list or tuple.""" # pprint represents lists and tuples in one row if possible. We want one # per row, so we iterate ourselves. if _list is None: return 'None' if isinstance(_list, MutableSequence): bm = '[' em = ']' elif isinstance(_list, Iterable): bm = '(' em = ')' else: raise TypeError("Object must be an iterable, but is a %s" % type(_list)) ret = bm + '\n' for value in _list: ret += _indent('%r,\n' % value, 2) ret += em ret = repr_text(ret, indent=indent) return ret.lstrip(' ')
python
{ "resource": "" }
q15165
repr_dict
train
def repr_dict(_dict, indent): """Return a debug representation of a dict or OrderedDict.""" # pprint represents OrderedDict objects using the tuple init syntax, # which is not very readable. Therefore, dictionaries are iterated over. if _dict is None: return 'None' if not isinstance(_dict, Mapping): raise TypeError("Object must be a mapping, but is a %s" % type(_dict)) if isinstance(_dict, OrderedDict): kind = 'ordered' ret = '%s {\n' % kind # non standard syntax for the kind indicator for key in six.iterkeys(_dict): value = _dict[key] ret += _indent('%r: %r,\n' % (key, value), 2) else: # dict kind = 'sorted' ret = '%s {\n' % kind # non standard syntax for the kind indicator for key in sorted(six.iterkeys(_dict)): value = _dict[key] ret += _indent('%r: %r,\n' % (key, value), 2) ret += '}' ret = repr_text(ret, indent=indent) return ret.lstrip(' ')
python
{ "resource": "" }
q15166
repr_timestamp
train
def repr_timestamp(timestamp): """Return a debug representation of an HMC timestamp number.""" if timestamp is None: return 'None' dt = datetime_from_timestamp(timestamp) ret = "%d (%s)" % (timestamp, dt.strftime('%Y-%m-%d %H:%M:%S.%f %Z')) return ret
python
{ "resource": "" }
q15167
StorageGroupManager.create
train
def create(self, properties): """ Create and configure a storage group. The new storage group will be associated with the CPC identified by the `cpc-uri` input property. Authorization requirements: * Object-access permission to the CPC that will be associated with the new storage group. * Task permission to the "Configure Storage - System Programmer" task. Parameters: properties (dict): Initial property values. Allowable properties are defined in section 'Request body contents' in section 'Create Storage Group' in the :term:`HMC API` book. The 'cpc-uri' property identifies the CPC to which the new storage group will be associated, and is required to be specified in this parameter. Returns: :class:`~zhmcclient.StorageGroup`: The resource object for the new storage group. The object will have its 'object-uri' property set as returned by the HMC, and will also have the input properties set. Raises: :exc:`~zhmcclient.HTTPError` :exc:`~zhmcclient.ParseError` :exc:`~zhmcclient.AuthError` :exc:`~zhmcclient.ConnectionError` """ if properties is None: properties = {} result = self.session.post(self._base_uri, body=properties) # There should not be overlaps, but just in case there are, the # returned props should overwrite the input props: props = copy.deepcopy(properties) props.update(result) name = props.get(self._name_prop, None) uri = props[self._uri_prop] storage_group = StorageGroup(self, uri, name, props) self._name_uri_cache.update(name, uri) return storage_group
python
{ "resource": "" }
q15168
StorageGroup.list_attached_partitions
train
def list_attached_partitions(self, name=None, status=None): """ Return the partitions to which this storage group is currently attached, optionally filtered by partition name and status. Authorization requirements: * Object-access permission to this storage group. * Task permission to the "Configure Storage - System Programmer" task. Parameters: name (:term:`string`): Filter pattern (regular expression) to limit returned partitions to those that have a matching name. If `None`, no filtering for the partition name takes place. status (:term:`string`): Filter string to limit returned partitions to those that have a matching status. The value must be a valid partition status property value. If `None`, no filtering for the partition status takes place. Returns: List of :class:`~zhmcclient.Partition` objects representing the partitions to whivch this storage group is currently attached, with a minimal set of properties ('object-id', 'name', 'status'). Raises: :exc:`~zhmcclient.HTTPError` :exc:`~zhmcclient.ParseError` :exc:`~zhmcclient.AuthError` :exc:`~zhmcclient.ConnectionError` """ query_parms = [] if name is not None: self.manager._append_query_parms(query_parms, 'name', name) if status is not None: self.manager._append_query_parms(query_parms, 'status', status) query_parms_str = '&'.join(query_parms) if query_parms_str: query_parms_str = '?{}'.format(query_parms_str) uri = '{}/operations/get-partitions{}'.format( self.uri, query_parms_str) sg_cpc = self.cpc part_mgr = sg_cpc.partitions result = self.manager.session.get(uri) props_list = result['partitions'] part_list = [] for props in props_list: part = part_mgr.resource_object(props['object-uri'], props) part_list.append(part) return part_list
python
{ "resource": "" }
q15169
StorageGroup.add_candidate_adapter_ports
train
def add_candidate_adapter_ports(self, ports): """ Add a list of storage adapter ports to this storage group's candidate adapter ports list. This operation only applies to storage groups of type "fcp". These adapter ports become candidates for use as backing adapters when creating virtual storage resources when the storage group is attached to a partition. The adapter ports should have connectivity to the storage area network (SAN). Candidate adapter ports may only be added before the CPC discovers a working communications path, indicated by a "verified" status on at least one of this storage group's WWPNs. After that point, all adapter ports in the storage group are automatically detected and manually adding them is no longer possible. Because the CPC discovers working communications paths automatically, candidate adapter ports do not need to be added by the user. Any ports that are added, are validated by the CPC during discovery, and may or may not actually be used. Authorization requirements: * Object-access permission to this storage group. * Object-access permission to the adapter of each specified port. * Task permission to the "Configure Storage - System Programmer" task. Parameters: ports (:class:`py:list`): List of :class:`~zhmcclient.Port` objects representing the ports to be added. All specified ports must not already be members of this storage group's candidate adapter ports list. Raises: :exc:`~zhmcclient.HTTPError` :exc:`~zhmcclient.ParseError` :exc:`~zhmcclient.AuthError` :exc:`~zhmcclient.ConnectionError` """ body = { 'adapter-port-uris': [p.uri for p in ports], } self.manager.session.post( self.uri + '/operations/add-candidate-adapter-ports', body=body)
python
{ "resource": "" }
q15170
StorageGroup.list_candidate_adapter_ports
train
def list_candidate_adapter_ports(self, full_properties=False): """ Return the current candidate storage adapter port list of this storage group. The result reflects the actual list of ports used by the CPC, including any changes that have been made during discovery. The source for this information is the 'candidate-adapter-port-uris' property of the storage group object. Parameters: full_properties (bool): Controls that the full set of resource properties for each returned candidate storage adapter port is being retrieved, vs. only the following short set: "element-uri", "element-id", "class", "parent". TODO: Verify short list of properties. Returns: List of :class:`~zhmcclient.Port` objects representing the current candidate storage adapter ports of this storage group. Raises: :exc:`~zhmcclient.HTTPError` :exc:`~zhmcclient.ParseError` :exc:`~zhmcclient.AuthError` :exc:`~zhmcclient.ConnectionError` """ sg_cpc = self.cpc adapter_mgr = sg_cpc.adapters port_list = [] port_uris = self.get_property('candidate-adapter-port-uris') if port_uris: for port_uri in port_uris: m = re.match(r'^(/api/adapters/[^/]*)/.*', port_uri) adapter_uri = m.group(1) adapter = adapter_mgr.resource_object(adapter_uri) port_mgr = adapter.ports port = port_mgr.resource_object(port_uri) port_list.append(port) if full_properties: port.pull_full_properties() return port_list
python
{ "resource": "" }
q15171
AdapterManager.create_hipersocket
train
def create_hipersocket(self, properties): """ Create and configure a HiperSockets Adapter in this CPC. Authorization requirements: * Object-access permission to the scoping CPC. * Task permission to the "Create HiperSockets Adapter" task. Parameters: properties (dict): Initial property values. Allowable properties are defined in section 'Request body contents' in section 'Create Hipersocket' in the :term:`HMC API` book. Returns: :class:`~zhmcclient.Adapter`: The resource object for the new HiperSockets Adapter. The object will have its 'object-uri' property set as returned by the HMC, and will also have the input properties set. Raises: :exc:`~zhmcclient.HTTPError` :exc:`~zhmcclient.ParseError` :exc:`~zhmcclient.AuthError` :exc:`~zhmcclient.ConnectionError` """ result = self.session.post(self.cpc.uri + '/adapters', body=properties) # There should not be overlaps, but just in case there are, the # returned props should overwrite the input props: props = copy.deepcopy(properties) props.update(result) name = props.get(self._name_prop, None) uri = props[self._uri_prop] adapter = Adapter(self, uri, name, props) self._name_uri_cache.update(name, uri) return adapter
python
{ "resource": "" }
q15172
Adapter.change_crypto_type
train
def change_crypto_type(self, crypto_type, zeroize=None): """ Reconfigures a cryptographic adapter to a different crypto type. This operation is only supported for cryptographic adapters. The cryptographic adapter must be varied offline before its crypto type can be reconfigured. Authorization requirements: * Object-access permission to this Adapter. * Task permission to the "Adapter Details" task. Parameters: crypto_type (:term:`string`): - ``"accelerator"``: Crypto Express5S Accelerator - ``"cca-coprocessor"``: Crypto Express5S CCA Coprocessor - ``"ep11-coprocessor"``: Crypto Express5S EP11 Coprocessor zeroize (bool): Specifies whether the cryptographic adapter will be zeroized when it is reconfigured to a crypto type of ``"accelerator"``. `None` means that the HMC-implemented default of `True` will be used. Raises: :exc:`~zhmcclient.HTTPError` :exc:`~zhmcclient.ParseError` :exc:`~zhmcclient.AuthError` :exc:`~zhmcclient.ConnectionError` """ body = {'crypto-type': crypto_type} if zeroize is not None: body['zeroize'] = zeroize self.manager.session.post( self.uri + '/operations/change-crypto-type', body)
python
{ "resource": "" }
q15173
Lpar.stop
train
def stop(self, wait_for_completion=True, operation_timeout=None, status_timeout=None, allow_status_exceptions=False): """ Stop this LPAR, using the HMC operation "Stop Logical Partition". The stop operation stops the processors from processing instructions. This HMC operation has deferred status behavior: If the asynchronous job on the HMC is complete, it takes a few seconds until the LPAR status has reached the desired value. If `wait_for_completion=True`, this method repeatedly checks the status of the LPAR after the HMC operation has completed, and waits until the status is in the desired state "operating", or if `allow_status_exceptions` was set additionally in the state "exceptions". Authorization requirements: * Object-access permission to the CPC containing this LPAR. * Object-access permission to this LPAR. * Task permission for the "Stop" task. Parameters: wait_for_completion (bool): Boolean controlling whether this method should wait for completion of the requested asynchronous HMC operation, as follows: * If `True`, this method will wait for completion of the asynchronous job performing the operation, and for the status becoming "operating" (or in addition "exceptions", if `allow_status_exceptions` was set. * If `False`, this method will return immediately once the HMC has accepted the request to perform the operation. operation_timeout (:term:`number`): Timeout in seconds, for waiting for completion of the asynchronous job performing the operation. The special value 0 means that no timeout is set. `None` means that the default async operation timeout of the session is used. If the timeout expires when `wait_for_completion=True`, a :exc:`~zhmcclient.OperationTimeout` is raised. status_timeout (:term:`number`): Timeout in seconds, for waiting that the status of the LPAR has reached the desired status, after the HMC operation has completed. The special value 0 means that no timeout is set. `None` means that the default async operation timeout of the session is used. If the timeout expires when `wait_for_completion=True`, a :exc:`~zhmcclient.StatusTimeout` is raised. allow_status_exceptions (bool): Boolean controlling whether LPAR status "exceptions" is considered an additional acceptable end status when `wait_for_completion` is set. Returns: `None` or :class:`~zhmcclient.Job`: If `wait_for_completion` is `True`, returns `None`. If `wait_for_completion` is `False`, returns a :class:`~zhmcclient.Job` object representing the asynchronously executing job on the HMC. Raises: :exc:`~zhmcclient.HTTPError` :exc:`~zhmcclient.ParseError` :exc:`~zhmcclient.AuthError` :exc:`~zhmcclient.ConnectionError` :exc:`~zhmcclient.OperationTimeout`: The timeout expired while waiting for completion of the operation. :exc:`~zhmcclient.StatusTimeout`: The timeout expired while waiting for the desired LPAR status. """ body = {} result = self.manager.session.post( self.uri + '/operations/stop', body, wait_for_completion=wait_for_completion, operation_timeout=operation_timeout) if wait_for_completion: statuses = ["operating"] if allow_status_exceptions: statuses.append("exceptions") self.wait_for_status(statuses, status_timeout) return result
python
{ "resource": "" }
q15174
_result_object
train
def _result_object(result): """ Return the JSON payload in the HTTP response as a Python dict. Parameters: result (requests.Response): HTTP response object. Raises: zhmcclient.ParseError: Error parsing the returned JSON. """ content_type = result.headers.get('content-type', None) if content_type is None or content_type.startswith('application/json'): # This function is only called when there is content expected. # Therefore, a response without content will result in a ParseError. try: return result.json(object_pairs_hook=OrderedDict) except ValueError as exc: raise ParseError( "JSON parse error in HTTP response: {}. " "HTTP request: {} {}. " "Response status {}. " "Response content-type: {!r}. " "Content (max.1000, decoded using {}): {}". format(exc.args[0], result.request.method, result.request.url, result.status_code, content_type, result.encoding, _text_repr(result.text, 1000))) elif content_type.startswith('text/html'): # We are in some error situation. The HMC returns HTML content # for some 5xx status codes. We try to deal with it somehow, # but we are not going as far as real HTML parsing. m = re.search(r'charset=([^;,]+)', content_type) if m: encoding = m.group(1) # e.g. RFC "ISO-8859-1" else: encoding = 'utf-8' try: html_uni = result.content.decode(encoding) except LookupError: html_uni = result.content.decode() # We convert to one line to be regexp-friendly. html_oneline = html_uni.replace('\r\n', '\\n').replace('\r', '\\n').\ replace('\n', '\\n') # Check for some well-known errors: if re.search(r'javax\.servlet\.ServletException: ' r'Web Services are not enabled\.', html_oneline): html_title = "Console Configuration Error" html_details = "Web Services API is not enabled on the HMC." html_reason = HTML_REASON_WEB_SERVICES_DISABLED else: m = re.search( r'<title>([^<]*)</title>.*' r'<h2>Details:</h2>(.*)(<hr size="1" noshade>)?</body>', html_oneline) if m: html_title = m.group(1) # Spend a reasonable effort to make the HTML readable: html_details = m.group(2).replace('<p>', '\\n').\ replace('<br>', '\\n').replace('\\n\\n', '\\n').strip() else: html_title = "Console Internal Error" html_details = "Response body: {!r}".format(html_uni) html_reason = HTML_REASON_OTHER message = "{}: {}".format(html_title, html_details) # We create a minimal JSON error object (to the extent we use it # when processing it): result_obj = { 'http-status': result.status_code, 'reason': html_reason, 'message': message, 'request-uri': result.request.url, 'request-method': result.request.method, } return result_obj elif content_type.startswith('application/vnd.ibm-z-zmanager-metrics'): content_bytes = result.content assert isinstance(content_bytes, six.binary_type) return content_bytes.decode('utf-8') # as a unicode object else: raise ParseError( "Unknown content type in HTTP response: {}. " "HTTP request: {} {}. " "Response status {}. " "Response content-type: {!r}. " "Content (max.1000, decoded using {}): {}". format(content_type, result.request.method, result.request.url, result.status_code, content_type, result.encoding, _text_repr(result.text, 1000)))
python
{ "resource": "" }
q15175
RetryTimeoutConfig.override_with
train
def override_with(self, override_config): """ Return a new configuration object that represents the configuration from this configuration object acting as a default, and the specified configuration object overriding that default. Parameters: override_config (:class:`~zhmcclient.RetryTimeoutConfig`): The configuration object overriding the defaults defined in this configuration object. Returns: :class:`~zhmcclient.RetryTimeoutConfig`: A new configuration object representing this configuration object, overridden by the specified configuration object. """ ret = RetryTimeoutConfig() for attr in RetryTimeoutConfig._attrs: value = getattr(self, attr) if override_config and getattr(override_config, attr) is not None: value = getattr(override_config, attr) setattr(ret, attr, value) return ret
python
{ "resource": "" }
q15176
Session.is_logon
train
def is_logon(self, verify=False): """ Return a boolean indicating whether the session is currently logged on to the HMC. By default, this method checks whether there is a session-id set and considers that sufficient for determining that the session is logged on. The `verify` parameter can be used to verify the validity of a session-id that is already set, by issuing a dummy operation ("Get Console Properties") to the HMC. Parameters: verify (bool): If a session-id is already set, verify its validity. """ if self._session_id is None: return False if verify: try: self.get('/api/console', logon_required=True) except ServerAuthError: return False return True
python
{ "resource": "" }
q15177
Session._do_logon
train
def _do_logon(self): """ Log on, unconditionally. This can be used to re-logon. This requires credentials to be provided. Raises: :exc:`~zhmcclient.ClientAuthError` :exc:`~zhmcclient.ServerAuthError` :exc:`~zhmcclient.ConnectionError` :exc:`~zhmcclient.ParseError` :exc:`~zhmcclient.HTTPError` """ if self._userid is None: raise ClientAuthError("Userid is not provided.") if self._password is None: if self._get_password: self._password = self._get_password(self._host, self._userid) else: raise ClientAuthError("Password is not provided.") logon_uri = '/api/sessions' logon_body = { 'userid': self._userid, 'password': self._password } self._headers.pop('X-API-Session', None) # Just in case self._session = self._new_session(self.retry_timeout_config) logon_res = self.post(logon_uri, logon_body, logon_required=False) self._session_id = logon_res['api-session'] self._headers['X-API-Session'] = self._session_id
python
{ "resource": "" }
q15178
Session._new_session
train
def _new_session(retry_timeout_config): """ Return a new `requests.Session` object. """ retry = requests.packages.urllib3.Retry( total=None, connect=retry_timeout_config.connect_retries, read=retry_timeout_config.read_retries, method_whitelist=retry_timeout_config.method_whitelist, redirect=retry_timeout_config.max_redirects) session = requests.Session() session.mount('https://', requests.adapters.HTTPAdapter(max_retries=retry)) session.mount('http://', requests.adapters.HTTPAdapter(max_retries=retry)) return session
python
{ "resource": "" }
q15179
Session._do_logoff
train
def _do_logoff(self): """ Log off, unconditionally. Raises: :exc:`~zhmcclient.ServerAuthError` :exc:`~zhmcclient.ConnectionError` :exc:`~zhmcclient.ParseError` :exc:`~zhmcclient.HTTPError` """ session_uri = '/api/sessions/this-session' self.delete(session_uri, logon_required=False) self._session_id = None self._session = None self._headers.pop('X-API-Session', None)
python
{ "resource": "" }
q15180
Session._log_http_request
train
def _log_http_request(method, url, headers=None, content=None): """ Log the HTTP request of an HMC REST API call, at the debug level. Parameters: method (:term:`string`): HTTP method name in upper case, e.g. 'GET' url (:term:`string`): HTTP URL (base URL and operation URI) headers (iterable): HTTP headers used for the request content (:term:`string`): HTTP body (aka content) used for the request """ if method == 'POST' and url.endswith('/api/sessions'): # In Python 3 up to 3.5, json.loads() requires unicode strings. if sys.version_info[0] == 3 and sys.version_info[1] in (4, 5) and \ isinstance(content, six.binary_type): content = content.decode('utf-8') # Because zhmcclient has built the request, we are not handling # any JSON parse errors from json.loads(). content_dict = json.loads(content) content_dict['password'] = '********' content = json.dumps(content_dict) if headers and 'X-API-Session' in headers: headers = headers.copy() headers['X-API-Session'] = '********' HMC_LOGGER.debug("Request: %s %s, headers: %r, " "content(max.1000): %.1000r", method, url, headers, content)
python
{ "resource": "" }
q15181
Session._log_http_response
train
def _log_http_response(method, url, status, headers=None, content=None): """ Log the HTTP response of an HMC REST API call, at the debug level. Parameters: method (:term:`string`): HTTP method name in upper case, e.g. 'GET' url (:term:`string`): HTTP URL (base URL and operation URI) status (integer): HTTP status code headers (iterable): HTTP headers returned in the response content (:term:`string`): HTTP body (aka content) returned in the response """ if method == 'POST' and url.endswith('/api/sessions'): # In Python 3 up to 3.5, json.loads() requires unicode strings. if sys.version_info[0] == 3 and sys.version_info[1] in (4, 5) and \ isinstance(content, six.binary_type): content = content.decode('utf-8') try: content_dict = json.loads(content) except ValueError as exc: content = '"Error: Cannot parse JSON payload of response: ' \ '{}"'.format(exc) else: content_dict['api-session'] = '********' content_dict['session-credential'] = '********' content = json.dumps(content_dict) if headers and 'X-API-Session' in headers: headers = headers.copy() headers['X-API-Session'] = '********' HMC_LOGGER.debug("Respons: %s %s, status: %s, headers: %r, " "content(max.1000): %.1000r", method, url, status, headers, content)
python
{ "resource": "" }
q15182
Session.delete
train
def delete(self, uri, logon_required=True): """ Perform the HTTP DELETE method against the resource identified by a URI. A set of standard HTTP headers is automatically part of the request. If the HMC session token is expired, this method re-logs on and retries the operation. Parameters: uri (:term:`string`): Relative URI path of the resource, e.g. "/api/session/{session-id}". This URI is relative to the base URL of the session (see the :attr:`~zhmcclient.Session.base_url` property). Must not be `None`. logon_required (bool): Boolean indicating whether the operation requires that the session is logged on to the HMC. For example, for the logoff operation, it does not make sense to first log on. Raises: :exc:`~zhmcclient.HTTPError` :exc:`~zhmcclient.ParseError` :exc:`~zhmcclient.ClientAuthError` :exc:`~zhmcclient.ServerAuthError` :exc:`~zhmcclient.ConnectionError` """ if logon_required: self.logon() url = self.base_url + uri self._log_http_request('DELETE', url, headers=self.headers) stats = self.time_stats_keeper.get_stats('delete ' + uri) stats.begin() req = self._session or requests req_timeout = (self.retry_timeout_config.connect_timeout, self.retry_timeout_config.read_timeout) try: result = req.delete(url, headers=self.headers, verify=False, timeout=req_timeout) except requests.exceptions.RequestException as exc: _handle_request_exc(exc, self.retry_timeout_config) finally: stats.end() self._log_http_response('DELETE', url, status=result.status_code, headers=result.headers, content=result.content) if result.status_code in (200, 204): return elif result.status_code == 403: result_object = _result_object(result) reason = result_object.get('reason', None) if reason == 5: # API session token expired: re-logon and retry self._do_logon() self.delete(uri, logon_required) return else: msg = result_object.get('message', None) raise ServerAuthError("HTTP authentication failed: {}". format(msg), HTTPError(result_object)) else: result_object = _result_object(result) raise HTTPError(result_object)
python
{ "resource": "" }
q15183
Job.check_for_completion
train
def check_for_completion(self): """ Check once for completion of the job and return completion status and result if it has completed. If the job completed in error, an :exc:`~zhmcclient.HTTPError` exception is raised. Returns: : A tuple (status, result) with: * status (:term:`string`): Completion status of the job, as returned in the ``status`` field of the response body of the "Query Job Status" HMC operation, as follows: * ``"complete"``: Job completed (successfully). * any other value: Job is not yet complete. * result (:term:`json object` or `None`): `None` for incomplete jobs. For completed jobs, the result of the original asynchronous operation that was performed by the job, from the ``job-results`` field of the response body of the "Query Job Status" HMC operation. That result is a :term:`json object` as described for the asynchronous operation, or `None` if the operation has no result. Raises: :exc:`~zhmcclient.HTTPError`: The job completed in error, or the job status cannot be retrieved, or the job cannot be deleted. :exc:`~zhmcclient.ParseError` :exc:`~zhmcclient.ClientAuthError` :exc:`~zhmcclient.ServerAuthError` :exc:`~zhmcclient.ConnectionError` """ job_result_obj = self.session.get(self.uri) job_status = job_result_obj['status'] if job_status == 'complete': self.session.delete(self.uri) op_status_code = job_result_obj['job-status-code'] if op_status_code in (200, 201): op_result_obj = job_result_obj.get('job-results', None) elif op_status_code == 204: # No content op_result_obj = None else: error_result_obj = job_result_obj.get('job-results', None) if not error_result_obj: message = None elif 'message' in error_result_obj: message = error_result_obj['message'] elif 'error' in error_result_obj: message = error_result_obj['error'] else: message = None error_obj = { 'http-status': op_status_code, 'reason': job_result_obj['job-reason-code'], 'message': message, 'request-method': self.op_method, 'request-uri': self.op_uri, } raise HTTPError(error_obj) else: op_result_obj = None return job_status, op_result_obj
python
{ "resource": "" }
q15184
Job.wait_for_completion
train
def wait_for_completion(self, operation_timeout=None): """ Wait for completion of the job, then delete the job on the HMC and return the result of the original asynchronous HMC operation, if it completed successfully. If the job completed in error, an :exc:`~zhmcclient.HTTPError` exception is raised. Parameters: operation_timeout (:term:`number`): Timeout in seconds, when waiting for completion of the job. The special value 0 means that no timeout is set. `None` means that the default async operation timeout of the session is used. If the timeout expires, a :exc:`~zhmcclient.OperationTimeout` is raised. This method gives completion of the job priority over strictly achieving the timeout. This may cause a slightly longer duration of the method than prescribed by the timeout. Returns: :term:`json object` or `None`: The result of the original asynchronous operation that was performed by the job, from the ``job-results`` field of the response body of the "Query Job Status" HMC operation. That result is a :term:`json object` as described for the asynchronous operation, or `None` if the operation has no result. Raises: :exc:`~zhmcclient.HTTPError`: The job completed in error, or the job status cannot be retrieved, or the job cannot be deleted. :exc:`~zhmcclient.ParseError` :exc:`~zhmcclient.ClientAuthError` :exc:`~zhmcclient.ServerAuthError` :exc:`~zhmcclient.ConnectionError` :exc:`~zhmcclient.OperationTimeout`: The timeout expired while waiting for job completion. """ if operation_timeout is None: operation_timeout = \ self.session.retry_timeout_config.operation_timeout if operation_timeout > 0: start_time = time.time() while True: job_status, op_result_obj = self.check_for_completion() # We give completion of status priority over strictly achieving # the timeout, so we check status first. This may cause a longer # duration of the method than prescribed by the timeout. if job_status == 'complete': return op_result_obj if operation_timeout > 0: current_time = time.time() if current_time > start_time + operation_timeout: raise OperationTimeout( "Waiting for completion of job {} timed out " "(operation timeout: {} s)". format(self.uri, operation_timeout), operation_timeout) time.sleep(1)
python
{ "resource": "" }
q15185
logged_api_call
train
def logged_api_call(func): """ Function decorator that causes the decorated API function or method to log calls to itself to a logger. The logger's name is the dotted module name of the module defining the decorated function (e.g. 'zhmcclient._cpc'). Parameters: func (function object): The original function being decorated. Returns: function object: The function wrappering the original function being decorated. Raises: TypeError: The @logged_api_call decorator must be used on a function or method (and not on top of the @property decorator). """ # Note that in this decorator function, we are in a module loading context, # where the decorated functions are being defined. When this decorator # function is called, its call stack represents the definition of the # decorated functions. Not all global definitions in the module have been # defined yet, and methods of classes that are decorated with this # decorator are still functions at this point (and not yet methods). module = inspect.getmodule(func) if not inspect.isfunction(func) or not hasattr(module, '__name__'): raise TypeError("The @logged_api_call decorator must be used on a " "function or method (and not on top of the @property " "decorator)") try: # We avoid the use of inspect.getouterframes() because it is slow, # and use the pointers up the stack frame, instead. this_frame = inspect.currentframe() # this decorator function here apifunc_frame = this_frame.f_back # the decorated API function apifunc_owner = inspect.getframeinfo(apifunc_frame)[2] finally: # Recommended way to deal with frame objects to avoid ref cycles del this_frame del apifunc_frame # TODO: For inner functions, show all outer levels instead of just one. if apifunc_owner == '<module>': # The decorated API function is defined globally (at module level) apifunc_str = '{func}()'.format(func=func.__name__) else: # The decorated API function is defined in a class or in a function apifunc_str = '{owner}.{func}()'.format(owner=apifunc_owner, func=func.__name__) logger = get_logger(API_LOGGER_NAME) def is_external_call(): """ Return a boolean indicating whether the call to the decorated API function is an external call (vs. b eing an internal call). """ try: # We avoid the use of inspect.getouterframes() because it is slow, # and use the pointers up the stack frame, instead. log_it_frame = inspect.currentframe() # this log_it() function log_api_call_frame = log_it_frame.f_back # the log_api_call() func apifunc_frame = log_api_call_frame.f_back # the decorated API func apicaller_frame = apifunc_frame.f_back # caller of API function apicaller_module = inspect.getmodule(apicaller_frame) if apicaller_module is None: apicaller_module_name = "<unknown>" else: apicaller_module_name = apicaller_module.__name__ finally: # Recommended way to deal with frame objects to avoid ref cycles del log_it_frame del log_api_call_frame del apifunc_frame del apicaller_frame del apicaller_module # Log only if the caller is not from the zhmcclient package return apicaller_module_name.split('.')[0] != 'zhmcclient' def log_api_call(func, *args, **kwargs): """ Log entry to and exit from the decorated function, at the debug level. Note that this wrapper function is called every time the decorated function/method is called, but that the log message only needs to be constructed when logging for this logger and for this log level is turned on. Therefore, we do as much as possible in the decorator function, plus we use %-formatting and lazy interpolation provided by the log functions, in order to save resources in this function here. Parameters: func (function object): The decorated function. *args: Any positional arguments for the decorated function. **kwargs: Any keyword arguments for the decorated function. """ # Note that in this function, we are in the context where the # decorated function is actually called. _log_it = is_external_call() and logger.isEnabledFor(logging.DEBUG) if _log_it: logger.debug("Called: {}, args: {:.500}, kwargs: {:.500}". format(apifunc_str, log_escaped(repr(args)), log_escaped(repr(kwargs)))) result = func(*args, **kwargs) if _log_it: logger.debug("Return: {}, result: {:.1000}". format(apifunc_str, log_escaped(repr(result)))) return result if 'decorate' in globals(): return decorate(func, log_api_call) else: return decorator(log_api_call, func)
python
{ "resource": "" }
q15186
generic_div
train
def generic_div(a, b): """Simple function to divide two numbers""" logger.debug('Called generic_div({}, {})'.format(a, b)) return a / b
python
{ "resource": "" }
q15187
buggy_div
train
def buggy_div(request): """ A buggy endpoint to perform division between query parameters a and b. It will fail if b is equal to 0 or either a or b are not float. :param request: request object :return: """ a = float(request.GET.get('a', '0')) b = float(request.GET.get('b', '0')) return JsonResponse({'result': a / b})
python
{ "resource": "" }
q15188
ascii
train
def ascii(graph): """Format graph as an ASCII art.""" from .._ascii import DAG from .._echo import echo_via_pager echo_via_pager(str(DAG(graph)))
python
{ "resource": "" }
q15189
_jsonld
train
def _jsonld(graph, format, *args, **kwargs): """Return formatted graph in JSON-LD ``format`` function.""" import json from pyld import jsonld from renku.models._jsonld import asjsonld output = getattr(jsonld, format)([ asjsonld(action) for action in graph.activities.values() ]) return json.dumps(output, indent=2)
python
{ "resource": "" }
q15190
dot
train
def dot(graph, simple=True, debug=False, landscape=False): """Format graph as a dot file.""" import sys from rdflib import ConjunctiveGraph from rdflib.plugin import register, Parser from rdflib.tools.rdf2dot import rdf2dot register('json-ld', Parser, 'rdflib_jsonld.parser', 'JsonLDParser') g = ConjunctiveGraph().parse( data=_jsonld(graph, 'expand'), format='json-ld', ) g.bind('prov', 'http://www.w3.org/ns/prov#') g.bind('wfdesc', 'http://purl.org/wf4ever/wfdesc#') g.bind('wf', 'http://www.w3.org/2005/01/wf/flow#') g.bind('wfprov', 'http://purl.org/wf4ever/wfprov#') if debug: rdf2dot(g, sys.stdout) return sys.stdout.write('digraph { \n node [ fontname="DejaVu Sans" ] ; \n ') if landscape: sys.stdout.write('rankdir="LR" \n') if simple: _rdf2dot_simple(g, sys.stdout) return _rdf2dot_reduced(g, sys.stdout)
python
{ "resource": "" }
q15191
_rdf2dot_simple
train
def _rdf2dot_simple(g, stream): """Create a simple graph of processes and artifacts.""" from itertools import chain import re path_re = re.compile( r'file:///(?P<type>[a-zA-Z]+)/' r'(?P<commit>\w+)' r'(?P<path>.+)?' ) inputs = g.query( """ SELECT ?input ?role ?activity ?comment WHERE { ?activity (prov:qualifiedUsage/prov:entity) ?input . ?activity prov:qualifiedUsage ?qual . ?qual prov:hadRole ?role . ?qual prov:entity ?input . ?qual rdf:type ?type . ?activity rdf:type wfprov:ProcessRun . ?activity rdfs:comment ?comment . FILTER NOT EXISTS {?activity rdf:type wfprov:WorkflowRun} } """ ) outputs = g.query( """ SELECT ?activity ?role ?output ?comment WHERE { ?output (prov:qualifiedGeneration/prov:activity) ?activity . ?output prov:qualifiedGeneration ?qual . ?qual prov:hadRole ?role . ?qual prov:activity ?activity . ?qual rdf:type ?type . ?activity rdf:type wfprov:ProcessRun ; rdfs:comment ?comment . FILTER NOT EXISTS {?activity rdf:type wfprov:WorkflowRun} } """ ) activity_nodes = {} artifact_nodes = {} for source, role, target, comment, in chain(inputs, outputs): # extract the pieces of the process URI src_path = path_re.match(source).groupdict() tgt_path = path_re.match(target).groupdict() # write the edge stream.write( '\t"{src_commit}:{src_path}" -> ' '"{tgt_commit}:{tgt_path}" ' '[label={role}] \n'.format( src_commit=src_path['commit'][:5], src_path=src_path.get('path') or '', tgt_commit=tgt_path['commit'][:5], tgt_path=tgt_path.get('path') or '', role=role ) ) if src_path.get('type') == 'commit': activity_nodes.setdefault(source, {'comment': comment}) artifact_nodes.setdefault(target, {}) if tgt_path.get('type') == 'commit': activity_nodes.setdefault(target, {'comment': comment}) artifact_nodes.setdefault(source, {}) # customize the nodes for node, content in activity_nodes.items(): node_path = path_re.match(node).groupdict() stream.write( '\t"{commit}:{path}" ' '[shape=box label="#{commit}:{path}:{comment}"] \n'.format( comment=content['comment'], commit=node_path['commit'][:5], path=node_path.get('path') or '' ) ) for node, content in artifact_nodes.items(): node_path = path_re.match(node).groupdict() stream.write( '\t"{commit}:{path}" ' '[label="#{commit}:{path}"] \n'.format( commit=node_path['commit'][:5], path=node_path.get('path') or '' ) ) stream.write('}\n')
python
{ "resource": "" }
q15192
makefile
train
def makefile(graph): """Format graph as Makefile.""" from renku.models.provenance.activities import ProcessRun, WorkflowRun for activity in graph.activities.values(): if not isinstance(activity, ProcessRun): continue elif isinstance(activity, WorkflowRun): steps = activity.subprocesses.values() else: steps = [activity] for step in steps: click.echo(' '.join(step.outputs) + ': ' + ' '.join(step.inputs)) tool = step.process click.echo( '\t@' + ' '.join(tool.to_argv()) + ' ' + ' '.join( tool.STD_STREAMS_REPR[key] + ' ' + str(path) for key, path in tool._std_streams().items() ) )
python
{ "resource": "" }
q15193
nt
train
def nt(graph): """Format graph as n-tuples.""" from rdflib import ConjunctiveGraph from rdflib.plugin import register, Parser register('json-ld', Parser, 'rdflib_jsonld.parser', 'JsonLDParser') click.echo( ConjunctiveGraph().parse( data=_jsonld(graph, 'expand'), format='json-ld', ).serialize(format='nt') )
python
{ "resource": "" }
q15194
install
train
def install(client, force): """Install Git hooks.""" import pkg_resources from git.index.fun import hook_path as get_hook_path for hook in HOOKS: hook_path = Path(get_hook_path(hook, client.repo.git_dir)) if hook_path.exists(): if not force: click.echo( 'Hook already exists. Skipping {0}'.format(str(hook_path)), err=True ) continue else: hook_path.unlink() # Make sure the hooks directory exists. hook_path.parent.mkdir(parents=True, exist_ok=True) Path(hook_path).write_bytes( pkg_resources.resource_string( 'renku.data', '{hook}.sh'.format(hook=hook) ) ) hook_path.chmod(hook_path.stat().st_mode | stat.S_IEXEC)
python
{ "resource": "" }
q15195
uninstall
train
def uninstall(client): """Uninstall Git hooks.""" from git.index.fun import hook_path as get_hook_path for hook in HOOKS: hook_path = Path(get_hook_path(hook, client.repo.git_dir)) if hook_path.exists(): hook_path.unlink()
python
{ "resource": "" }
q15196
format_cell
train
def format_cell(cell, datetime_fmt=None): """Format a cell.""" if datetime_fmt and isinstance(cell, datetime): return cell.strftime(datetime_fmt) return cell
python
{ "resource": "" }
q15197
tabulate
train
def tabulate(collection, headers, datetime_fmt='%Y-%m-%d %H:%M:%S', **kwargs): """Pretty-print a collection.""" if isinstance(headers, dict): attrs = headers.keys() # if mapping is not specified keep original names = [ key if value is None else value for key, value in headers.items() ] else: attrs = names = headers table = [( format_cell(cell, datetime_fmt=datetime_fmt) for cell in attrgetter(*attrs)(c) ) for c in collection] return tblte(table, headers=[h.upper() for h in names], **kwargs)
python
{ "resource": "" }
q15198
_convert_dataset_files
train
def _convert_dataset_files(value): """Convert dataset files.""" output = {} for k, v in value.items(): inst = DatasetFile.from_jsonld(v) output[inst.path] = inst return output
python
{ "resource": "" }
q15199
remove
train
def remove(ctx, client, sources): """Remove files and check repository for potential problems.""" from renku.api._git import _expand_directories def fmt_path(path): """Format path as relative to the client path.""" return str(Path(path).absolute().relative_to(client.path)) files = { fmt_path(source): fmt_path(file_or_dir) for file_or_dir in sources for source in _expand_directories((file_or_dir, )) } # 1. Update dataset metadata files. with progressbar( client.datasets.values(), item_show_func=lambda item: str(item.short_id) if item else '', label='Updating dataset metadata', width=0, ) as bar: for dataset in bar: remove = [] for key, file_ in dataset.files.items(): filepath = fmt_path(file_.full_path) if filepath in files: remove.append(key) if remove: for key in remove: dataset.unlink_file(key) dataset.to_yaml() # 2. Manage .gitattributes for external storage. tracked = tuple( path for path, attr in client.find_attr(*files).items() if attr.get('filter') == 'lfs' ) client.untrack_paths_from_storage(*tracked) existing = client.find_attr(*tracked) if existing: click.echo(WARNING + 'There are custom .gitattributes.\n') if click.confirm( 'Do you want to edit ".gitattributes" now?', default=False ): click.edit(filename=str(client.path / '.gitattributes')) # Finally remove the files. final_sources = list(set(files.values())) if final_sources: run(['git', 'rm', '-rf'] + final_sources, check=True)
python
{ "resource": "" }