code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
if self.humidity is None: return None humidity = round(float(self.humidity) / 100, 1) return humidity
def state(self)
Main state of sensor.
4.672678
3.875396
1.205729
if self.lightlevel is None: return None lux = round(10 ** (float(self.lightlevel - 1) / 10000), 1) return lux
def state(self)
Main state of sensor.
5.907415
4.898623
1.205934
field = self.deconz_id + '/config' await self._async_set_state_callback(field, data)
async def async_set_config(self, data)
Set config of thermostat. { "mode": "auto", "heatsetpoint": 180, }
10.610222
9.382129
1.130897
if metric_type in (int, float): try: return metric_type(value_str) except ValueError: raise ValueError("Invalid {} metric value: {!r}". format(metric_type.__class__.__name__, value_str)) elif metric_type is six.text_type: # In Python 3, decode('unicode_escape) requires bytes, so we need # to encode to bytes. This also works in Python 2. return value_str.strip('"').encode('utf-8').decode('unicode_escape') else: assert metric_type is bool lower_str = value_str.lower() if lower_str == 'true': return True elif lower_str == 'false': return False else: raise ValueError("Invalid boolean metric value: {!r}". format(value_str))
def _metric_value(value_str, metric_type)
Return a Python-typed metric value from a metric value string.
2.557867
2.497179
1.024303
for item in _PATTERN_UNIT_LIST: pattern, unit = item if pattern.match(metric_name): return unit return None
def _metric_unit_from_name(metric_name)
Return a metric unit string for human consumption, that is inferred from the metric name. If a unit cannot be inferred, `None` is returned.
5.058171
5.839599
0.866185
result = self.session.post('/api/services/metrics/context', body=properties) mc_properties = properties.copy() mc_properties.update(result) new_metrics_context = MetricsContext(self, result['metrics-context-uri'], None, mc_properties) self._metrics_contexts.append(new_metrics_context) return new_metrics_context
def create(self, properties)
Create a :term:`Metrics Context` resource in the HMC this client is connected to. Parameters: properties (dict): Initial property values. Allowable properties are defined in section 'Request body contents' in section 'Create Metrics Context' in the :term:`HMC API` book. Returns: :class:`~zhmcclient.MetricsContext`: The resource object for the new :term:`Metrics Context` resource. Raises: :exc:`~zhmcclient.HTTPError` :exc:`~zhmcclient.ParseError` :exc:`~zhmcclient.AuthError` :exc:`~zhmcclient.ConnectionError`
4.823184
3.741044
1.289261
# Dictionary of MetricGroupDefinition objects, by metric group name metric_group_definitions = dict() for mg_info in self.properties['metric-group-infos']: mg_name = mg_info['group-name'] mg_def = MetricGroupDefinition( name=mg_name, resource_class=_resource_class_from_group(mg_name), metric_definitions=dict()) for i, m_info in enumerate(mg_info['metric-infos']): m_name = m_info['metric-name'] m_def = MetricDefinition( index=i, name=m_name, type=_metric_type(m_info['metric-type']), unit=_metric_unit_from_name(m_name)) mg_def.metric_definitions[m_name] = m_def metric_group_definitions[mg_name] = mg_def return metric_group_definitions
def _setup_metric_group_definitions(self)
Return the dict of MetricGroupDefinition objects for this metrics context, by processing its 'metric-group-infos' property.
2.473366
2.118781
1.167353
metrics_response = self.manager.session.get(self.uri) return metrics_response
def get_metrics(self)
Retrieve the current metric values for this :term:`Metrics Context` resource from the HMC. The metric values are returned by this method as a string in the `MetricsResponse` format described with the 'Get Metrics' operation in the :term:`HMC API` book. The :class:`~zhmcclient.MetricsResponse` class can be used to process the `MetricsResponse` string returned by this method, and provides structured access to the metrics values. Returns: :term:`string`: The current metric values, in the `MetricsResponse` string format. Raises: :exc:`~zhmcclient.HTTPError` :exc:`~zhmcclient.ParseError` :exc:`~zhmcclient.AuthError` :exc:`~zhmcclient.ConnectionError`
11.272791
10.472924
1.076375
self.manager.session.delete(self.uri) self.manager._metrics_contexts.remove(self)
def delete(self)
Delete this :term:`Metrics Context` resource. Raises: :exc:`~zhmcclient.HTTPError` :exc:`~zhmcclient.ParseError` :exc:`~zhmcclient.AuthError` :exc:`~zhmcclient.ConnectionError`
12.099667
7.879065
1.535673
mg_defs = self._metrics_context.metric_group_definitions metric_group_name = None resource_uri = None dt_timestamp = None object_values = None metric_group_values = list() state = 0 for mr_line in self._metrics_response_str.splitlines(): if state == 0: if object_values is not None: # Store the result from the previous metric group mgv = MetricGroupValues(metric_group_name, object_values) metric_group_values.append(mgv) object_values = None if mr_line == '': # Skip initial (or trailing) empty lines pass else: # Process the next metrics group metric_group_name = mr_line.strip('"') # No " or \ inside assert metric_group_name in mg_defs m_defs = mg_defs[metric_group_name].metric_definitions object_values = list() state = 1 elif state == 1: if mr_line == '': # There are no (or no more) ObjectValues items in this # metrics group state = 0 else: # There are ObjectValues items resource_uri = mr_line.strip('"') # No " or \ inside state = 2 elif state == 2: # Process the timestamp assert mr_line != '' try: dt_timestamp = datetime_from_timestamp(int(mr_line)) except ValueError: # Sometimes, the returned epoch timestamp values are way # too large, e.g. 3651584404810066 (which would translate # to the year 115791 A.D.). Python datetime supports # up to the year 9999. We circumvent this issue by # simply using the current date&time. # TODO: Remove the circumvention for too large timestamps. dt_timestamp = datetime.now(pytz.utc) state = 3 elif state == 3: if mr_line != '': # Process the metric values in the ValueRow line str_values = mr_line.split(',') metrics = dict() for m_name in m_defs: m_def = m_defs[m_name] m_type = m_def.type m_value_str = str_values[m_def.index] m_value = _metric_value(m_value_str, m_type) metrics[m_name] = m_value ov = MetricObjectValues( self._client, mg_defs[metric_group_name], resource_uri, dt_timestamp, metrics) object_values.append(ov) # stay in this state, for more ValueRow lines else: # On the empty line after the last ValueRow line state = 1 return metric_group_values
def _setup_metric_group_values(self)
Return the list of MetricGroupValues objects for this metrics response, by processing its metrics response string. The lines in the metrics response string are:: MetricsResponse: MetricsGroup{0,*} <emptyline> a third empty line at the end MetricsGroup: MetricsGroupName ObjectValues{0,*} <emptyline> a second empty line after each MG ObjectValues: ObjectURI Timestamp ValueRow{1,*} <emptyline> a first empty line after this blk
4.208942
3.756891
1.120326
if self._resource is not None: return self._resource resource_class = self.metric_group_definition.resource_class resource_uri = self.resource_uri if resource_class == 'cpc': filter_args = {'object-uri': resource_uri} resource = self.client.cpcs.find(**filter_args) elif resource_class == 'logical-partition': for cpc in self.client.cpcs.list(): try: filter_args = {'object-uri': resource_uri} resource = cpc.lpars.find(**filter_args) break except NotFound: pass # Try next CPC else: raise elif resource_class == 'partition': for cpc in self.client.cpcs.list(): try: filter_args = {'object-uri': resource_uri} resource = cpc.partitions.find(**filter_args) break except NotFound: pass # Try next CPC else: raise elif resource_class == 'adapter': for cpc in self.client.cpcs.list(): try: filter_args = {'object-uri': resource_uri} resource = cpc.adapters.find(**filter_args) break except NotFound: pass # Try next CPC else: raise elif resource_class == 'nic': for cpc in self.client.cpcs.list(): found = False for partition in cpc.partitions.list(): try: filter_args = {'element-uri': resource_uri} resource = partition.nics.find(**filter_args) found = True break except NotFound: pass # Try next partition / next CPC if found: break else: raise else: raise ValueError( "Invalid resource class: {!r}".format(resource_class)) self._resource = resource return self._resource
def resource(self)
:class:`~zhmcclient.BaseResource`: The Python resource object of the resource these metric values apply to. Raises: :exc:`~zhmcclient.NotFound`: No resource found for this URI in the management scope of the HMC.
1.909284
1.764249
1.082208
assert not self._free # free pool is empty expand_end = self._expand_start + self._expand_len if expand_end > self._range_end: # This happens if the size of the value range is not a multiple # of the expansion chunk size. expand_end = self._range_end if self._expand_start == expand_end: raise ValueError("Out of capacity in ID pool") self._free = set(range(self._expand_start, expand_end)) self._expand_start = expand_end
def _expand(self)
Expand the free pool, if possible. If out of capacity w.r.t. the defined ID value range, ValueError is raised.
4.805634
3.670351
1.309312
if not self._free: self._expand() id = self._free.pop() self._used.add(id) return id
def alloc(self)
Allocate an ID value and return it. Raises: ValueError: Out of capacity in ID pool.
4.866313
4.637119
1.049426
result = self.session.post(self.partition.uri + '/nics', 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] nic = Nic(self, uri, name, props) self._name_uri_cache.update(name, uri) return nic
def create(self, properties)
Create and configure a NIC in this Partition. The NIC must be backed by an adapter port (on an OSA, ROCE, or Hipersockets adapter). The way the backing adapter port is specified in the "properties" parameter of this method depends on the adapter type, as follows: * For OSA and Hipersockets adapters, the "virtual-switch-uri" property is used to specify the URI of the virtual switch that is associated with the backing adapter port. This virtual switch is a resource that automatically exists as soon as the adapter resource exists. Note that these virtual switches do not show up in the HMC GUI; but they do show up at the HMC REST API and thus also at the zhmcclient API as the :class:`~zhmcclient.VirtualSwitch` class. The value for the "virtual-switch-uri" property can be determined from a given adapter name and port index as shown in the following example code (omitting any error handling): .. code-block:: python partition = ... # Partition object for the new NIC adapter_name = 'OSA #1' # name of adapter with backing port adapter_port_index = 0 # port index of backing port adapter = partition.manager.cpc.adapters.find(name=adapter_name) vswitches = partition.manager.cpc.virtual_switches.findall( **{'backing-adapter-uri': adapter.uri}) vswitch = None for vs in vswitches: if vs.get_property('port') == adapter_port_index: vswitch = vs break properties['virtual-switch-uri'] = vswitch.uri * For RoCE adapters, the "network-adapter-port-uri" property is used to specify the URI of the backing adapter port, directly. The value for the "network-adapter-port-uri" property can be determined from a given adapter name and port index as shown in the following example code (omitting any error handling): .. code-block:: python partition = ... # Partition object for the new NIC adapter_name = 'ROCE #1' # name of adapter with backing port adapter_port_index = 0 # port index of backing port adapter = partition.manager.cpc.adapters.find(name=adapter_name) port = adapter.ports.find(index=adapter_port_index) properties['network-adapter-port-uri'] = port.uri Authorization requirements: * Object-access permission to this Partition. * Object-access permission to the backing Adapter for the new NIC. * Task permission to the "Partition Details" task. Parameters: properties (dict): Initial property values. Allowable properties are defined in section 'Request body contents' in section 'Create NIC' in the :term:`HMC API` book. Returns: Nic: The resource object for the new NIC. The object will have its 'element-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`
5.236603
4.91001
1.066516
self.manager.session.delete(self._uri) self.manager._name_uri_cache.delete( self.properties.get(self.manager._name_prop, None))
def delete(self)
Delete this NIC. Authorization requirements: * Object-access permission to the Partition containing this HBA. * Task permission to the "Partition Details" task. Raises: :exc:`~zhmcclient.HTTPError` :exc:`~zhmcclient.ParseError` :exc:`~zhmcclient.AuthError` :exc:`~zhmcclient.ConnectionError`
7.726585
7.401349
1.043943
self.manager.session.post(self.uri, body=properties) is_rename = self.manager._name_prop in properties if is_rename: # Delete the old name from the cache self.manager._name_uri_cache.delete(self.name) self.properties.update(copy.deepcopy(properties)) if is_rename: # Add the new name to the cache self.manager._name_uri_cache.update(self.name, self.uri)
def update_properties(self, properties)
Update writeable properties of this NIC. Authorization requirements: * Object-access permission to the Partition containing this NIC. * Object-access permission to the backing Adapter for this NIC. * Task permission to the "Partition Details" 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 - NIC Element Object' in the :term:`HMC API` book. Raises: :exc:`~zhmcclient.HTTPError` :exc:`~zhmcclient.ParseError` :exc:`~zhmcclient.AuthError` :exc:`~zhmcclient.ConnectionError`
3.772585
3.971371
0.949945
if self._attached_partition is None: part_mgr = self.manager.storage_group.manager.cpc.partitions part = part_mgr.resource_object(self.get_property('partition-uri')) self._attached_partition = part return self._attached_partition
def attached_partition(self)
:class:`~zhmcclient.Partition`: The partition to which this virtual storage resource is attached. The returned partition object has only a minimal set of properties set ('object-id', 'object-uri', 'class', 'parent'). Note that a virtual storage resource is always attached to a partition, as long as it exists. Authorization requirements: * Object-access permission to the storage group owning this virtual storage resource. Raises: :exc:`~zhmcclient.HTTPError` :exc:`~zhmcclient.ParseError` :exc:`~zhmcclient.AuthError` :exc:`~zhmcclient.ConnectionError`
5.476174
8.311606
0.658859
if self._adapter_port is None: port_uri = self.get_property('adapter-port-uri') assert port_uri is not None m = re.match(r'^(/api/adapters/[^/]+)/.*', port_uri) adapter_uri = m.group(1) adapter_mgr = self.manager.storage_group.manager.cpc.adapters filter_args = {'object-uri': adapter_uri} adapter = adapter_mgr.find(**filter_args) port_mgr = adapter.ports port = port_mgr.resource_object(port_uri) self._adapter_port = port return self._adapter_port
def adapter_port(self)
:class:`~zhmcclient.Port`: The storage adapter port associated with this virtual storage resource, once discovery has determined which port to use for this virtual storage resource. This applies to both, FCP and FICON/ECKD typed storage groups. The returned adapter port object has only a minimal set of properties set ('object-id', 'object-uri', 'class', 'parent'). Authorization requirements: * Object-access permission to the storage group owning this virtual storage resource. * Object-access permission to the CPC of the storage adapter. * Object-access permission to the storage adapter. Raises: :exc:`~zhmcclient.HTTPError` :exc:`~zhmcclient.ParseError` :exc:`~zhmcclient.AuthError` :exc:`~zhmcclient.ConnectionError`
3.518645
3.677686
0.956755
self.auto_invalidate() try: return self._uris[name] except KeyError: self.refresh() try: return self._uris[name] except KeyError: raise NotFound({self._manager._name_prop: name}, self._manager)
def get(self, name)
Get the resource URI for a specified resource name. If an entry for the specified resource name does not exist in the Name-URI cache, the cache is refreshed from the HMC with all resources of the manager holding this cache. If an entry for the specified resource name still does not exist after that, ``NotFound`` is raised.
5.501408
4.98178
1.104306
current = datetime.now() if current > self._invalidated + timedelta(seconds=self._timetolive): self.invalidate()
def auto_invalidate(self)
Invalidate the cache if the current time is past the time to live.
6.850448
4.46748
1.533403
self.invalidate() full = not self._manager._list_has_name res_list = self._manager.list(full_properties=full) self.update_from(res_list)
def refresh(self)
Refresh the Name-URI cache from the HMC. This is done by invalidating the cache, listing the resources of this manager from the HMC, and populating the cache with that information.
12.6457
9.531483
1.32673
for res in res_list: # We access the properties dictionary, in order to make sure # we don't drive additional HMC interactions. name = res.properties.get(self._manager._name_prop, None) uri = res.properties.get(self._manager._uri_prop, None) self.update(name, uri)
def update_from(self, res_list)
Update the Name-URI cache from the provided resource list. This is done by going through the resource list and updating any cache entries for non-empty resource names in that list. Other cache entries remain unchanged.
6.767976
6.241582
1.084337
if filter_args is None or len(filter_args) != 1 or \ self._oid_prop not in filter_args: return None oid_match = filter_args[self._oid_prop] if not isinstance(oid_match, six.string_types) or \ not re.match(r'^[a-zA-Z0-9_\-]+$', oid_match): return None # The match string is a plain string (not a reg.expression) # Construct the resource URI from the filter property # and issue a Get <Resource> Properties on that URI uri = self._base_uri + '/' + oid_match try: props = self.session.get(uri) except HTTPError as exc: if exc.http_status == 404 and exc.reason == 1: # No such resource return None raise resource_obj = self.resource_class( manager=self, uri=props[self._uri_prop], name=props.get(self._name_prop, None), properties=props) resource_obj._full_properties = True return resource_obj
def _try_optimized_lookup(self, filter_args)
Try to optimize the lookup by checking whether the filter arguments specify the property that is used as the last segment in the resource URI, with a plain string as match value (i.e. not using regular expression matching). If so, the lookup is performed by constructing the resource URI from the specified filter argument, and by issuing a Get Properties operation on that URI, returning a single resource object. Parameters: filter_args (dict): Filter arguments. For details, see :ref:`Filtering`. Returns: resource object, or `None` if the optimization was not possible.
3.929511
3.254112
1.207552
query_parms = [] # query parameter strings client_filter_args = {} if filter_args is not None: for prop_name in filter_args: prop_match = filter_args[prop_name] if prop_name in self._query_props: self._append_query_parms(query_parms, prop_name, prop_match) else: client_filter_args[prop_name] = prop_match query_parms_str = '&'.join(query_parms) if query_parms_str: query_parms_str = '?{}'.format(query_parms_str) return query_parms_str, client_filter_args
def _divide_filter_args(self, filter_args)
Divide the filter arguments into filter query parameters for filtering on the server side, and the remaining client-side filters. Parameters: 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: : tuple (query_parms_str, client_filter_args)
2.673592
2.428281
1.101022
if filter_args is not None: for prop_name in filter_args: prop_match = filter_args[prop_name] if not self._matches_prop(obj, prop_name, prop_match): return False return True
def _matches_filters(self, obj, filter_args)
Return a boolean indicating whether a resource object matches a set of filter arguments. This is used for client-side filtering. Depending on the properties specified in the filter arguments, this method retrieves the resource properties from the HMC. Parameters: obj (BaseResource): Resource object. filter_args (dict): Filter arguments. For details, see :ref:`Filtering`. `None` causes the resource to always match. Returns: bool: Boolean indicating whether the resource object matches the filter arguments.
2.554624
2.929257
0.872106
if isinstance(prop_match, (list, tuple)): # List items are logically ORed, so one matching item suffices. for pm in prop_match: if self._matches_prop(obj, prop_name, pm): return True else: # Some lists of resources do not have all properties, for example # Hipersocket adapters do not have a "card-location" property. # If a filter property does not exist on a resource, the resource # does not match. try: prop_value = obj.get_property(prop_name) except KeyError: return False if isinstance(prop_value, six.string_types): # HMC resource property is Enum String or (non-enum) String, # and is both matched by regexp matching. Ideally, regexp # matching should only be done for non-enum strings, but # distinguishing them is not possible given that the client # has no knowledge about the properties. # The regexp matching implemented in the HMC requires begin and # end of the string value to match, even if the '^' for begin # and '$' for end are not specified in the pattern. The code # here is consistent with that: We add end matching to the # pattern, and begin matching is done by re.match() # automatically. re_match = prop_match + '$' m = re.match(re_match, prop_value) if m: return True else: if prop_value == prop_match: return True return False
def _matches_prop(self, obj, prop_name, prop_match)
Return a boolean indicating whether a resource object matches with a single property against a property match value. This is used for client-side filtering. Depending on the specified property, this method retrieves the resource properties from the HMC. Parameters: obj (BaseResource): Resource object. prop_match: Property match value that is used to match the actual value of the specified property against, as follows: - If the match value is a list or tuple, this method is invoked recursively to find whether one or more match values inthe list match. - Else if the property is of string type, its value is matched by interpreting the match value as a regular expression. - Else the property value is matched by exact value comparison with the match value. Returns: bool: Boolean indicating whether the resource object matches w.r.t. the specified property and the match value.
6.283506
5.895142
1.065879
if uri_or_oid.startswith('/api/'): assert uri_or_oid[-1] != '/' uri = uri_or_oid oid = uri.split('/')[-1] else: assert '/' not in uri_or_oid oid = uri_or_oid uri = '{}/{}'.format(self._base_uri, oid) res_props = { self._oid_prop: oid, 'parent': self.parent.uri if self.parent is not None else None, 'class': self.class_name, } name = None if props: res_props.update(props) try: name = props[self._name_prop] except KeyError: pass return self.resource_class(self, uri, name, res_props)
def resource_object(self, uri_or_oid, props=None)
Return a minimalistic Python resource object for this resource class, that is scoped to this manager. This method is an internal helper function and is not normally called by users. The returned resource object will have the following minimal set of properties set automatically: * `object-uri` * `object-id` * `parent` * `class` Additional properties for the Python resource object can be specified by the caller. Parameters: uri_or_oid (string): `object-uri` or `object-id` of the resource. props (dict): Property values in addition to the minimal list of properties that are set automatically (see above). Returns: Subclass of :class:`~zhmcclient.BaseResource`: A Python resource object for this resource class.
2.527852
2.479708
1.019415
if len(filter_args) == 1 and self._name_prop in filter_args: try: obj = self.find_by_name(filter_args[self._name_prop]) except NotFound: return [] return [obj] else: obj_list = self.list(filter_args=filter_args) return obj_list
def findall(self, **filter_args)
Find zero or more resources in scope of this manager, by matching resource properties against the specified filter arguments, and return a list of their Python resource objects (e.g. for CPCs, a list of :class:`~zhmcclient.Cpc` objects is returned). Any resource property may be specified in a filter argument. For details about filter arguments, see :ref:`Filtering`. The zhmcclient implementation handles the specified properties in an optimized way: Properties that can be filtered on the HMC are actually filtered there (this varies by resource type), and the remaining properties are filtered on the client side. If the "name" property is specified as the only filter argument, an optimized lookup is performed that uses a name-to-URI cache in this manager object. This this optimized lookup uses the specified match value for exact matching and is not interpreted as a regular expression. Authorization requirements: * see the `list()` method in the derived classes. Parameters: \\**filter_args: All keyword arguments are used as filter arguments. Specifying no keyword arguments causes no filtering to happen. See the examples for usage details. Returns: List of resource objects in scope of this manager object that match the filter arguments. These resource objects have a minimal set of properties. Raises: : Exceptions raised by the `list()` methods in derived resource manager classes (see :ref:`Resources`). Examples: * The following example finds partitions in a CPC by status. Because the 'status' resource property is also a valid Python variable name, there are two ways for the caller to specify the filter arguments for this method: As named parameters:: run_states = ['active', 'degraded'] run_parts = cpc.partitions.find(status=run_states) As a parameter dictionary:: run_parts = cpc.partitions.find(**{'status': run_states}) * The following example finds adapters of the OSA family in a CPC with an active status. Because the resource property for the adapter family is named 'adapter-family', it is not suitable as a Python variable name. Therefore, the caller can specify the filter argument only as a parameter dictionary:: filter_args = {'adapter-family': 'osa', 'status': 'active'} active_osa_adapters = cpc.adapters.findall(**filter_args)
2.930368
3.858131
0.759531
obj_list = self.findall(**filter_args) num_objs = len(obj_list) if num_objs == 0: raise NotFound(filter_args, self) elif num_objs > 1: raise NoUniqueMatch(filter_args, self, obj_list) else: return obj_list[0]
def find(self, **filter_args)
Find exactly one resource in scope of this manager, by matching resource properties against the specified filter arguments, and return its Python resource object (e.g. for a CPC, a :class:`~zhmcclient.Cpc` object is returned). Any resource property may be specified in a filter argument. For details about filter arguments, see :ref:`Filtering`. The zhmcclient implementation handles the specified properties in an optimized way: Properties that can be filtered on the HMC are actually filtered there (this varies by resource type), and the remaining properties are filtered on the client side. If the "name" property is specified as the only filter argument, an optimized lookup is performed that uses a name-to-URI cache in this manager object. This this optimized lookup uses the specified match value for exact matching and is not interpreted as a regular expression. Authorization requirements: * see the `list()` method in the derived classes. Parameters: \\**filter_args: All keyword arguments are used as filter arguments. Specifying no keyword arguments causes no filtering to happen. See the examples for usage details. Returns: Resource object in scope of this manager object that matches the filter arguments. This resource object has a minimal set of properties. Raises: :exc:`~zhmcclient.NotFound`: No matching resource found. :exc:`~zhmcclient.NoUniqueMatch`: More than one matching resource found. : Exceptions raised by the `list()` methods in derived resource manager classes (see :ref:`Resources`). Examples: * The following example finds a CPC by its name. Because the 'name' resource property is also a valid Python variable name, there are two ways for the caller to specify the filter arguments for this method: As named parameters:: cpc = client.cpcs.find(name='CPC001') As a parameter dictionary:: filter_args = {'name': 'CPC0001'} cpc = client.cpcs.find(**filter_args) * The following example finds a CPC by its object ID. Because the 'object-id' resource property is not a valid Python variable name, the caller can specify the filter argument only as a parameter dictionary:: filter_args = {'object-id': '12345-abc...de-12345'} cpc = client.cpcs.find(**filter_args)
2.605178
3.35549
0.776393
uri = self._name_uri_cache.get(name) obj = self.resource_class( manager=self, uri=uri, name=name, properties=None) return obj
def find_by_name(self, name)
Find a resource by name (i.e. value of its 'name' resource property) and return its Python resource object (e.g. for a CPC, a :class:`~zhmcclient.Cpc` object is returned). This method performs an optimized lookup that uses a name-to-URI mapping cached in this manager object. This method is automatically used by the :meth:`~zhmcclient.BaseManager.find` and :meth:`~zhmcclient.BaseManager.findall` methods, so it does not normally need to be used directly by users. Authorization requirements: * see the `list()` method in the derived classes. Parameters: name (string): Name of the resource (value of its 'name' resource property). Regular expression matching is not supported for the name for this optimized lookup. Returns: Resource object in scope of this manager object that matches the filter arguments. This resource object has a minimal set of properties. Raises: :exc:`~zhmcclient.NotFound`: No matching resource found. : Exceptions raised by the `list()` methods in derived resource manager classes (see :ref:`Resources`). Examples: * The following example finds a CPC by its name:: cpc = client.cpcs.find_by_name('CPC001')
5.478735
7.350366
0.745369
od_saved = OrderedDict.__repr__ try: OrderedDict.__repr__ = dict.__repr__ yield finally: OrderedDict.__repr__ = od_saved
def pprint_for_ordereddict()
Context manager that causes pprint() to print OrderedDict objects as nicely as standard Python dictionary objects.
5.395082
4.571994
1.180028
for child_attr in resources: child_list = resources[child_attr] self._process_child_list(self, child_attr, child_list)
def add_resources(self, resources)
Add faked child resources to this resource, from the provided resource definitions. Duplicate resource names in the same scope are not permitted. Although this method is typically used to initially load the faked HMC with resource state just once, it can be invoked multiple times and can also be invoked on faked resources (e.g. on a faked CPC). Parameters: resources (dict): resource dictionary with definitions of faked child resources to be added. For an explanation of how the resource dictionary is set up, see the examples below. For requirements on and auto-generation of certain resource properties, see the ``add()`` methods of the various faked resource managers (e.g. :meth:`zhmcclient_mock.FakedCpcManager.add`). For example, the object-id or element-id properties and the corresponding uri properties are always auto-generated. The resource dictionary specifies a tree of resource managers and resources, in an alternating manner. It starts with the resource managers of child resources of the target resource, which contains a list of those child resources. For an HMC, the CPCs managed by the HMC would be its child resources. Each resource specifies its own properties (``properties`` key) and the resource managers for its child resources. For example, the CPC resource specifies its adapter child resources using the ``adapters`` key. The keys for the child resource managers are the attribute names of these resource managers in the parent resource. For example, the ``adapters`` key is named after the :attr:`zhmcclient.Cpc.adapters` attribute (which has the same name as in its corresponding faked CPC resource: :attr:`zhmcclient_mock.FakedCpc.adapters`). Raises: :exc:`zhmcclient_mock.InputError`: Some issue with the input resources. Examples: Example for targeting a faked HMC for adding a CPC with one adapter:: resources = { 'cpcs': [ # name of manager attribute for this resource { 'properties': { 'name': 'cpc_1', }, 'adapters': [ # name of manager attribute for this # resource { 'properties': { 'object-id': '12', 'name': 'ad_1', }, 'ports': [ { 'properties': { 'name': 'port_1', } }, ], }, ], }, ], } Example for targeting a faked CPC for adding an LPAR and a load activation profile:: resources = { 'lpars': [ # name of manager attribute for this resource { 'properties': { # object-id is not provided -> auto-generated # object-uri is not provided -> auto-generated 'name': 'lpar_1', }, }, ], 'load_activation_profiles': [ # name of manager attribute { 'properties': { # object-id is not provided -> auto-generated # object-uri is not provided -> auto-generated 'name': 'lpar_1', }, }, ], }
5.444254
8.692438
0.626321
resource = self.resource_class(self, properties) self._resources[resource.oid] = resource self._hmc.all_resources[resource.uri] = resource return resource
def add(self, properties)
Add a faked resource to this manager. For URI-based lookup, the resource is also added to the faked HMC. Parameters: properties (dict): Resource properties. If the URI property (e.g. 'object-uri') or the object ID property (e.g. 'object-id') are not specified, they will be auto-generated. Returns: FakedBaseResource: The faked resource object.
5.800816
5.836091
0.993956
uri = self._resources[oid].uri del self._resources[oid] del self._hmc.all_resources[uri]
def remove(self, oid)
Remove a faked resource from this manager. Parameters: oid (string): The object ID of the resource (e.g. value of the 'object-uri' property).
9.887001
10.787163
0.916553
res = list() for oid in self._resources: resource = self._resources[oid] if self._matches_filters(resource, filter_args): res.append(resource) return res
def list(self, filter_args=None)
List the faked resources of this manager. Parameters: filter_args (dict): Filter arguments. `None` causes no filtering to happen. See :meth:`~zhmcclient.BaseManager.list()` for details. Returns: list of FakedBaseResource: The faked resource objects of this manager.
3.860736
5.662395
0.68182
if self._console is None: self._console = self.list()[0] return self._console
def console(self)
The faked Console representing the faked HMC (an object of :class:`~zhmcclient_mock.FakedConsole`). The object is cached.
5.609549
5.953728
0.942191
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
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.
3.297988
2.884375
1.143398
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)
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.
3.50115
3.121192
1.121735
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
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.
4.139891
3.258517
1.270483
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)
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.
5.669331
4.541828
1.248249
devno_int = self._devno_pool.alloc() devno = "{:04X}".format(devno_int) return devno
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.
5.099126
5.182414
0.983929
devno_int = int(devno, 16) self._devno_pool.free(devno_int)
def devno_free(self, devno)
Free a device number allocated with :meth:`devno_alloc`. The device number must be allocated. Parameters: devno (string): The device number as four hexadecimal digits. Raises: ValueError: Device number not in pool range or not currently allocated.
4.295485
5.250628
0.81809
devno_int = int(devno, 16) self._devno_pool.free_if_allocated(devno_int)
def devno_free_if_allocated(self, devno)
Free a device number allocated with :meth:`devno_alloc`. If the device number is not currently allocated or not in the pool range, nothing happens. Parameters: devno (string): The device number as four hexadecimal digits.
3.793463
4.86913
0.779084
wwpn_int = self._wwpn_pool.alloc() wwpn = "AFFEAFFE0000" + "{:04X}".format(wwpn_int) return wwpn
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.
7.806667
5.652688
1.381054
wwpn_int = int(wwpn[-4:], 16) self._wwpn_pool.free(wwpn_int)
def wwpn_free(self, wwpn)
Free a WWPN allocated with :meth:`wwpn_alloc`. The WWPN must be allocated. Parameters: WWPN (string): The WWPN as 16 hexadecimal digits. Raises: ValueError: WWPN not in pool range or not currently allocated.
4.790776
6.382482
0.750613
wwpn_int = int(wwpn[-4:], 16) self._wwpn_pool.free_if_allocated(wwpn_int)
def wwpn_free_if_allocated(self, wwpn)
Free a WWPN allocated with :meth:`wwpn_alloc`. If the WWPN is not currently allocated or not in the pool range, nothing happens. Parameters: WWPN (string): The WWPN as 16 hexadecimal digits.
4.51527
5.989615
0.75385
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
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.
3.448973
2.12442
1.623489
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)
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.
3.297883
2.107973
1.564481
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
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.
4.89607
3.37172
1.452098
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)
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.
5.674128
4.24587
1.336388
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)
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.
2.368765
2.294889
1.032191
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]
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.
2.566793
2.604506
0.98552
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)
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.
2.53389
2.349321
1.078563
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]
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.
2.943019
3.248399
0.905991
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
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.
2.651186
2.623598
1.010515
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
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.
2.027251
2.024095
1.001559
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
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.
3.328517
3.191854
1.042816
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'
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.
2.400593
2.412192
0.995191
result = self.session.post(self.console.uri + '/user-roles', 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] user_role = UserRole(self, uri, name, props) self._name_uri_cache.update(name, uri) return user_role
def create(self, properties)
Create a new (user-defined) User Role in this HMC. Authorization requirements: * Task permission to the "Manage User Roles" task. Parameters: properties (dict): Initial property values. Allowable properties are defined in section 'Request body contents' in section 'Create User Role' in the :term:`HMC API` book. Returns: UserRole: The resource object for the new User Role. 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`
5.116864
4.176909
1.225036
# noqa: E501 if isinstance(permitted_object, BaseResource): perm_obj = permitted_object.uri perm_type = 'object' elif isinstance(permitted_object, six.string_types): perm_obj = permitted_object perm_type = 'object-class' else: raise TypeError( "permitted_object must be a string or BaseResource, but is: " "{}".format(type(permitted_object))) body = { 'permitted-object': perm_obj, 'permitted-object-type': perm_type, 'include-members': include_members, 'view-only-mode': view_only, } self.manager.session.post( self.uri + '/operations/add-permission', body=body)
def add_permission(self, permitted_object, include_members=False, view_only=True)
Add permission for the specified permitted object(s) to this User Role, thereby granting that permission to all users that have this User Role. The granted permission depends on the resource class of the permitted object(s): * For Task resources, the granted permission is task permission for that task. * For Group resources, the granted permission is object access permission for the group resource, and optionally also for the group members. * For any other resources, the granted permission is object access permission for these resources. The User Role must be user-defined. Authorization requirements: * Task permission to the "Manage User Roles" task. Parameters: permitted_object (:class:`~zhmcclient.BaseResource` or :term:`string`): Permitted object(s), either as a Python resource object (e.g. :class:`~zhmcclient.Partition`), or as a resource class string (e.g. 'partition'). Must not be `None`. include_members (bool): Controls whether for Group resources, the operation applies additionally to its group member resources. This parameter will be ignored when the permitted object does not specify Group resources. view_only (bool): Controls whether for Task resources, the operation aplies to the view-only version of the task (if `True`), or to the full version of the task (if `False`). Only certain tasks support a view-only version. This parameter will be ignored when the permitted object does not specify Task resources. Raises: :exc:`~zhmcclient.HTTPError` :exc:`~zhmcclient.ParseError` :exc:`~zhmcclient.AuthError` :exc:`~zhmcclient.ConnectionError`
2.34645
2.360478
0.994057
volreq_obj = copy.deepcopy(properties) volreq_obj['operation'] = 'create' 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) result = self.session.post( self.storage_group.uri + '/operations/modify', body=body) uri = result['element-uris'][0] storage_volume = self.resource_object(uri, properties) # The name is not guaranteed to be unique, so we don't maintain # a name-to-uri cache for storage volumes. return storage_volume
def create(self, properties, email_to_addresses=None, email_cc_addresses=None, email_insert=None)
Create a :term:`storage volume` in this storage group on the HMC, and optionally send emails to storage administrators requesting creation of the storage volume on the storage subsystem and setup of any resources related to the storage volume (e.g. LUN mask definition on the storage subsystem). This method performs the "Modify Storage Group Properties" operation, requesting creation of the volume. Authorization requirements: * Object-access permission to this storage group. * Task permission to the "Configure Storage - System Programmer" task. Parameters: properties (dict): Initial property values for the new volume. Allowable properties are the fields defined in the "storage-volume-request-info" nested object described for operation "Modify Storage Group Properties" in the :term:`HMC API` book. The valid fields are those for the "create" operation. The `operation` field must not be provided; it is set automatically to the value "create". The properties provided in this parameter will be copied and then amended with the `operation="create"` field, and then used as a single array item for the `storage-volumes` field in the request body of the "Modify Storage Group Properties" operation. Note that for storage volumes, the HMC does auto-generate a value for the "name" property, but that auto-generated name is not unique within the parent storage group. If you depend on a unique name, you need to specify a "name" property accordingly. 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. Returns: StorageVolume: The resource object for the new storage volume. The object will have the following properties set: - 'element-uri' as returned by the HMC - 'element-id' as determined from the 'element-uri' property - 'class' and 'parent' - additional properties as specified in the input properties Raises: :exc:`~zhmcclient.HTTPError` :exc:`~zhmcclient.ParseError` :exc:`~zhmcclient.AuthError` :exc:`~zhmcclient.ConnectionError` Example:: stovol1 = fcp_stogrp.storage_volumes.create( properties=dict( name='vol1', size=30, # GiB ))
2.91155
2.55497
1.139563
m = re.match(r'^/api/storage-groups/[^/]*/storage-volumes/([^/]*)$', self.uri) oid = m.group(1) return oid
def oid(self)
:term `unicode string`: The object ID of this storage volume. The object ID is unique within the parent storage group. Note that for storage volumes, the 'name' property is not unique and therefore cannot be used to identify a storage volume. Therefore, storage volumes provide easy access to the object ID, as a means to identify the storage volume in CLIs and other string-based tooling.
7.14037
3.825582
1.866479
volreq_obj = { 'operation': 'delete', '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.manager._name_uri_cache.delete( self.properties.get(self.manager._name_prop, None))
def delete(self, email_to_addresses=None, email_cc_addresses=None, email_insert=None)
Delete this storage volume on the HMC, and optionally send emails to storage administrators requesting deletion of the storage volume on the storage subsystem and cleanup of any resources related to the storage volume (e.g. LUN mask definitions on a storage subsystem). This method performs the "Modify Storage Group Properties" operation, requesting deletion 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: 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`
2.671577
2.311996
1.155528
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))
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`
2.374793
2.007332
1.18306
# The operation requires exactly 2 characters in lower case unit_address_2 = format(int(unit_address, 16), '02x') body = { 'control-unit-uri': control_unit.uri, 'unit-address': unit_address_2, } self.manager.session.post( self.uri + '/operations/fulfill-ficon-storage-volume', body=body)
def indicate_fulfillment_ficon(self, control_unit, unit_address)
TODO: Add ControlUnit objects etc for FICON support. Indicate completion of :term:`fulfillment` for this ECKD (=FICON) storage volume and provide identifying information (control unit and unit address) about the actual storage volume on the storage subsystem. Manually indicating fulfillment is required for all ECKD volumes, because they are not auto-discovered by the CPC. This method performs the "Fulfill FICON Storage Volume" HMC operation. Upon successful completion of this operation, the "fulfillment-state" property of this storage volume object will have been set to "complete". That is necessary for the CPC to be able to address and connect to the volume. If the "fulfillment-state" properties of all storage volumes in the owning storage group are "complete", the owning storage group's "fulfillment-state" property will also be set to "complete". Parameters: control_unit (:class:`~zhmcclient.ControlUnit`): Logical control unit (LCU) in which the backing ECKD volume is defined. unit_address (:term:`string`): Unit address of the backing ECKD volume within its logical control unit, as a hexadecimal number of up to 2 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`
6.003973
3.843163
1.562248
# The operation requires exactly 16 characters in lower case wwpn_16 = format(int(wwpn, 16), '016x') lun_16 = format(int(lun, 16), '016x') body = { 'world-wide-port-name': wwpn_16, 'logical-unit-number': lun_16, 'adapter-port-uri': host_port.uri, } self.manager.session.post( self.uri + '/operations/fulfill-fcp-storage-volume', body=body)
def indicate_fulfillment_fcp(self, wwpn, lun, host_port)
Indicate completion of :term:`fulfillment` for this FCP storage volume and provide identifying information (WWPN and LUN) about the actual storage volume on the storage subsystem. Manually indicating fulfillment is required for storage volumes that will be used as boot devices for a partition. The specified host port will be used to access the storage volume during boot of the partition. Because the CPC discovers storage volumes automatically, the fulfillment of non-boot volumes does not need to be manually indicated using this function (it may be indicated though before the CPC discovers a working communications path to the volume, but the role of the specified host port is not clear in this case). This method performs the "Fulfill FCP Storage Volume" HMC operation. Upon successful completion of this operation, the "fulfillment-state" property of this storage volume object will have been set to "complete". That is necessary for the CPC to be able to address and connect to the volume. If the "fulfillment-state" properties of all storage volumes in the owning storage group are "complete", the owning storage group's "fulfillment-state" property will also be set to "complete". Parameters: 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. host_port (:class:`~zhmcclient.Port`): Storage port on the CPC that will be used to boot from. 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`
3.696711
2.932872
1.260441
return "classname={!r}; read_timeout={!r}; read_retries={!r}; " \ "message={!r};". \ format(self.__class__.__name__, self.read_timeout, self.read_retries, self.args[0])
def str_def(self)
:term:`string`: The exception as a string in a Python definition-style format, e.g. for parsing by scripts: .. code-block:: text classname={}; read_timeout={}; read_retries={}; message={};
5.690309
2.745052
2.072933
return "classname={!r}; connect_retries={!r}; message={!r};". \ format(self.__class__.__name__, self.connect_retries, self.args[0])
def str_def(self)
:term:`string`: The exception as a string in a Python definition-style format, e.g. for parsing by scripts: .. code-block:: text classname={}; connect_retries={}; message={};
9.528188
3.336901
2.8554
return "classname={!r}; line={!r}; column={!r}; message={!r};". \ format(self.__class__.__name__, self.line, self.column, self.args[0])
def str_def(self)
:term:`string`: The exception as a string in a Python definition-style format, e.g. for parsing by scripts: .. code-block:: text classname={}; line={}; column={}; message={};
5.256377
2.901951
1.811325
return "classname={!r}; min_api_version={!r}; api_version={!r}; " \ "message={!r};". \ format(self.__class__.__name__, self.min_api_version, self.api_version, self.args[0])
def str_def(self)
:term:`string`: The exception as a string in a Python definition-style format, e.g. for parsing by scripts: .. code-block:: text classname={}; min_api_version={}; api_version={}; message={};
4.868738
2.498488
1.948673
return "classname={!r}; operation_timeout={!r}; message={!r};". \ format(self.__class__.__name__, self.operation_timeout, self.args[0])
def str_def(self)
:term:`string`: The exception as a string in a Python definition-style format, e.g. for parsing by scripts: .. code-block:: text classname={}; operation_timeout={}; message={};
8.940027
3.448732
2.592265
body = {'adapter-port-uri': port.uri} self.manager.session.post( self._uri + '/operations/reassign-storage-adapter-port', body=body) self.properties.update(body)
def reassign_port(self, port)
Reassign this HBA to a new underlying :term:`FCP port`. This method performs the HMC operation "Reassign Storage Adapter Port". Authorization requirements: * Object-access permission to the Partition containing this HBA. * Object-access permission to the Adapter with the new Port. * Task permission to the "Partition Details" task. Parameters: port (:class:`~zhmcclient.Port`): :term:`FCP port` to be used. Raises: :exc:`~zhmcclient.HTTPError`: See the HTTP status and reason codes of operation "Reassign Storage Adapter Port" in the :term:`HMC API` book. :exc:`~zhmcclient.ParseError` :exc:`~zhmcclient.AuthError` :exc:`~zhmcclient.ConnectionError`
8.00409
5.395326
1.483523
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
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`
3.309702
2.963085
1.116978
result = self.manager.session.get( self.uri + '/operations/get-connected-vnics') nic_uris = result['connected-vnic-uris'] nic_list = [] parts = {} # Key: Partition ID; Value: Partition object for nic_uri in nic_uris: m = re.match(r"^/api/partitions/([^/]+)/nics/([^/]+)/?$", nic_uri) part_id = m.group(1) nic_id = m.group(2) # We remember created Partition objects and reuse them. try: part = parts[part_id] except KeyError: part = self.manager.cpc.partitions.resource_object(part_id) parts[part_id] = part nic = part.nics.resource_object(nic_id) nic_list.append(nic) return nic_list
def get_connected_nics(self)
List the :term:`NICs <NIC>` connected to this Virtual Switch. This method performs the "Get Connected VNICs of a Virtual Switch" HMC operation. Authorization requirements: * Object-access permission to this CPC. * Object-access permission to the backing Adapter of this Virtual Switch. Returns: : A list of :term:`Nic` objects. These objects will be connected in the resource tree (i.e. have a parent :term:`Partition` object, etc.) and will have the following properties set: * `element-uri` * `element-id` * `parent` * `class` Raises: :exc:`~zhmcclient.HTTPError` :exc:`~zhmcclient.ParseError` :exc:`~zhmcclient.AuthError` :exc:`~zhmcclient.ConnectionError`
3.262568
2.604918
1.252465
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
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`
4.575094
3.936551
1.162209
body = { 'user-role-uri': user_role.uri } self.manager.session.post( self.uri + '/operations/add-user-role', body=body)
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`
5.173254
4.393709
1.177423
body = { 'user-role-uri': user_role.uri } self.manager.session.post( self.uri + '/operations/remove-user-role', body=body)
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`
4.736624
4.153422
1.140415
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)
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`
4.611453
4.690133
0.983224
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)
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`
4.077782
4.367527
0.933659
while True: with self._handover_cond: # Wait until MessageListener has a new notification while len(self._handover_dict) == 0: self._handover_cond.wait(self._wait_timeout) if self._handover_dict['headers'] is None: return # Process the notification yield (self._handover_dict['headers'], self._handover_dict['message']) # Indicate to MessageListener that we are ready for next # notification del self._handover_dict['headers'] del self._handover_dict['message'] self._handover_cond.notifyAll()
def notifications(self)
Generator method that yields all HMC notifications (= JMS messages) received by this notification receiver. Example:: receiver = zhmcclient.NotificationReceiver(topic, hmc, userid, password) for headers, message in receiver.notifications(): . . . Yields: : A tuple (headers, message) representing one HMC notification, with: * headers (dict): The notification header fields. Some important header fields (dict items) are: * 'notification-type' (string): The HMC notification type (e.g. 'os-message', 'job-completion', or others). * 'session-sequence-nr' (string): The sequence number of this HMC notification within the session created by this notification receiver object. This number starts at 0 when this receiver object is created, and is incremented each time an HMC notification is published to this receiver. * 'class' (string): The class name of the HMC resource publishing the HMC notification (e.g. 'partition'). * 'object-id' (string) or 'element-id' (string): The ID of the HMC resource publishing the HMC notification. For a complete list of notification header fields, see section "Message format" in chapter 4. "Asynchronous notification" in the :term:`HMC API` book. * message (:term:`JSON object`): Body of the HMC notification, converted into a JSON object. The properties of the JSON object vary by notification type. For a description of the JSON properties, see the sub-sections for each notification type within section "Notification message formats" in chapter 4. "Asynchronous notification" in the :term:`HMC API` book.
3.634767
3.343061
1.087257
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()
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).
5.95108
4.274231
1.392316
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 new notification self._handover_dict['headers'] = headers try: msg_obj = json.loads(message) except Exception: raise # TODO: Find better exception for this case self._handover_dict['message'] = msg_obj self._handover_cond.notifyAll()
def on_message(self, headers, message)
Event method that gets called when this listener has received a JMS message (representing an HMC notification). Parameters: headers (dict): JMS message headers, as described for `headers` tuple item returned by the :meth:`~zhmcclient.NotificationReceiver.notifications` method. message (string): JMS message body as a string, which contains a serialized JSON object. The JSON object is described in the `message` tuple item returned by the :meth:`~zhmcclient.NotificationReceiver.notifications` method).
4.161813
4.035295
1.031353
uri = self._base_uri # There is only one console object. if full_properties: props = self.session.get(uri) else: # Note: The Console resource's Object ID is not part of its URI. props = { self._uri_prop: uri, } resource_obj = self.resource_class( manager=self, uri=props[self._uri_prop], name=props.get(self._name_prop, None), properties=props) return [resource_obj]
def list(self, full_properties=True, filter_args=None)
List the (one) :term:`Console` representing the HMC this client is connected to. Authorization requirements: * None Parameters: full_properties (bool): Controls whether the full set of resource properties should be retrieved, vs. only a short set consisting of 'object-uri'. filter_args (dict): This parameter exists for consistency with other list() methods and will be ignored. Returns: : A list of :class:`~zhmcclient.Console` objects, containing the one :term:`Console` representing the HMC this client is connected to. Raises: :exc:`~zhmcclient.HTTPError` :exc:`~zhmcclient.ParseError` :exc:`~zhmcclient.AuthError` :exc:`~zhmcclient.ConnectionError`
5.104106
4.512986
1.130982
# We do here some lazy loading. if not self._storage_groups: self._storage_groups = StorageGroupManager(self) return self._storage_groups
def storage_groups(self)
:class:`~zhmcclient.StorageGroupManager`: Manager object for the Storage Groups in scope of this Console.
5.786421
4.849194
1.193275
# We do here some lazy loading. if not self._users: self._users = UserManager(self) return self._users
def users(self)
:class:`~zhmcclient.UserManager`: Access to the :term:`Users <User>` in this Console.
8.514685
6.570387
1.295918
# We do here some lazy loading. if not self._user_roles: self._user_roles = UserRoleManager(self) return self._user_roles
def user_roles(self)
:class:`~zhmcclient.UserRoleManager`: Access to the :term:`User Roles <User Role>` in this Console.
5.937143
4.778646
1.242432
# We do here some lazy loading. if not self._user_patterns: self._user_patterns = UserPatternManager(self) return self._user_patterns
def user_patterns(self)
:class:`~zhmcclient.UserPatternManager`: Access to the :term:`User Patterns <User Pattern>` in this Console.
6.087473
4.848991
1.25541
# We do here some lazy loading. if not self._password_rules: self._password_rules = PasswordRuleManager(self) return self._password_rules
def password_rules(self)
:class:`~zhmcclient.PasswordRuleManager`: Access to the :term:`Password Rules <Password Rule>` in this Console.
6.44249
4.930369
1.306695
# We do here some lazy loading. if not self._tasks: self._tasks = TaskManager(self) return self._tasks
def tasks(self)
:class:`~zhmcclient.TaskManager`: Access to the :term:`Tasks <Task>` in this Console.
8.397778
6.763185
1.24169
# We do here some lazy loading. if not self._ldap_server_definitions: self._ldap_server_definitions = LdapServerDefinitionManager(self) return self._ldap_server_definitions
def ldap_server_definitions(self)
:class:`~zhmcclient.LdapServerDefinitionManager`: Access to the :term:`LDAP Server Definitions <LDAP Server Definition>` in this Console.
4.458018
3.688098
1.208758
# We do here some lazy loading. if not self._unmanaged_cpcs: self._unmanaged_cpcs = UnmanagedCpcManager(self) return self._unmanaged_cpcs
def unmanaged_cpcs(self)
:class:`~zhmcclient.UnmanagedCpcManager`: Access to the unmanaged :term:`CPCs <CPC>` in this Console.
5.557804
4.03863
1.376161
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)
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.
3.48174
4.811282
0.723662
body = {'force': force} self.manager.session.post(self.uri + '/operations/shutdown', body=body)
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`
6.928641
7.750426
0.893969
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
def _time_query_parms(begin_time, end_time)
Return the URI query paramterer string for the specified begin time and end time.
1.643176
1.573171
1.044499
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
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`
4.835946
4.617509
1.047306
filter_args = dict() if name is not None: filter_args['name'] = name cpcs = self.unmanaged_cpcs.list(filter_args=filter_args) return cpcs
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`
2.628294
3.765915
0.697916
# We do here some lazy loading. if not self._lpars: self._lpars = LparManager(self) return self._lpars
def lpars(self)
:class:`~zhmcclient.LparManager`: Access to the :term:`LPARs <LPAR>` in this CPC.
7.943796
5.295362
1.500142
# We do here some lazy loading. if not self._partitions: self._partitions = PartitionManager(self) return self._partitions
def partitions(self)
:class:`~zhmcclient.PartitionManager`: Access to the :term:`Partitions <Partition>` in this CPC.
8.726624
6.743738
1.294034
# We do here some lazy loading. if not self._adapters: self._adapters = AdapterManager(self) return self._adapters
def adapters(self)
:class:`~zhmcclient.AdapterManager`: Access to the :term:`Adapters <Adapter>` in this CPC.
8.242954
6.811649
1.210126
# We do here some lazy loading. if not self._virtual_switches: self._virtual_switches = VirtualSwitchManager(self) return self._virtual_switches
def virtual_switches(self)
:class:`~zhmcclient.VirtualSwitchManager`: Access to the :term:`Virtual Switches <Virtual Switch>` in this CPC.
5.126836
4.188794
1.223941