id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
51
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
15,100
zhmcclient/python-zhmcclient
zhmcclient_mock/_hmc.py
FakedHbaManager.add
def add(self, properties): """ Add a faked HBA resource. Parameters: properties (dict): Resource properties. Special handling and requirements for certain properties: * 'element-id' will be auto-generated with a unique value across all instances of this resource type, if not specified. * 'element-uri' will be auto-generated based upon the element ID, if not specified. * 'class' will be auto-generated to 'hba', if not specified. * 'adapter-port-uri' identifies the backing FCP port for this HBA and is required to be specified. * 'device-number' will be auto-generated with a unique value within the partition in the range 0x8000 to 0xFFFF, if not specified. This method also updates the 'hba-uris' property in the parent faked Partition resource, by adding the URI for the faked HBA resource. Returns: :class:`~zhmcclient_mock.FakedHba`: The faked HBA resource. Raises: :exc:`zhmcclient_mock.InputError`: Some issue with the input properties. """ new_hba = super(FakedHbaManager, self).add(properties) partition = self.parent # Reflect the new NIC in the partition assert 'hba-uris' in partition.properties partition.properties['hba-uris'].append(new_hba.uri) # Create a default device-number if not specified if 'device-number' not in new_hba.properties: devno = partition.devno_alloc() new_hba.properties['device-number'] = devno # Create a default wwpn if not specified if 'wwpn' not in new_hba.properties: wwpn = partition.wwpn_alloc() new_hba.properties['wwpn'] = wwpn return new_hba
python
def add(self, properties): new_hba = super(FakedHbaManager, self).add(properties) partition = self.parent # Reflect the new NIC in the partition assert 'hba-uris' in partition.properties partition.properties['hba-uris'].append(new_hba.uri) # Create a default device-number if not specified if 'device-number' not in new_hba.properties: devno = partition.devno_alloc() new_hba.properties['device-number'] = devno # Create a default wwpn if not specified if 'wwpn' not in new_hba.properties: wwpn = partition.wwpn_alloc() new_hba.properties['wwpn'] = wwpn return new_hba
[ "def", "add", "(", "self", ",", "properties", ")", ":", "new_hba", "=", "super", "(", "FakedHbaManager", ",", "self", ")", ".", "add", "(", "properties", ")", "partition", "=", "self", ".", "parent", "# Reflect the new NIC in the partition", "assert", "'hba-ur...
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.
[ "Add", "a", "faked", "HBA", "resource", "." ]
9657563e5d9184c51d3c903442a58b9725fdf335
https://github.com/zhmcclient/python-zhmcclient/blob/9657563e5d9184c51d3c903442a58b9725fdf335/zhmcclient_mock/_hmc.py#L1760-L1812
15,101
zhmcclient/python-zhmcclient
zhmcclient_mock/_hmc.py
FakedHbaManager.remove
def remove(self, oid): """ Remove a faked HBA resource. This method also updates the 'hba-uris' property in the parent Partition resource, by removing the URI for the faked HBA resource. Parameters: oid (string): The object ID of the faked HBA resource. """ hba = self.lookup_by_oid(oid) partition = self.parent devno = hba.properties.get('device-number', None) if devno: partition.devno_free_if_allocated(devno) wwpn = hba.properties.get('wwpn', None) if wwpn: partition.wwpn_free_if_allocated(wwpn) assert 'hba-uris' in partition.properties hba_uris = partition.properties['hba-uris'] hba_uris.remove(hba.uri) super(FakedHbaManager, self).remove(oid)
python
def remove(self, oid): 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", ")", ":", "hba", "=", "self", ".", "lookup_by_oid", "(", "oid", ")", "partition", "=", "self", ".", "parent", "devno", "=", "hba", ".", "properties", ".", "get", "(", "'device-number'", ",", "None", ")", "if"...
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.
[ "Remove", "a", "faked", "HBA", "resource", "." ]
9657563e5d9184c51d3c903442a58b9725fdf335
https://github.com/zhmcclient/python-zhmcclient/blob/9657563e5d9184c51d3c903442a58b9725fdf335/zhmcclient_mock/_hmc.py#L1814-L1837
15,102
zhmcclient/python-zhmcclient
zhmcclient_mock/_hmc.py
FakedNicManager.add
def add(self, properties): """ Add a faked NIC resource. Parameters: properties (dict): Resource properties. Special handling and requirements for certain properties: * 'element-id' will be auto-generated with a unique value across all instances of this resource type, if not specified. * 'element-uri' will be auto-generated based upon the element ID, if not specified. * 'class' will be auto-generated to 'nic', if not specified. * Either 'network-adapter-port-uri' (for backing ROCE adapters) or 'virtual-switch-uri'(for backing OSA or Hipersockets adapters) is required to be specified. * 'device-number' will be auto-generated with a unique value within the partition in the range 0x8000 to 0xFFFF, if not specified. This method also updates the 'nic-uris' property in the parent faked Partition resource, by adding the URI for the faked NIC resource. This method also updates the 'connected-vnic-uris' property in the virtual switch referenced by 'virtual-switch-uri' property, and sets it to the URI of the faked NIC resource. Returns: :class:`zhmcclient_mock.FakedNic`: The faked NIC resource. Raises: :exc:`zhmcclient_mock.InputError`: Some issue with the input properties. """ new_nic = super(FakedNicManager, self).add(properties) partition = self.parent # For OSA-backed NICs, reflect the new NIC in the virtual switch if 'virtual-switch-uri' in new_nic.properties: vswitch_uri = new_nic.properties['virtual-switch-uri'] # Even though the URI handler when calling this method ensures that # the vswitch exists, this method can be called by the user as # well, so we have to handle the possibility that it does not # exist: try: vswitch = self.hmc.lookup_by_uri(vswitch_uri) except KeyError: raise InputError("The virtual switch specified in the " "'virtual-switch-uri' property does not " "exist: {!r}".format(vswitch_uri)) connected_uris = vswitch.properties['connected-vnic-uris'] if new_nic.uri not in connected_uris: connected_uris.append(new_nic.uri) # Create a default device-number if not specified if 'device-number' not in new_nic.properties: devno = partition.devno_alloc() new_nic.properties['device-number'] = devno # Reflect the new NIC in the partition assert 'nic-uris' in partition.properties partition.properties['nic-uris'].append(new_nic.uri) return new_nic
python
def add(self, properties): new_nic = super(FakedNicManager, self).add(properties) partition = self.parent # For OSA-backed NICs, reflect the new NIC in the virtual switch if 'virtual-switch-uri' in new_nic.properties: vswitch_uri = new_nic.properties['virtual-switch-uri'] # Even though the URI handler when calling this method ensures that # the vswitch exists, this method can be called by the user as # well, so we have to handle the possibility that it does not # exist: try: vswitch = self.hmc.lookup_by_uri(vswitch_uri) except KeyError: raise InputError("The virtual switch specified in the " "'virtual-switch-uri' property does not " "exist: {!r}".format(vswitch_uri)) connected_uris = vswitch.properties['connected-vnic-uris'] if new_nic.uri not in connected_uris: connected_uris.append(new_nic.uri) # Create a default device-number if not specified if 'device-number' not in new_nic.properties: devno = partition.devno_alloc() new_nic.properties['device-number'] = devno # Reflect the new NIC in the partition assert 'nic-uris' in partition.properties partition.properties['nic-uris'].append(new_nic.uri) return new_nic
[ "def", "add", "(", "self", ",", "properties", ")", ":", "new_nic", "=", "super", "(", "FakedNicManager", ",", "self", ")", ".", "add", "(", "properties", ")", "partition", "=", "self", ".", "parent", "# For OSA-backed NICs, reflect the new NIC in the virtual switc...
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.
[ "Add", "a", "faked", "NIC", "resource", "." ]
9657563e5d9184c51d3c903442a58b9725fdf335
https://github.com/zhmcclient/python-zhmcclient/blob/9657563e5d9184c51d3c903442a58b9725fdf335/zhmcclient_mock/_hmc.py#L1935-L2004
15,103
zhmcclient/python-zhmcclient
zhmcclient_mock/_hmc.py
FakedNicManager.remove
def remove(self, oid): """ Remove a faked NIC resource. This method also updates the 'nic-uris' property in the parent Partition resource, by removing the URI for the faked NIC resource. Parameters: oid (string): The object ID of the faked NIC resource. """ nic = self.lookup_by_oid(oid) partition = self.parent devno = nic.properties.get('device-number', None) if devno: partition.devno_free_if_allocated(devno) assert 'nic-uris' in partition.properties nic_uris = partition.properties['nic-uris'] nic_uris.remove(nic.uri) super(FakedNicManager, self).remove(oid)
python
def remove(self, oid): 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", ")", ":", "nic", "=", "self", ".", "lookup_by_oid", "(", "oid", ")", "partition", "=", "self", ".", "parent", "devno", "=", "nic", ".", "properties", ".", "get", "(", "'device-number'", ",", "None", ")", "if"...
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.
[ "Remove", "a", "faked", "NIC", "resource", "." ]
9657563e5d9184c51d3c903442a58b9725fdf335
https://github.com/zhmcclient/python-zhmcclient/blob/9657563e5d9184c51d3c903442a58b9725fdf335/zhmcclient_mock/_hmc.py#L2006-L2026
15,104
zhmcclient/python-zhmcclient
zhmcclient_mock/_hmc.py
FakedPartition.devno_alloc
def devno_alloc(self): """ Allocates a device number unique to this partition, in the range of 0x8000 to 0xFFFF. Returns: string: The device number as four hexadecimal digits in upper case. Raises: ValueError: No more device numbers available in that range. """ devno_int = self._devno_pool.alloc() devno = "{:04X}".format(devno_int) return devno
python
def devno_alloc(self): devno_int = self._devno_pool.alloc() devno = "{:04X}".format(devno_int) return devno
[ "def", "devno_alloc", "(", "self", ")", ":", "devno_int", "=", "self", ".", "_devno_pool", ".", "alloc", "(", ")", "devno", "=", "\"{:04X}\"", ".", "format", "(", "devno_int", ")", "return", "devno" ]
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.
[ "Allocates", "a", "device", "number", "unique", "to", "this", "partition", "in", "the", "range", "of", "0x8000", "to", "0xFFFF", "." ]
9657563e5d9184c51d3c903442a58b9725fdf335
https://github.com/zhmcclient/python-zhmcclient/blob/9657563e5d9184c51d3c903442a58b9725fdf335/zhmcclient_mock/_hmc.py#L2181-L2194
15,105
zhmcclient/python-zhmcclient
zhmcclient_mock/_hmc.py
FakedPartition.wwpn_alloc
def wwpn_alloc(self): """ Allocates a WWPN unique to this partition, in the range of 0xAFFEAFFE00008000 to 0xAFFEAFFE0000FFFF. Returns: string: The WWPN as 16 hexadecimal digits in upper case. Raises: ValueError: No more WWPNs available in that range. """ wwpn_int = self._wwpn_pool.alloc() wwpn = "AFFEAFFE0000" + "{:04X}".format(wwpn_int) return wwpn
python
def wwpn_alloc(self): wwpn_int = self._wwpn_pool.alloc() wwpn = "AFFEAFFE0000" + "{:04X}".format(wwpn_int) return wwpn
[ "def", "wwpn_alloc", "(", "self", ")", ":", "wwpn_int", "=", "self", ".", "_wwpn_pool", ".", "alloc", "(", ")", "wwpn", "=", "\"AFFEAFFE0000\"", "+", "\"{:04X}\"", ".", "format", "(", "wwpn_int", ")", "return", "wwpn" ]
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.
[ "Allocates", "a", "WWPN", "unique", "to", "this", "partition", "in", "the", "range", "of", "0xAFFEAFFE00008000", "to", "0xAFFEAFFE0000FFFF", "." ]
9657563e5d9184c51d3c903442a58b9725fdf335
https://github.com/zhmcclient/python-zhmcclient/blob/9657563e5d9184c51d3c903442a58b9725fdf335/zhmcclient_mock/_hmc.py#L2225-L2238
15,106
zhmcclient/python-zhmcclient
zhmcclient_mock/_hmc.py
FakedPortManager.add
def add(self, properties): """ Add a faked Port resource. Parameters: properties (dict): Resource properties. Special handling and requirements for certain properties: * 'element-id' will be auto-generated with a unique value across all instances of this resource type, if not specified. * 'element-uri' will be auto-generated based upon the element ID, if not specified. * 'class' will be auto-generated to 'network-port' or 'storage-port', if not specified. This method also updates the 'network-port-uris' or 'storage-port-uris' property in the parent Adapter resource, by adding the URI for the faked Port resource. Returns: :class:`zhmcclient_mock.FakedPort`: The faked Port resource. """ new_port = super(FakedPortManager, self).add(properties) adapter = self.parent if 'network-port-uris' in adapter.properties: adapter.properties['network-port-uris'].append(new_port.uri) if 'storage-port-uris' in adapter.properties: adapter.properties['storage-port-uris'].append(new_port.uri) return new_port
python
def add(self, properties): 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", ")", ":", "new_port", "=", "super", "(", "FakedPortManager", ",", "self", ")", ".", "add", "(", "properties", ")", "adapter", "=", "self", ".", "parent", "if", "'network-port-uris'", "in", "adapter", ".", "pr...
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.
[ "Add", "a", "faked", "Port", "resource", "." ]
9657563e5d9184c51d3c903442a58b9725fdf335
https://github.com/zhmcclient/python-zhmcclient/blob/9657563e5d9184c51d3c903442a58b9725fdf335/zhmcclient_mock/_hmc.py#L2300-L2331
15,107
zhmcclient/python-zhmcclient
zhmcclient_mock/_hmc.py
FakedPortManager.remove
def remove(self, oid): """ Remove a faked Port resource. This method also updates the 'network-port-uris' or 'storage-port-uris' property in the parent Adapter resource, by removing the URI for the faked Port resource. Parameters: oid (string): The object ID of the faked Port resource. """ port = self.lookup_by_oid(oid) adapter = self.parent if 'network-port-uris' in adapter.properties: port_uris = adapter.properties['network-port-uris'] port_uris.remove(port.uri) if 'storage-port-uris' in adapter.properties: port_uris = adapter.properties['storage-port-uris'] port_uris.remove(port.uri) super(FakedPortManager, self).remove(oid)
python
def remove(self, oid): 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", ")", ":", "port", "=", "self", ".", "lookup_by_oid", "(", "oid", ")", "adapter", "=", "self", ".", "parent", "if", "'network-port-uris'", "in", "adapter", ".", "properties", ":", "port_uris", "=", "adapter", ".",...
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.
[ "Remove", "a", "faked", "Port", "resource", "." ]
9657563e5d9184c51d3c903442a58b9725fdf335
https://github.com/zhmcclient/python-zhmcclient/blob/9657563e5d9184c51d3c903442a58b9725fdf335/zhmcclient_mock/_hmc.py#L2333-L2354
15,108
zhmcclient/python-zhmcclient
zhmcclient_mock/_hmc.py
FakedVirtualFunctionManager.add
def add(self, properties): """ Add a faked Virtual Function resource. Parameters: properties (dict): Resource properties. Special handling and requirements for certain properties: * 'element-id' will be auto-generated with a unique value across all instances of this resource type, if not specified. * 'element-uri' will be auto-generated based upon the element ID, if not specified. * 'class' will be auto-generated to 'virtual-function', if not specified. * 'device-number' will be auto-generated with a unique value within the partition in the range 0x8000 to 0xFFFF, if not specified. This method also updates the 'virtual-function-uris' property in the parent Partition resource, by adding the URI for the faked Virtual Function resource. Returns: :class:`zhmcclient_mock.FakedVirtualFunction`: The faked Virtual Function resource. """ new_vf = super(FakedVirtualFunctionManager, self).add(properties) partition = self.parent assert 'virtual-function-uris' in partition.properties partition.properties['virtual-function-uris'].append(new_vf.uri) if 'device-number' not in new_vf.properties: devno = partition.devno_alloc() new_vf.properties['device-number'] = devno return new_vf
python
def add(self, properties): 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", ")", ":", "new_vf", "=", "super", "(", "FakedVirtualFunctionManager", ",", "self", ")", ".", "add", "(", "properties", ")", "partition", "=", "self", ".", "parent", "assert", "'virtual-function-uris'", "in", "par...
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.
[ "Add", "a", "faked", "Virtual", "Function", "resource", "." ]
9657563e5d9184c51d3c903442a58b9725fdf335
https://github.com/zhmcclient/python-zhmcclient/blob/9657563e5d9184c51d3c903442a58b9725fdf335/zhmcclient_mock/_hmc.py#L2391-L2427
15,109
zhmcclient/python-zhmcclient
zhmcclient_mock/_hmc.py
FakedVirtualFunctionManager.remove
def remove(self, oid): """ Remove a faked Virtual Function resource. This method also updates the 'virtual-function-uris' property in the parent Partition resource, by removing the URI for the faked Virtual Function resource. Parameters: oid (string): The object ID of the faked Virtual Function resource. """ virtual_function = self.lookup_by_oid(oid) partition = self.parent devno = virtual_function.properties.get('device-number', None) if devno: partition.devno_free_if_allocated(devno) assert 'virtual-function-uris' in partition.properties vf_uris = partition.properties['virtual-function-uris'] vf_uris.remove(virtual_function.uri) super(FakedVirtualFunctionManager, self).remove(oid)
python
def remove(self, oid): 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", ")", ":", "virtual_function", "=", "self", ".", "lookup_by_oid", "(", "oid", ")", "partition", "=", "self", ".", "parent", "devno", "=", "virtual_function", ".", "properties", ".", "get", "(", "'device-number'", ",...
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.
[ "Remove", "a", "faked", "Virtual", "Function", "resource", "." ]
9657563e5d9184c51d3c903442a58b9725fdf335
https://github.com/zhmcclient/python-zhmcclient/blob/9657563e5d9184c51d3c903442a58b9725fdf335/zhmcclient_mock/_hmc.py#L2429-L2450
15,110
zhmcclient/python-zhmcclient
zhmcclient_mock/_hmc.py
FakedMetricsContextManager.add_metric_group_definition
def add_metric_group_definition(self, definition): """ Add a faked metric group definition. The definition will be used: * For later addition of faked metrics responses. * For returning the metric-group-info objects in the response of the Create Metrics Context operations. For defined metric groups, see chapter "Metric groups" in the :term:`HMC API` book. Parameters: definition (:class:~zhmcclient.FakedMetricGroupDefinition`): Definition of the metric group. Raises: ValueError: A metric group definition with this name already exists. """ assert isinstance(definition, FakedMetricGroupDefinition) group_name = definition.name if group_name in self._metric_group_defs: raise ValueError("A metric group definition with this name " "already exists: {}".format(group_name)) self._metric_group_defs[group_name] = definition self._metric_group_def_names.append(group_name)
python
def add_metric_group_definition(self, definition): 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", ")", ":", "assert", "isinstance", "(", "definition", ",", "FakedMetricGroupDefinition", ")", "group_name", "=", "definition", ".", "name", "if", "group_name", "in", "self", ".", "_metric_group_def...
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.
[ "Add", "a", "faked", "metric", "group", "definition", "." ]
9657563e5d9184c51d3c903442a58b9725fdf335
https://github.com/zhmcclient/python-zhmcclient/blob/9657563e5d9184c51d3c903442a58b9725fdf335/zhmcclient_mock/_hmc.py#L2820-L2848
15,111
zhmcclient/python-zhmcclient
zhmcclient_mock/_hmc.py
FakedMetricsContextManager.get_metric_group_definition
def get_metric_group_definition(self, group_name): """ Get a faked metric group definition by its group name. Parameters: group_name (:term:`string`): Name of the metric group. Returns: :class:~zhmcclient.FakedMetricGroupDefinition`: Definition of the metric group. Raises: ValueError: A metric group definition with this name does not exist. """ if group_name not in self._metric_group_defs: raise ValueError("A metric group definition with this name does " "not exist: {}".format(group_name)) return self._metric_group_defs[group_name]
python
def get_metric_group_definition(self, group_name): 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", ")", ":", "if", "group_name", "not", "in", "self", ".", "_metric_group_defs", ":", "raise", "ValueError", "(", "\"A metric group definition with this name does \"", "\"not exist: {}\"", ".", "format", ...
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.
[ "Get", "a", "faked", "metric", "group", "definition", "by", "its", "group", "name", "." ]
9657563e5d9184c51d3c903442a58b9725fdf335
https://github.com/zhmcclient/python-zhmcclient/blob/9657563e5d9184c51d3c903442a58b9725fdf335/zhmcclient_mock/_hmc.py#L2850-L2870
15,112
zhmcclient/python-zhmcclient
zhmcclient_mock/_hmc.py
FakedMetricsContextManager.add_metric_values
def add_metric_values(self, values): """ Add one set of faked metric values for a particular resource to the metrics response for a particular metric group, for later retrieval. For defined metric groups, see chapter "Metric groups" in the :term:`HMC API` book. Parameters: values (:class:`~zhmclient.FakedMetricObjectValues`): The set of metric values to be added. It specifies the resource URI and the targeted metric group name. """ assert isinstance(values, FakedMetricObjectValues) group_name = values.group_name if group_name not in self._metric_values: self._metric_values[group_name] = [] self._metric_values[group_name].append(values) if group_name not in self._metric_value_names: self._metric_value_names.append(group_name)
python
def add_metric_values(self, values): 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", ")", ":", "assert", "isinstance", "(", "values", ",", "FakedMetricObjectValues", ")", "group_name", "=", "values", ".", "group_name", "if", "group_name", "not", "in", "self", ".", "_metric_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.
[ "Add", "one", "set", "of", "faked", "metric", "values", "for", "a", "particular", "resource", "to", "the", "metrics", "response", "for", "a", "particular", "metric", "group", "for", "later", "retrieval", "." ]
9657563e5d9184c51d3c903442a58b9725fdf335
https://github.com/zhmcclient/python-zhmcclient/blob/9657563e5d9184c51d3c903442a58b9725fdf335/zhmcclient_mock/_hmc.py#L2883-L2903
15,113
zhmcclient/python-zhmcclient
zhmcclient_mock/_hmc.py
FakedMetricsContextManager.get_metric_values
def get_metric_values(self, group_name): """ Get the faked metric values for a metric group, by its metric group name. The result includes all metric object values added earlier for that metric group name, using :meth:`~zhmcclient.FakedMetricsContextManager.add_metric_object_values` i.e. the metric values for all resources and all points in time that were added. Parameters: group_name (:term:`string`): Name of the metric group. Returns: iterable of :class:`~zhmclient.FakedMetricObjectValues`: The metric values for that metric group, in the order they had been added. Raises: ValueError: Metric values for this group name do not exist. """ if group_name not in self._metric_values: raise ValueError("Metric values for this group name do not " "exist: {}".format(group_name)) return self._metric_values[group_name]
python
def get_metric_values(self, group_name): 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", ")", ":", "if", "group_name", "not", "in", "self", ".", "_metric_values", ":", "raise", "ValueError", "(", "\"Metric values for this group name do not \"", "\"exist: {}\"", ".", "format", "(", "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.
[ "Get", "the", "faked", "metric", "values", "for", "a", "metric", "group", "by", "its", "metric", "group", "name", "." ]
9657563e5d9184c51d3c903442a58b9725fdf335
https://github.com/zhmcclient/python-zhmcclient/blob/9657563e5d9184c51d3c903442a58b9725fdf335/zhmcclient_mock/_hmc.py#L2905-L2932
15,114
zhmcclient/python-zhmcclient
zhmcclient_mock/_hmc.py
FakedMetricsContext.get_metric_group_definitions
def get_metric_group_definitions(self): """ Get the faked metric group definitions for this context object that are to be returned from its create operation. If a 'metric-groups' property had been specified for this context, only those faked metric group definitions of its manager object that are in that list, are included in the result. Otherwise, all metric group definitions of its manager are included in the result. Returns: iterable of :class:~zhmcclient.FakedMetricGroupDefinition`: The faked metric group definitions, in the order they had been added. """ group_names = self.properties.get('metric-groups', None) if not group_names: group_names = self.manager.get_metric_group_definition_names() mg_defs = [] for group_name in group_names: try: mg_def = self.manager.get_metric_group_definition(group_name) mg_defs.append(mg_def) except ValueError: pass # ignore metric groups without metric group defs return mg_defs
python
def get_metric_group_definitions(self): 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", ")", ":", "group_names", "=", "self", ".", "properties", ".", "get", "(", "'metric-groups'", ",", "None", ")", "if", "not", "group_names", ":", "group_names", "=", "self", ".", "manager", ".", "get_metric_gro...
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.
[ "Get", "the", "faked", "metric", "group", "definitions", "for", "this", "context", "object", "that", "are", "to", "be", "returned", "from", "its", "create", "operation", "." ]
9657563e5d9184c51d3c903442a58b9725fdf335
https://github.com/zhmcclient/python-zhmcclient/blob/9657563e5d9184c51d3c903442a58b9725fdf335/zhmcclient_mock/_hmc.py#L2995-L3020
15,115
zhmcclient/python-zhmcclient
zhmcclient_mock/_hmc.py
FakedMetricsContext.get_metric_group_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. """ mg_defs = self.get_metric_group_definitions() mg_infos = [] for mg_def in mg_defs: metric_infos = [] for metric_name, metric_type in mg_def.types: metric_infos.append({ 'metric-name': metric_name, 'metric-type': metric_type, }) mg_info = { 'group-name': mg_def.name, 'metric-infos': metric_infos, } mg_infos.append(mg_info) return mg_infos
python
def get_metric_group_infos(self): 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", ")", ":", "mg_defs", "=", "self", ".", "get_metric_group_definitions", "(", ")", "mg_infos", "=", "[", "]", "for", "mg_def", "in", "mg_defs", ":", "metric_infos", "=", "[", "]", "for", "metric_name", ",", "metric...
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.
[ "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"...
9657563e5d9184c51d3c903442a58b9725fdf335
https://github.com/zhmcclient/python-zhmcclient/blob/9657563e5d9184c51d3c903442a58b9725fdf335/zhmcclient_mock/_hmc.py#L3022-L3047
15,116
zhmcclient/python-zhmcclient
zhmcclient_mock/_hmc.py
FakedMetricsContext.get_metric_values
def get_metric_values(self): """ Get the faked metrics, for all metric groups and all resources that have been prepared on the manager object of this context object. Returns: iterable of tuple (group_name, iterable of values): The faked metrics, in the order they had been added, where: group_name (string): Metric group name. values (:class:~zhmcclient.FakedMetricObjectValues`): The metric values for one resource at one point in time. """ group_names = self.properties.get('metric-groups', None) if not group_names: group_names = self.manager.get_metric_values_group_names() ret = [] for group_name in group_names: try: mo_val = self.manager.get_metric_values(group_name) ret_item = (group_name, mo_val) ret.append(ret_item) except ValueError: pass # ignore metric groups without metric values return ret
python
def get_metric_values(self): 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", ")", ":", "group_names", "=", "self", ".", "properties", ".", "get", "(", "'metric-groups'", ",", "None", ")", "if", "not", "group_names", ":", "group_names", "=", "self", ".", "manager", ".", "get_metric_values_group_n...
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.
[ "Get", "the", "faked", "metrics", "for", "all", "metric", "groups", "and", "all", "resources", "that", "have", "been", "prepared", "on", "the", "manager", "object", "of", "this", "context", "object", "." ]
9657563e5d9184c51d3c903442a58b9725fdf335
https://github.com/zhmcclient/python-zhmcclient/blob/9657563e5d9184c51d3c903442a58b9725fdf335/zhmcclient_mock/_hmc.py#L3049-L3075
15,117
zhmcclient/python-zhmcclient
zhmcclient_mock/_hmc.py
FakedMetricsContext.get_metric_values_response
def get_metric_values_response(self): """ Get the faked metrics, for all metric groups and all resources that have been prepared on the manager object of this context object, as a string in the format needed for the "Get Metrics" operation response. Returns: "MetricsResponse" string as described for the "Get Metrics" operation response. """ mv_list = self.get_metric_values() resp_lines = [] for mv in mv_list: group_name = mv[0] resp_lines.append('"{}"'.format(group_name)) mo_vals = mv[1] for mo_val in mo_vals: resp_lines.append('"{}"'.format(mo_val.resource_uri)) resp_lines.append( str(timestamp_from_datetime(mo_val.timestamp))) v_list = [] for n, v in mo_val.values: if isinstance(v, six.string_types): v_str = '"{}"'.format(v) else: v_str = str(v) v_list.append(v_str) v_line = ','.join(v_list) resp_lines.append(v_line) resp_lines.append('') resp_lines.append('') resp_lines.append('') return '\n'.join(resp_lines) + '\n'
python
def get_metric_values_response(self): 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", ")", ":", "mv_list", "=", "self", ".", "get_metric_values", "(", ")", "resp_lines", "=", "[", "]", "for", "mv", "in", "mv_list", ":", "group_name", "=", "mv", "[", "0", "]", "resp_lines", ".", "append", "...
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.
[ "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", "f...
9657563e5d9184c51d3c903442a58b9725fdf335
https://github.com/zhmcclient/python-zhmcclient/blob/9657563e5d9184c51d3c903442a58b9725fdf335/zhmcclient_mock/_hmc.py#L3077-L3110
15,118
zhmcclient/python-zhmcclient
zhmcclient/_storage_volume.py
StorageVolume.update_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` """ volreq_obj = copy.deepcopy(properties) volreq_obj['operation'] = 'modify' volreq_obj['element-uri'] = self.uri body = { 'storage-volumes': [volreq_obj], } if email_to_addresses: body['email-to-addresses'] = email_to_addresses if email_cc_addresses: body['email-cc-addresses'] = email_cc_addresses if email_insert: body['email-insert'] = email_insert else: if email_cc_addresses: raise ValueError("email_cc_addresses must not be specified if " "there is no email_to_addresses: %r" % email_cc_addresses) if email_insert: raise ValueError("email_insert must not be specified if " "there is no email_to_addresses: %r" % email_insert) self.manager.session.post( self.manager.storage_group.uri + '/operations/modify', body=body) self.properties.update(copy.deepcopy(properties))
python
def update_properties(self, properties, email_to_addresses=None, email_cc_addresses=None, email_insert=None): 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", ")", ":", "volreq_obj", "=", "copy", ".", "deepcopy", "(", "properties", ")", "volreq_...
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`
[ "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...
9657563e5d9184c51d3c903442a58b9725fdf335
https://github.com/zhmcclient/python-zhmcclient/blob/9657563e5d9184c51d3c903442a58b9725fdf335/zhmcclient/_storage_volume.py#L411-L493
15,119
zhmcclient/python-zhmcclient
zhmcclient/_virtual_function.py
VirtualFunctionManager.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` """ resource_obj_list = [] uris = self.partition.get_property('virtual-function-uris') if uris: for uri in uris: resource_obj = self.resource_class( manager=self, uri=uri, name=None, properties=None) if self._matches_filters(resource_obj, filter_args): resource_obj_list.append(resource_obj) if full_properties: resource_obj.pull_full_properties() self._name_uri_cache.update_from(resource_obj_list) return resource_obj_list
python
def list(self, full_properties=False, filter_args=None): 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", ")", ":", "resource_obj_list", "=", "[", "]", "uris", "=", "self", ".", "partition", ".", "get_property", "(", "'virtual-function-uris'", ")", "if", "uris", ...
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`
[ "List", "the", "Virtual", "Functions", "of", "this", "Partition", "." ]
9657563e5d9184c51d3c903442a58b9725fdf335
https://github.com/zhmcclient/python-zhmcclient/blob/9657563e5d9184c51d3c903442a58b9725fdf335/zhmcclient/_virtual_function.py#L78-L129
15,120
zhmcclient/python-zhmcclient
zhmcclient/_port.py
PortManager.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` """ uris_prop = self.adapter.port_uris_prop if not uris_prop: # Adapter does not have any ports return [] uris = self.adapter.get_property(uris_prop) assert uris is not None # TODO: Remove the following circumvention once fixed. # The following line circumvents a bug for FCP adapters that sometimes # causes duplicate URIs to show up in this property: uris = list(set(uris)) resource_obj_list = [] for uri in uris: resource_obj = self.resource_class( manager=self, uri=uri, name=None, properties=None) if self._matches_filters(resource_obj, filter_args): resource_obj_list.append(resource_obj) if full_properties: resource_obj.pull_full_properties() self._name_uri_cache.update_from(resource_obj_list) return resource_obj_list
python
def list(self, full_properties=False, filter_args=None): 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", ")", ":", "uris_prop", "=", "self", ".", "adapter", ".", "port_uris_prop", "if", "not", "uris_prop", ":", "# Adapter does not have any ports", "return", "[", "]"...
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`
[ "List", "the", "Ports", "of", "this", "Adapter", "." ]
9657563e5d9184c51d3c903442a58b9725fdf335
https://github.com/zhmcclient/python-zhmcclient/blob/9657563e5d9184c51d3c903442a58b9725fdf335/zhmcclient/_port.py#L95-L159
15,121
zhmcclient/python-zhmcclient
zhmcclient/_user.py
User.add_user_role
def add_user_role(self, user_role): """ Add the specified User Role to this User. This User must not be a system-defined or pattern-based user. Authorization requirements: * Task permission to the "Manage Users" task to modify a standard user or the "Manage User Templates" task to modify a template user. Parameters: user_role (:class:`~zhmcclient.UserRole`): User Role to be added. Must not be `None`. Raises: :exc:`~zhmcclient.HTTPError` :exc:`~zhmcclient.ParseError` :exc:`~zhmcclient.AuthError` :exc:`~zhmcclient.ConnectionError` """ body = { 'user-role-uri': user_role.uri } self.manager.session.post( self.uri + '/operations/add-user-role', body=body)
python
def add_user_role(self, user_role): 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", ")", ":", "body", "=", "{", "'user-role-uri'", ":", "user_role", ".", "uri", "}", "self", ".", "manager", ".", "session", ".", "post", "(", "self", ".", "uri", "+", "'/operations/add-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`
[ "Add", "the", "specified", "User", "Role", "to", "this", "User", "." ]
9657563e5d9184c51d3c903442a58b9725fdf335
https://github.com/zhmcclient/python-zhmcclient/blob/9657563e5d9184c51d3c903442a58b9725fdf335/zhmcclient/_user.py#L270-L298
15,122
zhmcclient/python-zhmcclient
zhmcclient/_user.py
User.remove_user_role
def remove_user_role(self, user_role): """ Remove the specified User Role from this User. This User must not be a system-defined or pattern-based user. Authorization requirements: * Task permission to the "Manage Users" task to modify a standard user or the "Manage User Templates" task to modify a template user. Parameters: user_role (:class:`~zhmcclient.UserRole`): User Role to be removed. Must not be `None`. Raises: :exc:`~zhmcclient.HTTPError` :exc:`~zhmcclient.ParseError` :exc:`~zhmcclient.AuthError` :exc:`~zhmcclient.ConnectionError` """ body = { 'user-role-uri': user_role.uri } self.manager.session.post( self.uri + '/operations/remove-user-role', body=body)
python
def remove_user_role(self, user_role): 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", ")", ":", "body", "=", "{", "'user-role-uri'", ":", "user_role", ".", "uri", "}", "self", ".", "manager", ".", "session", ".", "post", "(", "self", ".", "uri", "+", "'/operations/remove-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`
[ "Remove", "the", "specified", "User", "Role", "from", "this", "User", "." ]
9657563e5d9184c51d3c903442a58b9725fdf335
https://github.com/zhmcclient/python-zhmcclient/blob/9657563e5d9184c51d3c903442a58b9725fdf335/zhmcclient/_user.py#L301-L329
15,123
zhmcclient/python-zhmcclient
zhmcclient_mock/_session.py
FakedSession.get
def get(self, uri, logon_required=True): """ Perform the HTTP GET method against the resource identified by a URI, on the faked HMC. Parameters: uri (:term:`string`): Relative URI path of the resource, e.g. "/api/session". This URI is relative to the base URL of the session (see the :attr:`~zhmcclient.Session.base_url` property). Must not be `None`. logon_required (bool): Boolean indicating whether the operation requires that the session is logged on to the HMC. Because this is a faked HMC, this does not perform a real logon, but it is still used to update the state in the faked HMC. Returns: :term:`json object` with the operation result. Raises: :exc:`~zhmcclient.HTTPError` :exc:`~zhmcclient.ParseError` (not implemented) :exc:`~zhmcclient.AuthError` (not implemented) :exc:`~zhmcclient.ConnectionError` """ try: return self._urihandler.get(self._hmc, uri, logon_required) except HTTPError as exc: raise zhmcclient.HTTPError(exc.response()) except ConnectionError as exc: raise zhmcclient.ConnectionError(exc.message, None)
python
def get(self, uri, logon_required=True): 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", ")", ":", "try", ":", "return", "self", ".", "_urihandler", ".", "get", "(", "self", ".", "_hmc", ",", "uri", ",", "logon_required", ")", "except", "HTTPError", "as", "exc", "...
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`
[ "Perform", "the", "HTTP", "GET", "method", "against", "the", "resource", "identified", "by", "a", "URI", "on", "the", "faked", "HMC", "." ]
9657563e5d9184c51d3c903442a58b9725fdf335
https://github.com/zhmcclient/python-zhmcclient/blob/9657563e5d9184c51d3c903442a58b9725fdf335/zhmcclient_mock/_session.py#L118-L154
15,124
zhmcclient/python-zhmcclient
zhmcclient_mock/_session.py
FakedSession.post
def post(self, uri, body=None, logon_required=True, wait_for_completion=True, operation_timeout=None): """ Perform the HTTP POST method against the resource identified by a URI, using a provided request body, on the faked HMC. HMC operations using HTTP POST are either synchronous or asynchronous. Asynchronous operations return the URI of an asynchronously executing job that can be queried for status and result. Examples for synchronous operations: * With no response body: "Logon", "Update CPC Properties" * With a response body: "Create Partition" Examples for asynchronous operations: * With no ``job-results`` field in the completed job status response: "Start Partition" * With a ``job-results`` field in the completed job status response (under certain conditions): "Activate a Blade", or "Set CPC Power Save" The `wait_for_completion` parameter of this method can be used to deal with asynchronous HMC operations in a synchronous way. Parameters: uri (:term:`string`): Relative URI path of the resource, e.g. "/api/session". This URI is relative to the base URL of the session (see the :attr:`~zhmcclient.Session.base_url` property). Must not be `None`. body (:term:`json object`): JSON object to be used as the HTTP request body (payload). `None` means the same as an empty dictionary, namely that no HTTP body is included in the request. logon_required (bool): Boolean indicating whether the operation requires that the session is logged on to the HMC. For example, the "Logon" operation does not require that. Because this is a faked HMC, this does not perform a real logon, but it is still used to update the state in the faked HMC. wait_for_completion (bool): Boolean controlling whether this method should wait for completion of the requested HMC operation, as follows: * If `True`, this method will wait for completion of the requested operation, regardless of whether the operation is synchronous or asynchronous. This will cause an additional entry in the time statistics to be created for the asynchronous operation and waiting for its completion. This entry will have a URI that is the targeted URI, appended with "+completion". * If `False`, this method will immediately return the result of the HTTP POST method, regardless of whether the operation is synchronous or asynchronous. operation_timeout (:term:`number`): Timeout in seconds, when waiting for completion of an asynchronous operation. The special value 0 means that no timeout is set. `None` means that the default async operation timeout of the session is used. For `wait_for_completion=True`, a :exc:`~zhmcclient.OperationTimeout` is raised when the timeout expires. For `wait_for_completion=False`, this parameter has no effect. Returns: :term:`json object`: If `wait_for_completion` is `True`, returns a JSON object representing the response body of the synchronous operation, or the response body of the completed job that performed the asynchronous operation. If a synchronous operation has no response body, `None` is returned. If `wait_for_completion` is `False`, returns a JSON object representing the response body of the synchronous or asynchronous operation. In case of an asynchronous operation, the JSON object will have a member named ``job-uri``, whose value can be used with the :meth:`~zhmcclient.Session.query_job_status` method to determine the status of the job and the result of the original operation, once the job has completed. See the section in the :term:`HMC API` book about the specific HMC operation and about the 'Query Job Status' operation, for a description of the members of the returned JSON objects. Raises: :exc:`~zhmcclient.HTTPError` :exc:`~zhmcclient.ParseError` (not implemented) :exc:`~zhmcclient.AuthError` (not implemented) :exc:`~zhmcclient.ConnectionError` """ try: return self._urihandler.post(self._hmc, uri, body, logon_required, wait_for_completion) except HTTPError as exc: raise zhmcclient.HTTPError(exc.response()) except ConnectionError as exc: raise zhmcclient.ConnectionError(exc.message, None)
python
def post(self, uri, body=None, logon_required=True, wait_for_completion=True, operation_timeout=None): 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", ")", ":", "try", ":", "return", "self", ".", "_urihandler", ".", "post",...
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`
[ "Perform", "the", "HTTP", "POST", "method", "against", "the", "resource", "identified", "by", "a", "URI", "using", "a", "provided", "request", "body", "on", "the", "faked", "HMC", "." ]
9657563e5d9184c51d3c903442a58b9725fdf335
https://github.com/zhmcclient/python-zhmcclient/blob/9657563e5d9184c51d3c903442a58b9725fdf335/zhmcclient_mock/_session.py#L156-L267
15,125
zhmcclient/python-zhmcclient
zhmcclient/_notification.py
_NotificationListener.on_disconnected
def on_disconnected(self): """ Event method that gets called when the JMS session has been disconnected. It hands over a termination notification (headers and message are None). """ with self._handover_cond: # Wait until receiver has processed the previous notification while len(self._handover_dict) > 0: self._handover_cond.wait(self._wait_timeout) # Indicate to receiver that there is a termination notification self._handover_dict['headers'] = None # terminate receiver self._handover_dict['message'] = None self._handover_cond.notifyAll()
python
def on_disconnected(self): 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", ")", ":", "with", "self", ".", "_handover_cond", ":", "# Wait until receiver has processed the previous notification", "while", "len", "(", "self", ".", "_handover_dict", ")", ">", "0", ":", "self", ".", "_handover_cond", ".", ...
Event method that gets called when the JMS session has been disconnected. It hands over a termination notification (headers and message are None).
[ "Event", "method", "that", "gets", "called", "when", "the", "JMS", "session", "has", "been", "disconnected", "." ]
9657563e5d9184c51d3c903442a58b9725fdf335
https://github.com/zhmcclient/python-zhmcclient/blob/9657563e5d9184c51d3c903442a58b9725fdf335/zhmcclient/_notification.py#L267-L285
15,126
zhmcclient/python-zhmcclient
zhmcclient/_console.py
Console.restart
def restart(self, force=False, wait_for_available=True, operation_timeout=None): """ Restart the HMC represented by this Console object. Once the HMC is online again, this Console object, as well as any other resource objects accessed through this HMC, can continue to be used. An automatic re-logon will be performed under the covers, because the HMC restart invalidates the currently used HMC session. Authorization requirements: * Task permission for the "Shutdown/Restart" task. * "Remote Restart" must be enabled on the HMC. Parameters: force (bool): Boolean controlling whether the restart operation is processed when users are connected (`True`) or not (`False`). Users in this sense are local or remote GUI users. HMC WS API clients do not count as users for this purpose. wait_for_available (bool): Boolean controlling whether this method should wait for the HMC to become available again after the restart, as follows: * If `True`, this method will wait until the HMC has restarted and is available again. The :meth:`~zhmcclient.Client.query_api_version` method will be used to check for availability of the HMC. * If `False`, this method will return immediately once the HMC has accepted the request to be restarted. operation_timeout (:term:`number`): Timeout in seconds, for waiting for HMC availability after the restart. The special value 0 means that no timeout is set. `None` means that the default async operation timeout of the session is used. If the timeout expires when `wait_for_available=True`, a :exc:`~zhmcclient.OperationTimeout` is raised. Raises: :exc:`~zhmcclient.HTTPError` :exc:`~zhmcclient.ParseError` :exc:`~zhmcclient.AuthError` :exc:`~zhmcclient.ConnectionError` :exc:`~zhmcclient.OperationTimeout`: The timeout expired while waiting for the HMC to become available again after the restart. """ body = {'force': force} self.manager.session.post(self.uri + '/operations/restart', body=body) if wait_for_available: time.sleep(10) self.manager.client.wait_for_available( operation_timeout=operation_timeout)
python
def restart(self, force=False, wait_for_available=True, operation_timeout=None): 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", ")", ":", "body", "=", "{", "'force'", ":", "force", "}", "self", ".", "manager", ".", "session", ".", "post", "("...
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.
[ "Restart", "the", "HMC", "represented", "by", "this", "Console", "object", "." ]
9657563e5d9184c51d3c903442a58b9725fdf335
https://github.com/zhmcclient/python-zhmcclient/blob/9657563e5d9184c51d3c903442a58b9725fdf335/zhmcclient/_console.py#L287-L343
15,127
zhmcclient/python-zhmcclient
zhmcclient/_console.py
Console.shutdown
def shutdown(self, force=False): """ Shut down and power off the HMC represented by this Console object. While the HMC is powered off, any Python resource objects retrieved from this HMC may raise exceptions upon further use. In order to continue using Python resource objects retrieved from this HMC, the HMC needs to be started again (e.g. by powering it on locally). Once the HMC is available again, Python resource objects retrieved from that HMC can continue to be used. An automatic re-logon will be performed under the covers, because the HMC startup invalidates the currently used HMC session. Authorization requirements: * Task permission for the "Shutdown/Restart" task. * "Remote Shutdown" must be enabled on the HMC. Parameters: force (bool): Boolean controlling whether the shutdown operation is processed when users are connected (`True`) or not (`False`). Users in this sense are local or remote GUI users. HMC WS API clients do not count as users for this purpose. Raises: :exc:`~zhmcclient.HTTPError` :exc:`~zhmcclient.ParseError` :exc:`~zhmcclient.AuthError` :exc:`~zhmcclient.ConnectionError` """ body = {'force': force} self.manager.session.post(self.uri + '/operations/shutdown', body=body)
python
def shutdown(self, force=False): body = {'force': force} self.manager.session.post(self.uri + '/operations/shutdown', body=body)
[ "def", "shutdown", "(", "self", ",", "force", "=", "False", ")", ":", "body", "=", "{", "'force'", ":", "force", "}", "self", ".", "manager", ".", "session", ".", "post", "(", "self", ".", "uri", "+", "'/operations/shutdown'", ",", "body", "=", "body...
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`
[ "Shut", "down", "and", "power", "off", "the", "HMC", "represented", "by", "this", "Console", "object", "." ]
9657563e5d9184c51d3c903442a58b9725fdf335
https://github.com/zhmcclient/python-zhmcclient/blob/9657563e5d9184c51d3c903442a58b9725fdf335/zhmcclient/_console.py#L346-L381
15,128
zhmcclient/python-zhmcclient
zhmcclient/_console.py
Console._time_query_parms
def _time_query_parms(begin_time, end_time): """Return the URI query paramterer string for the specified begin time and end time.""" query_parms = [] if begin_time is not None: begin_ts = timestamp_from_datetime(begin_time) qp = 'begin-time={}'.format(begin_ts) query_parms.append(qp) if end_time is not None: end_ts = timestamp_from_datetime(end_time) qp = 'end-time={}'.format(end_ts) query_parms.append(qp) query_parms_str = '&'.join(query_parms) if query_parms_str: query_parms_str = '?' + query_parms_str return query_parms_str
python
def _time_query_parms(begin_time, end_time): query_parms = [] if begin_time is not None: begin_ts = timestamp_from_datetime(begin_time) qp = 'begin-time={}'.format(begin_ts) query_parms.append(qp) if end_time is not None: end_ts = timestamp_from_datetime(end_time) qp = 'end-time={}'.format(end_ts) query_parms.append(qp) query_parms_str = '&'.join(query_parms) if query_parms_str: query_parms_str = '?' + query_parms_str return query_parms_str
[ "def", "_time_query_parms", "(", "begin_time", ",", "end_time", ")", ":", "query_parms", "=", "[", "]", "if", "begin_time", "is", "not", "None", ":", "begin_ts", "=", "timestamp_from_datetime", "(", "begin_time", ")", "qp", "=", "'begin-time={}'", ".", "format...
Return the URI query paramterer string for the specified begin time and end time.
[ "Return", "the", "URI", "query", "paramterer", "string", "for", "the", "specified", "begin", "time", "and", "end", "time", "." ]
9657563e5d9184c51d3c903442a58b9725fdf335
https://github.com/zhmcclient/python-zhmcclient/blob/9657563e5d9184c51d3c903442a58b9725fdf335/zhmcclient/_console.py#L409-L424
15,129
zhmcclient/python-zhmcclient
zhmcclient/_console.py
Console.get_audit_log
def get_audit_log(self, begin_time=None, end_time=None): """ Return the console audit log entries, optionally filtered by their creation time. Authorization requirements: * Task permission to the "Audit and Log Management" task. Parameters: begin_time (:class:`~py:datetime.datetime`): Begin time for filtering. Log entries with a creation time older than the begin time will be omitted from the results. If `None`, no such filtering is performed (and the oldest available log entries will be included). end_time (:class:`~py:datetime.datetime`): End time for filtering. Log entries with a creation time newer than the end time will be omitted from the results. If `None`, no such filtering is performed (and the newest available log entries will be included). Returns: :term:`json object`: A JSON object with the log entries, as described in section 'Response body contents' of operation 'Get Console Audit Log' in the :term:`HMC API` book. Raises: :exc:`~zhmcclient.HTTPError` :exc:`~zhmcclient.ParseError` :exc:`~zhmcclient.AuthError` :exc:`~zhmcclient.ConnectionError` """ query_parms = self._time_query_parms(begin_time, end_time) uri = self.uri + '/operations/get-audit-log' + query_parms result = self.manager.session.post(uri) return result
python
def get_audit_log(self, begin_time=None, end_time=None): 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", ")", ":", "query_parms", "=", "self", ".", "_time_query_parms", "(", "begin_time", ",", "end_time", ")", "uri", "=", "self", ".", "uri", "+", "'/operations/g...
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`
[ "Return", "the", "console", "audit", "log", "entries", "optionally", "filtered", "by", "their", "creation", "time", "." ]
9657563e5d9184c51d3c903442a58b9725fdf335
https://github.com/zhmcclient/python-zhmcclient/blob/9657563e5d9184c51d3c903442a58b9725fdf335/zhmcclient/_console.py#L427-L469
15,130
zhmcclient/python-zhmcclient
zhmcclient/_console.py
Console.list_unmanaged_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` """ filter_args = dict() if name is not None: filter_args['name'] = name cpcs = self.unmanaged_cpcs.list(filter_args=filter_args) return cpcs
python
def list_unmanaged_cpcs(self, name=None): 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", ")", ":", "filter_args", "=", "dict", "(", ")", "if", "name", "is", "not", "None", ":", "filter_args", "[", "'name'", "]", "=", "name", "cpcs", "=", "self", ".", "unmanaged_cpcs", "."...
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`
[ "List", "the", "unmanaged", "CPCs", "of", "this", "HMC", "." ]
9657563e5d9184c51d3c903442a58b9725fdf335
https://github.com/zhmcclient/python-zhmcclient/blob/9657563e5d9184c51d3c903442a58b9725fdf335/zhmcclient/_console.py#L517-L552
15,131
zhmcclient/python-zhmcclient
zhmcclient/_cpc.py
Cpc.feature_info
def feature_info(self): """ Returns information about the features available for this CPC. Authorization requirements: * Object-access permission to this CPC. Returns: :term:`iterable`: An iterable where each item represents one feature that is available for this CPC. Each item is a dictionary with the following items: * `name` (:term:`unicode string`): Name of the feature. * `description` (:term:`unicode string`): Short description of the feature. * `state` (bool): Enablement state of the feature (`True` if the enabled, `False` if disabled). Raises: :exc:`ValueError`: Features are not supported on the HMC. :exc:`~zhmcclient.HTTPError` :exc:`~zhmcclient.ParseError` :exc:`~zhmcclient.AuthError` :exc:`~zhmcclient.ConnectionError` """ feature_list = self.prop('available-features-list', None) if feature_list is None: raise ValueError("Firmware features are not supported on CPC %s" % self.name) return feature_list
python
def feature_info(self): feature_list = self.prop('available-features-list', None) if feature_list is None: raise ValueError("Firmware features are not supported on CPC %s" % self.name) return feature_list
[ "def", "feature_info", "(", "self", ")", ":", "feature_list", "=", "self", ".", "prop", "(", "'available-features-list'", ",", "None", ")", "if", "feature_list", "is", "None", ":", "raise", "ValueError", "(", "\"Firmware features are not supported on CPC %s\"", "%",...
Returns information about the features available for this CPC. Authorization requirements: * Object-access permission to this CPC. Returns: :term:`iterable`: An iterable where each item represents one feature that is available for this CPC. Each item is a dictionary with the following items: * `name` (:term:`unicode string`): Name of the feature. * `description` (:term:`unicode string`): Short description of the feature. * `state` (bool): Enablement state of the feature (`True` if the enabled, `False` if disabled). Raises: :exc:`ValueError`: Features are not supported on the HMC. :exc:`~zhmcclient.HTTPError` :exc:`~zhmcclient.ParseError` :exc:`~zhmcclient.AuthError` :exc:`~zhmcclient.ConnectionError`
[ "Returns", "information", "about", "the", "features", "available", "for", "this", "CPC", "." ]
9657563e5d9184c51d3c903442a58b9725fdf335
https://github.com/zhmcclient/python-zhmcclient/blob/9657563e5d9184c51d3c903442a58b9725fdf335/zhmcclient/_cpc.py#L461-L495
15,132
zhmcclient/python-zhmcclient
zhmcclient/_cpc.py
Cpc.start
def start(self, wait_for_completion=True, operation_timeout=None): """ Start this CPC, using the HMC operation "Start CPC". Authorization requirements: * Object-access permission to this CPC. * Task permission for the "Start (start a single DPM system)" task. Parameters: wait_for_completion (bool): Boolean controlling whether this method should wait for completion of the requested asynchronous HMC operation, as follows: * If `True`, this method will wait for completion of the asynchronous job performing the operation. * If `False`, this method will return immediately once the HMC has accepted the request to perform the operation. operation_timeout (:term:`number`): Timeout in seconds, for waiting for completion of the asynchronous job performing the operation. The special value 0 means that no timeout is set. `None` means that the default async operation timeout of the session is used. If the timeout expires when `wait_for_completion=True`, a :exc:`~zhmcclient.OperationTimeout` is raised. Returns: `None` or :class:`~zhmcclient.Job`: If `wait_for_completion` is `True`, returns `None`. If `wait_for_completion` is `False`, returns a :class:`~zhmcclient.Job` object representing the asynchronously executing job on the HMC. Raises: :exc:`~zhmcclient.HTTPError` :exc:`~zhmcclient.ParseError` :exc:`~zhmcclient.AuthError` :exc:`~zhmcclient.ConnectionError` :exc:`~zhmcclient.OperationTimeout`: The timeout expired while waiting for completion of the operation. """ result = self.manager.session.post( self.uri + '/operations/start', wait_for_completion=wait_for_completion, operation_timeout=operation_timeout) return result
python
def start(self, wait_for_completion=True, operation_timeout=None): result = self.manager.session.post( self.uri + '/operations/start', wait_for_completion=wait_for_completion, operation_timeout=operation_timeout) return result
[ "def", "start", "(", "self", ",", "wait_for_completion", "=", "True", ",", "operation_timeout", "=", "None", ")", ":", "result", "=", "self", ".", "manager", ".", "session", ".", "post", "(", "self", ".", "uri", "+", "'/operations/start'", ",", "wait_for_c...
Start this CPC, using the HMC operation "Start CPC". Authorization requirements: * Object-access permission to this CPC. * Task permission for the "Start (start a single DPM system)" task. Parameters: wait_for_completion (bool): Boolean controlling whether this method should wait for completion of the requested asynchronous HMC operation, as follows: * If `True`, this method will wait for completion of the asynchronous job performing the operation. * If `False`, this method will return immediately once the HMC has accepted the request to perform the operation. operation_timeout (:term:`number`): Timeout in seconds, for waiting for completion of the asynchronous job performing the operation. The special value 0 means that no timeout is set. `None` means that the default async operation timeout of the session is used. If the timeout expires when `wait_for_completion=True`, a :exc:`~zhmcclient.OperationTimeout` is raised. Returns: `None` or :class:`~zhmcclient.Job`: If `wait_for_completion` is `True`, returns `None`. If `wait_for_completion` is `False`, returns a :class:`~zhmcclient.Job` object representing the asynchronously executing job on the HMC. Raises: :exc:`~zhmcclient.HTTPError` :exc:`~zhmcclient.ParseError` :exc:`~zhmcclient.AuthError` :exc:`~zhmcclient.ConnectionError` :exc:`~zhmcclient.OperationTimeout`: The timeout expired while waiting for completion of the operation.
[ "Start", "this", "CPC", "using", "the", "HMC", "operation", "Start", "CPC", "." ]
9657563e5d9184c51d3c903442a58b9725fdf335
https://github.com/zhmcclient/python-zhmcclient/blob/9657563e5d9184c51d3c903442a58b9725fdf335/zhmcclient/_cpc.py#L528-L580
15,133
zhmcclient/python-zhmcclient
zhmcclient/_cpc.py
Cpc.get_free_crypto_domains
def get_free_crypto_domains(self, crypto_adapters=None): """ Return a list of crypto domains that are free for usage on a list of crypto adapters in this CPC. A crypto domain is considered free for usage if it is not assigned to any defined partition of this CPC in access mode 'control-usage' on any of the specified crypto adapters. For this test, all currently defined partitions of this CPC are checked, regardless of whether or not they are active. This ensures that a crypto domain that is found to be free for usage can be assigned to a partition for 'control-usage' access to the specified crypto adapters, without causing a crypto domain conflict when activating that partition. Note that a similar notion of free domains does not exist for access mode 'control', because a crypto domain on a crypto adapter can be in control access by multiple active partitions. This method requires the CPC to be in DPM mode. **Example:** .. code-block:: text crypto domains adapters 0 1 2 3 +---+---+---+---+ c1 |A,c|a,c| | C | +---+---+---+---+ c2 |b,c|B,c| B | C | +---+---+---+---+ In this example, the CPC has two crypto adapters c1 and c2. For simplicity of the example, we assume these crypto adapters support only 4 crypto domains. Partition A uses only adapter c1 and has domain 0 in 'control-usage' access (indicated by an upper case letter 'A' in the corresponding cell) and has domain 1 in 'control' access (indicated by a lower case letter 'a' in the corresponding cell). Partition B uses only adapter c2 and has domain 0 in 'control' access and domains 1 and 2 in 'control-usage' access. Partition C uses both adapters, and has domains 0 and 1 in 'control' access and domain 3 in 'control-usage' access. The domains free for usage in this example are shown in the following table, for each combination of crypto adapters to be investigated: =============== ====================== crypto_adapters domains free for usage =============== ====================== c1 1, 2 c2 0 c1, c2 (empty list) =============== ====================== **Experimental:** This method has been added in v0.14.0 and is currently considered experimental. Its interface may change incompatibly. Once the interface remains stable, this experimental marker will be removed. Authorization requirements: * Object-access permission to this CPC. * Object-access permission to all of its Partitions. * Object-access permission to all of its crypto Adapters. Parameters: crypto_adapters (:term:`iterable` of :class:`~zhmcclient.Adapter`): The crypto :term:`Adapters <Adapter>` to be investigated. `None` means to investigate all crypto adapters of this CPC. Returns: A sorted list of domain index numbers (integers) of the crypto domains that are free for usage on the specified crypto adapters. Returns `None`, if ``crypto_adapters`` was an empty list or if ``crypto_adapters`` was `None` and the CPC has no crypto adapters. Raises: :exc:`~zhmcclient.HTTPError` :exc:`~zhmcclient.ParseError` :exc:`~zhmcclient.AuthError` :exc:`~zhmcclient.ConnectionError` """ if crypto_adapters is None: crypto_adapters = self.adapters.findall(type='crypto') if not crypto_adapters: # No crypto adapters were specified or defaulted. return None # We determine the maximum number of crypto domains independently # of the partitions, because (1) it is possible that no partition # has a crypto configuration and (2) further down we want the inner # loop to be on the crypto adapters because accessing them multiple # times does not drive additional HMC operations. max_domains = None # maximum number of domains across all adapters for ca in crypto_adapters: if max_domains is None: max_domains = ca.maximum_crypto_domains else: max_domains = min(ca.maximum_crypto_domains, max_domains) used_domains = set() # Crypto domains used in control-usage mode partitions = self.partitions.list(full_properties=True) for partition in partitions: crypto_config = partition.get_property('crypto-configuration') if crypto_config: adapter_uris = crypto_config['crypto-adapter-uris'] domain_configs = crypto_config['crypto-domain-configurations'] for ca in crypto_adapters: if ca.uri in adapter_uris: used_adapter_domains = list() for dc in domain_configs: if dc['access-mode'] == 'control-usage': used_adapter_domains.append(dc['domain-index']) used_domains.update(used_adapter_domains) all_domains = set(range(0, max_domains)) free_domains = all_domains - used_domains return sorted(list(free_domains))
python
def get_free_crypto_domains(self, crypto_adapters=None): if crypto_adapters is None: crypto_adapters = self.adapters.findall(type='crypto') if not crypto_adapters: # No crypto adapters were specified or defaulted. return None # We determine the maximum number of crypto domains independently # of the partitions, because (1) it is possible that no partition # has a crypto configuration and (2) further down we want the inner # loop to be on the crypto adapters because accessing them multiple # times does not drive additional HMC operations. max_domains = None # maximum number of domains across all adapters for ca in crypto_adapters: if max_domains is None: max_domains = ca.maximum_crypto_domains else: max_domains = min(ca.maximum_crypto_domains, max_domains) used_domains = set() # Crypto domains used in control-usage mode partitions = self.partitions.list(full_properties=True) for partition in partitions: crypto_config = partition.get_property('crypto-configuration') if crypto_config: adapter_uris = crypto_config['crypto-adapter-uris'] domain_configs = crypto_config['crypto-domain-configurations'] for ca in crypto_adapters: if ca.uri in adapter_uris: used_adapter_domains = list() for dc in domain_configs: if dc['access-mode'] == 'control-usage': used_adapter_domains.append(dc['domain-index']) used_domains.update(used_adapter_domains) all_domains = set(range(0, max_domains)) free_domains = all_domains - used_domains return sorted(list(free_domains))
[ "def", "get_free_crypto_domains", "(", "self", ",", "crypto_adapters", "=", "None", ")", ":", "if", "crypto_adapters", "is", "None", ":", "crypto_adapters", "=", "self", ".", "adapters", ".", "findall", "(", "type", "=", "'crypto'", ")", "if", "not", "crypto...
Return a list of crypto domains that are free for usage on a list of crypto adapters in this CPC. A crypto domain is considered free for usage if it is not assigned to any defined partition of this CPC in access mode 'control-usage' on any of the specified crypto adapters. For this test, all currently defined partitions of this CPC are checked, regardless of whether or not they are active. This ensures that a crypto domain that is found to be free for usage can be assigned to a partition for 'control-usage' access to the specified crypto adapters, without causing a crypto domain conflict when activating that partition. Note that a similar notion of free domains does not exist for access mode 'control', because a crypto domain on a crypto adapter can be in control access by multiple active partitions. This method requires the CPC to be in DPM mode. **Example:** .. code-block:: text crypto domains adapters 0 1 2 3 +---+---+---+---+ c1 |A,c|a,c| | C | +---+---+---+---+ c2 |b,c|B,c| B | C | +---+---+---+---+ In this example, the CPC has two crypto adapters c1 and c2. For simplicity of the example, we assume these crypto adapters support only 4 crypto domains. Partition A uses only adapter c1 and has domain 0 in 'control-usage' access (indicated by an upper case letter 'A' in the corresponding cell) and has domain 1 in 'control' access (indicated by a lower case letter 'a' in the corresponding cell). Partition B uses only adapter c2 and has domain 0 in 'control' access and domains 1 and 2 in 'control-usage' access. Partition C uses both adapters, and has domains 0 and 1 in 'control' access and domain 3 in 'control-usage' access. The domains free for usage in this example are shown in the following table, for each combination of crypto adapters to be investigated: =============== ====================== crypto_adapters domains free for usage =============== ====================== c1 1, 2 c2 0 c1, c2 (empty list) =============== ====================== **Experimental:** This method has been added in v0.14.0 and is currently considered experimental. Its interface may change incompatibly. Once the interface remains stable, this experimental marker will be removed. Authorization requirements: * Object-access permission to this CPC. * Object-access permission to all of its Partitions. * Object-access permission to all of its crypto Adapters. Parameters: crypto_adapters (:term:`iterable` of :class:`~zhmcclient.Adapter`): The crypto :term:`Adapters <Adapter>` to be investigated. `None` means to investigate all crypto adapters of this CPC. Returns: A sorted list of domain index numbers (integers) of the crypto domains that are free for usage on the specified crypto adapters. Returns `None`, if ``crypto_adapters`` was an empty list or if ``crypto_adapters`` was `None` and the CPC has no crypto adapters. Raises: :exc:`~zhmcclient.HTTPError` :exc:`~zhmcclient.ParseError` :exc:`~zhmcclient.AuthError` :exc:`~zhmcclient.ConnectionError`
[ "Return", "a", "list", "of", "crypto", "domains", "that", "are", "free", "for", "usage", "on", "a", "list", "of", "crypto", "adapters", "in", "this", "CPC", "." ]
9657563e5d9184c51d3c903442a58b9725fdf335
https://github.com/zhmcclient/python-zhmcclient/blob/9657563e5d9184c51d3c903442a58b9725fdf335/zhmcclient/_cpc.py#L818-L948
15,134
zhmcclient/python-zhmcclient
zhmcclient/_cpc.py
Cpc.set_power_save
def set_power_save(self, power_saving, wait_for_completion=True, operation_timeout=None): """ Set the power save setting of this CPC. The current power save setting in effect for a CPC is described in the "cpc-power-saving" property of the CPC. This method performs the HMC operation "Set CPC Power Save". It requires that the feature "Automate/advanced management suite" (FC 0020) is installed and enabled, and fails otherwise. This method will also fail if the CPC is under group control. Whether a CPC currently allows this method is described in the "cpc-power-save-allowed" property of the CPC. Authorization requirements: * Object-access permission to this CPC. * Task permission for the "Power Save" task. Parameters: power_saving (:term:`string`): The new power save setting, with the possible values: * "high-performance" - The power consumption and performance of the CPC are not reduced. This is the default setting. * "low-power" - Low power consumption for all components of the CPC enabled for power saving. * "custom" - Components may have their own settings changed individually. No component settings are actually changed when this mode is entered. wait_for_completion (bool): Boolean controlling whether this method should wait for completion of the requested asynchronous HMC operation, as follows: * If `True`, this method will wait for completion of the asynchronous job performing the operation. * If `False`, this method will return immediately once the HMC has accepted the request to perform the operation. operation_timeout (:term:`number`): Timeout in seconds, for waiting for completion of the asynchronous job performing the operation. The special value 0 means that no timeout is set. `None` means that the default async operation timeout of the session is used. If the timeout expires when `wait_for_completion=True`, a :exc:`~zhmcclient.OperationTimeout` is raised. Returns: `None` or :class:`~zhmcclient.Job`: If `wait_for_completion` is `True`, returns `None`. If `wait_for_completion` is `False`, returns a :class:`~zhmcclient.Job` object representing the asynchronously executing job on the HMC. Raises: :exc:`~zhmcclient.HTTPError`: See the HTTP status and reason codes of operation "Set CPC Power Save" in the :term:`HMC API` book. :exc:`~zhmcclient.ParseError` :exc:`~zhmcclient.AuthError` :exc:`~zhmcclient.ConnectionError` :exc:`~zhmcclient.OperationTimeout`: The timeout expired while waiting for completion of the operation. """ body = {'power-saving': power_saving} result = self.manager.session.post( self.uri + '/operations/set-cpc-power-save', body, wait_for_completion=wait_for_completion, operation_timeout=operation_timeout) if wait_for_completion: # The HMC API book does not document what the result data of the # completed job is. It turns out that the completed job has this # dictionary as its result data: # {'message': 'Operation executed successfully'} # We transform that to None. return None return result
python
def set_power_save(self, power_saving, wait_for_completion=True, operation_timeout=None): body = {'power-saving': power_saving} result = self.manager.session.post( self.uri + '/operations/set-cpc-power-save', body, wait_for_completion=wait_for_completion, operation_timeout=operation_timeout) if wait_for_completion: # The HMC API book does not document what the result data of the # completed job is. It turns out that the completed job has this # dictionary as its result data: # {'message': 'Operation executed successfully'} # We transform that to None. return None return result
[ "def", "set_power_save", "(", "self", ",", "power_saving", ",", "wait_for_completion", "=", "True", ",", "operation_timeout", "=", "None", ")", ":", "body", "=", "{", "'power-saving'", ":", "power_saving", "}", "result", "=", "self", ".", "manager", ".", "se...
Set the power save setting of this CPC. The current power save setting in effect for a CPC is described in the "cpc-power-saving" property of the CPC. This method performs the HMC operation "Set CPC Power Save". It requires that the feature "Automate/advanced management suite" (FC 0020) is installed and enabled, and fails otherwise. This method will also fail if the CPC is under group control. Whether a CPC currently allows this method is described in the "cpc-power-save-allowed" property of the CPC. Authorization requirements: * Object-access permission to this CPC. * Task permission for the "Power Save" task. Parameters: power_saving (:term:`string`): The new power save setting, with the possible values: * "high-performance" - The power consumption and performance of the CPC are not reduced. This is the default setting. * "low-power" - Low power consumption for all components of the CPC enabled for power saving. * "custom" - Components may have their own settings changed individually. No component settings are actually changed when this mode is entered. wait_for_completion (bool): Boolean controlling whether this method should wait for completion of the requested asynchronous HMC operation, as follows: * If `True`, this method will wait for completion of the asynchronous job performing the operation. * If `False`, this method will return immediately once the HMC has accepted the request to perform the operation. operation_timeout (:term:`number`): Timeout in seconds, for waiting for completion of the asynchronous job performing the operation. The special value 0 means that no timeout is set. `None` means that the default async operation timeout of the session is used. If the timeout expires when `wait_for_completion=True`, a :exc:`~zhmcclient.OperationTimeout` is raised. Returns: `None` or :class:`~zhmcclient.Job`: If `wait_for_completion` is `True`, returns `None`. If `wait_for_completion` is `False`, returns a :class:`~zhmcclient.Job` object representing the asynchronously executing job on the HMC. Raises: :exc:`~zhmcclient.HTTPError`: See the HTTP status and reason codes of operation "Set CPC Power Save" in the :term:`HMC API` book. :exc:`~zhmcclient.ParseError` :exc:`~zhmcclient.AuthError` :exc:`~zhmcclient.ConnectionError` :exc:`~zhmcclient.OperationTimeout`: The timeout expired while waiting for completion of the operation.
[ "Set", "the", "power", "save", "setting", "of", "this", "CPC", "." ]
9657563e5d9184c51d3c903442a58b9725fdf335
https://github.com/zhmcclient/python-zhmcclient/blob/9657563e5d9184c51d3c903442a58b9725fdf335/zhmcclient/_cpc.py#L951-L1037
15,135
zhmcclient/python-zhmcclient
zhmcclient/_cpc.py
Cpc.set_power_capping
def set_power_capping(self, power_capping_state, power_cap=None, wait_for_completion=True, operation_timeout=None): """ Set the power capping settings of this CPC. The power capping settings of a CPC define whether or not the power consumption of the CPC is limited and if so, what the limit is. Use this method to limit the peak power consumption of a CPC, or to remove a power consumption limit for a CPC. The current power capping settings in effect for a CPC are described in the "cpc-power-capping-state" and "cpc-power-cap-current" properties of the CPC. This method performs the HMC operation "Set CPC Power Capping". It requires that the feature "Automate/advanced management suite" (FC 0020) is installed and enabled, and fails otherwise. This method will also fail if the CPC is under group control. Whether a CPC currently allows this method is described in the "cpc-power-cap-allowed" property of the CPC. Authorization requirements: * Object-access permission to this CPC. * Task permission for the "Power Capping" task. Parameters: power_capping_state (:term:`string`): The power capping state to be set, with the possible values: * "disabled" - The power cap of the CPC is not set and the peak power consumption is not limited. This is the default setting. * "enabled" - The peak power consumption of the CPC is limited to the specified power cap value. * "custom" - Individually configure the components for power capping. No component settings are actually changed when this mode is entered. power_cap (:term:`integer`): The power cap value to be set, as a power consumption in Watt. This parameter is required not to be `None` if `power_capping_state="enabled"`. The specified value must be between the values of the CPC properties "cpc-power-cap-minimum" and "cpc-power-cap-maximum". wait_for_completion (bool): Boolean controlling whether this method should wait for completion of the requested asynchronous HMC operation, as follows: * If `True`, this method will wait for completion of the asynchronous job performing the operation. * If `False`, this method will return immediately once the HMC has accepted the request to perform the operation. operation_timeout (:term:`number`): Timeout in seconds, for waiting for completion of the asynchronous job performing the operation. The special value 0 means that no timeout is set. `None` means that the default async operation timeout of the session is used. If the timeout expires when `wait_for_completion=True`, a :exc:`~zhmcclient.OperationTimeout` is raised. Returns: `None` or :class:`~zhmcclient.Job`: If `wait_for_completion` is `True`, returns `None`. If `wait_for_completion` is `False`, returns a :class:`~zhmcclient.Job` object representing the asynchronously executing job on the HMC. Raises: :exc:`~zhmcclient.HTTPError`: See the HTTP status and reason codes of operation "Set CPC Power Save" in the :term:`HMC API` book. :exc:`~zhmcclient.ParseError` :exc:`~zhmcclient.AuthError` :exc:`~zhmcclient.ConnectionError` :exc:`~zhmcclient.OperationTimeout`: The timeout expired while waiting for completion of the operation. """ body = {'power-capping-state': power_capping_state} if power_cap is not None: body['power-cap-current'] = power_cap result = self.manager.session.post( self.uri + '/operations/set-cpc-power-capping', body, wait_for_completion=wait_for_completion, operation_timeout=operation_timeout) if wait_for_completion: # The HMC API book does not document what the result data of the # completed job is. Just in case there is similar behavior to the # "Set CPC Power Save" operation, we transform that to None. # TODO: Verify job result of a completed "Set CPC Power Capping". return None return result
python
def set_power_capping(self, power_capping_state, power_cap=None, wait_for_completion=True, operation_timeout=None): body = {'power-capping-state': power_capping_state} if power_cap is not None: body['power-cap-current'] = power_cap result = self.manager.session.post( self.uri + '/operations/set-cpc-power-capping', body, wait_for_completion=wait_for_completion, operation_timeout=operation_timeout) if wait_for_completion: # The HMC API book does not document what the result data of the # completed job is. Just in case there is similar behavior to the # "Set CPC Power Save" operation, we transform that to None. # TODO: Verify job result of a completed "Set CPC Power Capping". return None return result
[ "def", "set_power_capping", "(", "self", ",", "power_capping_state", ",", "power_cap", "=", "None", ",", "wait_for_completion", "=", "True", ",", "operation_timeout", "=", "None", ")", ":", "body", "=", "{", "'power-capping-state'", ":", "power_capping_state", "}"...
Set the power capping settings of this CPC. The power capping settings of a CPC define whether or not the power consumption of the CPC is limited and if so, what the limit is. Use this method to limit the peak power consumption of a CPC, or to remove a power consumption limit for a CPC. The current power capping settings in effect for a CPC are described in the "cpc-power-capping-state" and "cpc-power-cap-current" properties of the CPC. This method performs the HMC operation "Set CPC Power Capping". It requires that the feature "Automate/advanced management suite" (FC 0020) is installed and enabled, and fails otherwise. This method will also fail if the CPC is under group control. Whether a CPC currently allows this method is described in the "cpc-power-cap-allowed" property of the CPC. Authorization requirements: * Object-access permission to this CPC. * Task permission for the "Power Capping" task. Parameters: power_capping_state (:term:`string`): The power capping state to be set, with the possible values: * "disabled" - The power cap of the CPC is not set and the peak power consumption is not limited. This is the default setting. * "enabled" - The peak power consumption of the CPC is limited to the specified power cap value. * "custom" - Individually configure the components for power capping. No component settings are actually changed when this mode is entered. power_cap (:term:`integer`): The power cap value to be set, as a power consumption in Watt. This parameter is required not to be `None` if `power_capping_state="enabled"`. The specified value must be between the values of the CPC properties "cpc-power-cap-minimum" and "cpc-power-cap-maximum". wait_for_completion (bool): Boolean controlling whether this method should wait for completion of the requested asynchronous HMC operation, as follows: * If `True`, this method will wait for completion of the asynchronous job performing the operation. * If `False`, this method will return immediately once the HMC has accepted the request to perform the operation. operation_timeout (:term:`number`): Timeout in seconds, for waiting for completion of the asynchronous job performing the operation. The special value 0 means that no timeout is set. `None` means that the default async operation timeout of the session is used. If the timeout expires when `wait_for_completion=True`, a :exc:`~zhmcclient.OperationTimeout` is raised. Returns: `None` or :class:`~zhmcclient.Job`: If `wait_for_completion` is `True`, returns `None`. If `wait_for_completion` is `False`, returns a :class:`~zhmcclient.Job` object representing the asynchronously executing job on the HMC. Raises: :exc:`~zhmcclient.HTTPError`: See the HTTP status and reason codes of operation "Set CPC Power Save" in the :term:`HMC API` book. :exc:`~zhmcclient.ParseError` :exc:`~zhmcclient.AuthError` :exc:`~zhmcclient.ConnectionError` :exc:`~zhmcclient.OperationTimeout`: The timeout expired while waiting for completion of the operation.
[ "Set", "the", "power", "capping", "settings", "of", "this", "CPC", ".", "The", "power", "capping", "settings", "of", "a", "CPC", "define", "whether", "or", "not", "the", "power", "consumption", "of", "the", "CPC", "is", "limited", "and", "if", "so", "wha...
9657563e5d9184c51d3c903442a58b9725fdf335
https://github.com/zhmcclient/python-zhmcclient/blob/9657563e5d9184c51d3c903442a58b9725fdf335/zhmcclient/_cpc.py#L1040-L1140
15,136
zhmcclient/python-zhmcclient
zhmcclient/_cpc.py
Cpc.get_energy_management_properties
def get_energy_management_properties(self): """ Return the energy management properties of the CPC. The returned energy management properties are a subset of the properties of the CPC resource, and are also available as normal properties of the CPC resource. In so far, there is no new data provided by this method. However, because only a subset of the properties is returned, this method is faster than retrieving the complete set of CPC properties (e.g. via :meth:`~zhmcclient.BaseResource.pull_full_properties`). This method performs the HMC operation "Get CPC Energy Management Data", and returns only the energy management properties for this CPC from the operation result. Note that in non-ensemble mode of a CPC, the HMC operation result will only contain data for the CPC alone. It requires that the feature "Automate/advanced management suite" (FC 0020) is installed and enabled, and returns empty values for most properties, otherwise. Authorization requirements: * Object-access permission to this CPC. Returns: dict: A dictionary of properties of the CPC that are related to energy management. For details, see section "Energy management related additional properties" in the data model for the CPC resource in the :term:`HMC API` book. Raises: :exc:`~zhmcclient.HTTPError`: See the HTTP status and reason codes of operation "Get CPC Energy Management Data" in the :term:`HMC API` book. :exc:`~zhmcclient.ParseError`: Also raised by this method when the JSON response could be parsed but contains inconsistent data. :exc:`~zhmcclient.AuthError` :exc:`~zhmcclient.ConnectionError` """ result = self.manager.session.get(self.uri + '/energy-management-data') em_list = result['objects'] if len(em_list) != 1: uris = [em_obj['object-uri'] for em_obj in em_list] raise ParseError("Energy management data returned for no resource " "or for more than one resource: %r" % uris) em_cpc_obj = em_list[0] if em_cpc_obj['object-uri'] != self.uri: raise ParseError("Energy management data returned for an " "unexpected resource: %r" % em_cpc_obj['object-uri']) if em_cpc_obj['error-occurred']: raise ParseError("Errors occurred when retrieving energy " "management data for CPC. Operation result: %r" % result) cpc_props = em_cpc_obj['properties'] return cpc_props
python
def get_energy_management_properties(self): result = self.manager.session.get(self.uri + '/energy-management-data') em_list = result['objects'] if len(em_list) != 1: uris = [em_obj['object-uri'] for em_obj in em_list] raise ParseError("Energy management data returned for no resource " "or for more than one resource: %r" % uris) em_cpc_obj = em_list[0] if em_cpc_obj['object-uri'] != self.uri: raise ParseError("Energy management data returned for an " "unexpected resource: %r" % em_cpc_obj['object-uri']) if em_cpc_obj['error-occurred']: raise ParseError("Errors occurred when retrieving energy " "management data for CPC. Operation result: %r" % result) cpc_props = em_cpc_obj['properties'] return cpc_props
[ "def", "get_energy_management_properties", "(", "self", ")", ":", "result", "=", "self", ".", "manager", ".", "session", ".", "get", "(", "self", ".", "uri", "+", "'/energy-management-data'", ")", "em_list", "=", "result", "[", "'objects'", "]", "if", "len",...
Return the energy management properties of the CPC. The returned energy management properties are a subset of the properties of the CPC resource, and are also available as normal properties of the CPC resource. In so far, there is no new data provided by this method. However, because only a subset of the properties is returned, this method is faster than retrieving the complete set of CPC properties (e.g. via :meth:`~zhmcclient.BaseResource.pull_full_properties`). This method performs the HMC operation "Get CPC Energy Management Data", and returns only the energy management properties for this CPC from the operation result. Note that in non-ensemble mode of a CPC, the HMC operation result will only contain data for the CPC alone. It requires that the feature "Automate/advanced management suite" (FC 0020) is installed and enabled, and returns empty values for most properties, otherwise. Authorization requirements: * Object-access permission to this CPC. Returns: dict: A dictionary of properties of the CPC that are related to energy management. For details, see section "Energy management related additional properties" in the data model for the CPC resource in the :term:`HMC API` book. Raises: :exc:`~zhmcclient.HTTPError`: See the HTTP status and reason codes of operation "Get CPC Energy Management Data" in the :term:`HMC API` book. :exc:`~zhmcclient.ParseError`: Also raised by this method when the JSON response could be parsed but contains inconsistent data. :exc:`~zhmcclient.AuthError` :exc:`~zhmcclient.ConnectionError`
[ "Return", "the", "energy", "management", "properties", "of", "the", "CPC", "." ]
9657563e5d9184c51d3c903442a58b9725fdf335
https://github.com/zhmcclient/python-zhmcclient/blob/9657563e5d9184c51d3c903442a58b9725fdf335/zhmcclient/_cpc.py#L1143-L1201
15,137
zhmcclient/python-zhmcclient
zhmcclient/_cpc.py
Cpc.validate_lun_path
def validate_lun_path(self, host_wwpn, host_port, wwpn, lun): """ Validate if an FCP storage volume on an actual storage subsystem is reachable from this CPC, through a specified host port and using a specified host WWPN. This method performs the "Validate LUN Path" HMC operation. If the volume is reachable, the method returns. If the volume is not reachable (and no other errors occur), an :exc:`~zhmcclient.HTTPError` is raised, and its :attr:`~zhmcclient.HTTPError.reason` property indicates the reason as follows: * 484: Target WWPN cannot be reached. * 485: Target WWPN can be reached, but LUN cannot be reached. The CPC must have the "dpm-storage-management" feature enabled. Parameters: host_wwpn (:term:`string`): World wide port name (WWPN) of the host (CPC), as a hexadecimal number of up to 16 characters in any lexical case. This may be the WWPN of the physical storage port, or a WWPN of a virtual HBA. In any case, it must be the kind of WWPN that is used for zoning and LUN masking in the SAN. host_port (:class:`~zhmcclient.Port`): Storage port on the CPC that will be used for validating reachability. wwpn (:term:`string`): World wide port name (WWPN) of the FCP storage subsystem containing the storage volume, as a hexadecimal number of up to 16 characters in any lexical case. lun (:term:`string`): Logical Unit Number (LUN) of the storage volume within its FCP storage subsystem, as a hexadecimal number of up to 16 characters in any lexical case. Authorization requirements: * Object-access permission to the storage group owning this storage volume. * Task permission to the "Configure Storage - Storage Administrator" task. Raises: :exc:`~zhmcclient.HTTPError` :exc:`~zhmcclient.ParseError` :exc:`~zhmcclient.AuthError` :exc:`~zhmcclient.ConnectionError` """ # The operation requires exactly 16 characters in lower case host_wwpn_16 = format(int(host_wwpn, 16), '016x') wwpn_16 = format(int(wwpn, 16), '016x') lun_16 = format(int(lun, 16), '016x') body = { 'host-world-wide-port-name': host_wwpn_16, 'adapter-port-uri': host_port.uri, 'target-world-wide-port-name': wwpn_16, 'logical-unit-number': lun_16, } self.manager.session.post( self.uri + '/operations/validate-lun-path', body=body)
python
def validate_lun_path(self, host_wwpn, host_port, wwpn, lun): # The operation requires exactly 16 characters in lower case host_wwpn_16 = format(int(host_wwpn, 16), '016x') wwpn_16 = format(int(wwpn, 16), '016x') lun_16 = format(int(lun, 16), '016x') body = { 'host-world-wide-port-name': host_wwpn_16, 'adapter-port-uri': host_port.uri, 'target-world-wide-port-name': wwpn_16, 'logical-unit-number': lun_16, } self.manager.session.post( self.uri + '/operations/validate-lun-path', body=body)
[ "def", "validate_lun_path", "(", "self", ",", "host_wwpn", ",", "host_port", ",", "wwpn", ",", "lun", ")", ":", "# The operation requires exactly 16 characters in lower case", "host_wwpn_16", "=", "format", "(", "int", "(", "host_wwpn", ",", "16", ")", ",", "'016x...
Validate if an FCP storage volume on an actual storage subsystem is reachable from this CPC, through a specified host port and using a specified host WWPN. This method performs the "Validate LUN Path" HMC operation. If the volume is reachable, the method returns. If the volume is not reachable (and no other errors occur), an :exc:`~zhmcclient.HTTPError` is raised, and its :attr:`~zhmcclient.HTTPError.reason` property indicates the reason as follows: * 484: Target WWPN cannot be reached. * 485: Target WWPN can be reached, but LUN cannot be reached. The CPC must have the "dpm-storage-management" feature enabled. Parameters: host_wwpn (:term:`string`): World wide port name (WWPN) of the host (CPC), as a hexadecimal number of up to 16 characters in any lexical case. This may be the WWPN of the physical storage port, or a WWPN of a virtual HBA. In any case, it must be the kind of WWPN that is used for zoning and LUN masking in the SAN. host_port (:class:`~zhmcclient.Port`): Storage port on the CPC that will be used for validating reachability. wwpn (:term:`string`): World wide port name (WWPN) of the FCP storage subsystem containing the storage volume, as a hexadecimal number of up to 16 characters in any lexical case. lun (:term:`string`): Logical Unit Number (LUN) of the storage volume within its FCP storage subsystem, as a hexadecimal number of up to 16 characters in any lexical case. Authorization requirements: * Object-access permission to the storage group owning this storage volume. * Task permission to the "Configure Storage - Storage Administrator" task. Raises: :exc:`~zhmcclient.HTTPError` :exc:`~zhmcclient.ParseError` :exc:`~zhmcclient.AuthError` :exc:`~zhmcclient.ConnectionError`
[ "Validate", "if", "an", "FCP", "storage", "volume", "on", "an", "actual", "storage", "subsystem", "is", "reachable", "from", "this", "CPC", "through", "a", "specified", "host", "port", "and", "using", "a", "specified", "host", "WWPN", "." ]
9657563e5d9184c51d3c903442a58b9725fdf335
https://github.com/zhmcclient/python-zhmcclient/blob/9657563e5d9184c51d3c903442a58b9725fdf335/zhmcclient/_cpc.py#L1269-L1339
15,138
zhmcclient/python-zhmcclient
zhmcclient/_user_pattern.py
UserPatternManager.reorder
def reorder(self, user_patterns): """ Reorder the User Patterns of the HMC as specified. The order of User Patterns determines the search order during logon processing. Authorization requirements: * Task permission to the "Manage User Patterns" task. Parameters: user_patterns (list of :class:`~zhmcclient.UserPattern`): The User Patterns in the desired order. Must not be `None`. Raises: :exc:`~zhmcclient.HTTPError` :exc:`~zhmcclient.ParseError` :exc:`~zhmcclient.AuthError` :exc:`~zhmcclient.ConnectionError` """ # noqa: E501 body = { 'user-pattern-uris': [up.uri for up in user_patterns] } self.manager.session.post( '/api/console/operations/reorder-user-patterns', body=body)
python
def reorder(self, user_patterns): # noqa: E501 body = { 'user-pattern-uris': [up.uri for up in user_patterns] } self.manager.session.post( '/api/console/operations/reorder-user-patterns', body=body)
[ "def", "reorder", "(", "self", ",", "user_patterns", ")", ":", "# noqa: E501", "body", "=", "{", "'user-pattern-uris'", ":", "[", "up", ".", "uri", "for", "up", "in", "user_patterns", "]", "}", "self", ".", "manager", ".", "session", ".", "post", "(", ...
Reorder the User Patterns of the HMC as specified. The order of User Patterns determines the search order during logon processing. Authorization requirements: * Task permission to the "Manage User Patterns" task. Parameters: user_patterns (list of :class:`~zhmcclient.UserPattern`): The User Patterns in the desired order. Must not be `None`. Raises: :exc:`~zhmcclient.HTTPError` :exc:`~zhmcclient.ParseError` :exc:`~zhmcclient.AuthError` :exc:`~zhmcclient.ConnectionError`
[ "Reorder", "the", "User", "Patterns", "of", "the", "HMC", "as", "specified", "." ]
9657563e5d9184c51d3c903442a58b9725fdf335
https://github.com/zhmcclient/python-zhmcclient/blob/9657563e5d9184c51d3c903442a58b9725fdf335/zhmcclient/_user_pattern.py#L195-L225
15,139
zhmcclient/python-zhmcclient
zhmcclient/_timestats.py
TimeStats.reset
def reset(self): """ Reset the time statistics data for the operation. """ self._count = 0 self._sum = float(0) self._min = float('inf') self._max = float(0)
python
def reset(self): self._count = 0 self._sum = float(0) self._min = float('inf') self._max = float(0)
[ "def", "reset", "(", "self", ")", ":", "self", ".", "_count", "=", "0", "self", ".", "_sum", "=", "float", "(", "0", ")", "self", ".", "_min", "=", "float", "(", "'inf'", ")", "self", ".", "_max", "=", "float", "(", "0", ")" ]
Reset the time statistics data for the operation.
[ "Reset", "the", "time", "statistics", "data", "for", "the", "operation", "." ]
9657563e5d9184c51d3c903442a58b9725fdf335
https://github.com/zhmcclient/python-zhmcclient/blob/9657563e5d9184c51d3c903442a58b9725fdf335/zhmcclient/_timestats.py#L134-L141
15,140
zhmcclient/python-zhmcclient
zhmcclient/_timestats.py
TimeStatsKeeper.get_stats
def get_stats(self, name): """ Get the time statistics for a name. If a time statistics for that name does not exist yet, create one. Parameters: name (string): Name of the time statistics. Returns: TimeStats: The time statistics for the specified name. If the statistics keeper is disabled, a dummy time statistics object is returned, in order to save resources. """ if not self.enabled: return self._disabled_stats if name not in self._time_stats: self._time_stats[name] = TimeStats(self, name) return self._time_stats[name]
python
def get_stats(self, name): if not self.enabled: return self._disabled_stats if name not in self._time_stats: self._time_stats[name] = TimeStats(self, name) return self._time_stats[name]
[ "def", "get_stats", "(", "self", ",", "name", ")", ":", "if", "not", "self", ".", "enabled", ":", "return", "self", ".", "_disabled_stats", "if", "name", "not", "in", "self", ".", "_time_stats", ":", "self", ".", "_time_stats", "[", "name", "]", "=", ...
Get the time statistics for a name. If a time statistics for that name does not exist yet, create one. Parameters: name (string): Name of the time statistics. Returns: TimeStats: The time statistics for the specified name. If the statistics keeper is disabled, a dummy time statistics object is returned, in order to save resources.
[ "Get", "the", "time", "statistics", "for", "a", "name", ".", "If", "a", "time", "statistics", "for", "that", "name", "does", "not", "exist", "yet", "create", "one", "." ]
9657563e5d9184c51d3c903442a58b9725fdf335
https://github.com/zhmcclient/python-zhmcclient/blob/9657563e5d9184c51d3c903442a58b9725fdf335/zhmcclient/_timestats.py#L255-L275
15,141
zhmcclient/python-zhmcclient
zhmcclient/_unmanaged_cpc.py
UnmanagedCpcManager.list
def list(self, full_properties=False, filter_args=None): """ List the unmanaged CPCs exposed by the HMC this client is connected to. Because the CPCs are unmanaged, the returned :class:`~zhmcclient.UnmanagedCpc` objects cannot perform any operations and will have only the following properties: * ``object-uri`` * ``name`` Authorization requirements: * None Parameters: full_properties (bool): Ignored (exists for consistency with other list() methods). filter_args (dict): Filter arguments that narrow the list of returned resources to those that match the specified filter arguments. For details, see :ref:`Filtering`. `None` causes no filtering to happen, i.e. all resources are returned. Returns: : A list of :class:`~zhmcclient.UnmanagedCpc` objects. Raises: :exc:`~zhmcclient.HTTPError` :exc:`~zhmcclient.ParseError` :exc:`~zhmcclient.AuthError` :exc:`~zhmcclient.ConnectionError` """ resource_obj_list = [] resource_obj = self._try_optimized_lookup(filter_args) if resource_obj: resource_obj_list.append(resource_obj) else: query_parms, client_filters = self._divide_filter_args(filter_args) uri = self.parent.uri + '/operations/list-unmanaged-cpcs' + \ query_parms result = self.session.get(uri) if result: props_list = result['cpcs'] for props in props_list: resource_obj = self.resource_class( manager=self, uri=props[self._uri_prop], name=props.get(self._name_prop, None), properties=props) if self._matches_filters(resource_obj, client_filters): resource_obj_list.append(resource_obj) self._name_uri_cache.update_from(resource_obj_list) return resource_obj_list
python
def list(self, full_properties=False, filter_args=None): resource_obj_list = [] resource_obj = self._try_optimized_lookup(filter_args) if resource_obj: resource_obj_list.append(resource_obj) else: query_parms, client_filters = self._divide_filter_args(filter_args) uri = self.parent.uri + '/operations/list-unmanaged-cpcs' + \ query_parms result = self.session.get(uri) if result: props_list = result['cpcs'] for props in props_list: resource_obj = self.resource_class( manager=self, uri=props[self._uri_prop], name=props.get(self._name_prop, None), properties=props) if self._matches_filters(resource_obj, client_filters): resource_obj_list.append(resource_obj) self._name_uri_cache.update_from(resource_obj_list) return resource_obj_list
[ "def", "list", "(", "self", ",", "full_properties", "=", "False", ",", "filter_args", "=", "None", ")", ":", "resource_obj_list", "=", "[", "]", "resource_obj", "=", "self", ".", "_try_optimized_lookup", "(", "filter_args", ")", "if", "resource_obj", ":", "r...
List the unmanaged CPCs exposed by the HMC this client is connected to. Because the CPCs are unmanaged, the returned :class:`~zhmcclient.UnmanagedCpc` objects cannot perform any operations and will have only the following properties: * ``object-uri`` * ``name`` Authorization requirements: * None Parameters: full_properties (bool): Ignored (exists for consistency with other list() methods). filter_args (dict): Filter arguments that narrow the list of returned resources to those that match the specified filter arguments. For details, see :ref:`Filtering`. `None` causes no filtering to happen, i.e. all resources are returned. Returns: : A list of :class:`~zhmcclient.UnmanagedCpc` objects. Raises: :exc:`~zhmcclient.HTTPError` :exc:`~zhmcclient.ParseError` :exc:`~zhmcclient.AuthError` :exc:`~zhmcclient.ConnectionError`
[ "List", "the", "unmanaged", "CPCs", "exposed", "by", "the", "HMC", "this", "client", "is", "connected", "to", "." ]
9657563e5d9184c51d3c903442a58b9725fdf335
https://github.com/zhmcclient/python-zhmcclient/blob/9657563e5d9184c51d3c903442a58b9725fdf335/zhmcclient/_unmanaged_cpc.py#L85-L149
15,142
zhmcclient/python-zhmcclient
zhmcclient_mock/_urihandler.py
parse_query_parms
def parse_query_parms(method, uri, query_str): """ Parse the specified query parms string and return a dictionary of query parameters. The key of each dict item is the query parameter name, and the value of each dict item is the query parameter value. If a query parameter shows up more than once, the resulting dict item value is a list of all those values. query_str is the query string from the URL, everything after the '?'. If it is empty or None, None is returned. If a query parameter is not of the format "name=value", an HTTPError 400,1 is raised. """ if not query_str: return None query_parms = {} for query_item in query_str.split('&'): # Example for these items: 'name=a%20b' if query_item == '': continue items = query_item.split('=') if len(items) != 2: raise BadRequestError( method, uri, reason=1, message="Invalid format for URI query parameter: {!r} " "(valid format is: 'name=value').". format(query_item)) name = unquote(items[0]) value = unquote(items[1]) if name in query_parms: existing_value = query_parms[name] if not isinstance(existing_value, list): query_parms[name] = list() query_parms[name].append(existing_value) query_parms[name].append(value) else: query_parms[name] = value return query_parms
python
def parse_query_parms(method, uri, query_str): if not query_str: return None query_parms = {} for query_item in query_str.split('&'): # Example for these items: 'name=a%20b' if query_item == '': continue items = query_item.split('=') if len(items) != 2: raise BadRequestError( method, uri, reason=1, message="Invalid format for URI query parameter: {!r} " "(valid format is: 'name=value').". format(query_item)) name = unquote(items[0]) value = unquote(items[1]) if name in query_parms: existing_value = query_parms[name] if not isinstance(existing_value, list): query_parms[name] = list() query_parms[name].append(existing_value) query_parms[name].append(value) else: query_parms[name] = value return query_parms
[ "def", "parse_query_parms", "(", "method", ",", "uri", ",", "query_str", ")", ":", "if", "not", "query_str", ":", "return", "None", "query_parms", "=", "{", "}", "for", "query_item", "in", "query_str", ".", "split", "(", "'&'", ")", ":", "# Example for the...
Parse the specified query parms string and return a dictionary of query parameters. The key of each dict item is the query parameter name, and the value of each dict item is the query parameter value. If a query parameter shows up more than once, the resulting dict item value is a list of all those values. query_str is the query string from the URL, everything after the '?'. If it is empty or None, None is returned. If a query parameter is not of the format "name=value", an HTTPError 400,1 is raised.
[ "Parse", "the", "specified", "query", "parms", "string", "and", "return", "a", "dictionary", "of", "query", "parameters", ".", "The", "key", "of", "each", "dict", "item", "is", "the", "query", "parameter", "name", "and", "the", "value", "of", "each", "dict...
9657563e5d9184c51d3c903442a58b9725fdf335
https://github.com/zhmcclient/python-zhmcclient/blob/9657563e5d9184c51d3c903442a58b9725fdf335/zhmcclient_mock/_urihandler.py#L166-L204
15,143
zhmcclient/python-zhmcclient
zhmcclient_mock/_urihandler.py
check_required_fields
def check_required_fields(method, uri, body, field_names): """ Check required fields in the request body. Raises: BadRequestError with reason 3: Missing request body BadRequestError with reason 5: Missing required field in request body """ # Check presence of request body if body is None: raise BadRequestError(method, uri, reason=3, message="Missing request body") # Check required input fields for field_name in field_names: if field_name not in body: raise BadRequestError(method, uri, reason=5, message="Missing required field in request " "body: {}".format(field_name))
python
def check_required_fields(method, uri, body, field_names): # Check presence of request body if body is None: raise BadRequestError(method, uri, reason=3, message="Missing request body") # Check required input fields for field_name in field_names: if field_name not in body: raise BadRequestError(method, uri, reason=5, message="Missing required field in request " "body: {}".format(field_name))
[ "def", "check_required_fields", "(", "method", ",", "uri", ",", "body", ",", "field_names", ")", ":", "# Check presence of request body", "if", "body", "is", "None", ":", "raise", "BadRequestError", "(", "method", ",", "uri", ",", "reason", "=", "3", ",", "m...
Check required fields in the request body. Raises: BadRequestError with reason 3: Missing request body BadRequestError with reason 5: Missing required field in request body
[ "Check", "required", "fields", "in", "the", "request", "body", "." ]
9657563e5d9184c51d3c903442a58b9725fdf335
https://github.com/zhmcclient/python-zhmcclient/blob/9657563e5d9184c51d3c903442a58b9725fdf335/zhmcclient_mock/_urihandler.py#L207-L226
15,144
zhmcclient/python-zhmcclient
zhmcclient_mock/_urihandler.py
check_valid_cpc_status
def check_valid_cpc_status(method, uri, cpc): """ Check that the CPC is in a valid status, as indicated by its 'status' property. If the Cpc object does not have a 'status' property set, this function does nothing (in order to make the mock support easy to use). Raises: ConflictError with reason 1: The CPC itself has been targeted by the operation. ConflictError with reason 6: The CPC is hosting the resource targeted by the operation. """ status = cpc.properties.get('status', None) if status is None: # Do nothing if no status is set on the faked CPC return valid_statuses = ['active', 'service-required', 'degraded', 'exceptions'] if status not in valid_statuses: if uri.startswith(cpc.uri): # The uri targets the CPC (either is the CPC uri or some # multiplicity under the CPC uri) raise ConflictError(method, uri, reason=1, message="The operation cannot be performed " "because the targeted CPC {} has a status " "that is not valid for the operation: {}". format(cpc.name, status)) else: # The uri targets a resource hosted by the CPC raise ConflictError(method, uri, reason=6, message="The operation cannot be performed " "because CPC {} hosting the targeted resource " "has a status that is not valid for the " "operation: {}". format(cpc.name, status))
python
def check_valid_cpc_status(method, uri, cpc): status = cpc.properties.get('status', None) if status is None: # Do nothing if no status is set on the faked CPC return valid_statuses = ['active', 'service-required', 'degraded', 'exceptions'] if status not in valid_statuses: if uri.startswith(cpc.uri): # The uri targets the CPC (either is the CPC uri or some # multiplicity under the CPC uri) raise ConflictError(method, uri, reason=1, message="The operation cannot be performed " "because the targeted CPC {} has a status " "that is not valid for the operation: {}". format(cpc.name, status)) else: # The uri targets a resource hosted by the CPC raise ConflictError(method, uri, reason=6, message="The operation cannot be performed " "because CPC {} hosting the targeted resource " "has a status that is not valid for the " "operation: {}". format(cpc.name, status))
[ "def", "check_valid_cpc_status", "(", "method", ",", "uri", ",", "cpc", ")", ":", "status", "=", "cpc", ".", "properties", ".", "get", "(", "'status'", ",", "None", ")", "if", "status", "is", "None", ":", "# Do nothing if no status is set on the faked CPC", "r...
Check that the CPC is in a valid status, as indicated by its 'status' property. If the Cpc object does not have a 'status' property set, this function does nothing (in order to make the mock support easy to use). Raises: ConflictError with reason 1: The CPC itself has been targeted by the operation. ConflictError with reason 6: The CPC is hosting the resource targeted by the operation.
[ "Check", "that", "the", "CPC", "is", "in", "a", "valid", "status", "as", "indicated", "by", "its", "status", "property", "." ]
9657563e5d9184c51d3c903442a58b9725fdf335
https://github.com/zhmcclient/python-zhmcclient/blob/9657563e5d9184c51d3c903442a58b9725fdf335/zhmcclient_mock/_urihandler.py#L229-L264
15,145
zhmcclient/python-zhmcclient
zhmcclient_mock/_urihandler.py
ensure_crypto_config
def ensure_crypto_config(partition): """ Ensure that the 'crypto-configuration' property on the faked partition is initialized. """ if 'crypto-configuration' not in partition.properties or \ partition.properties['crypto-configuration'] is None: partition.properties['crypto-configuration'] = {} crypto_config = partition.properties['crypto-configuration'] if 'crypto-adapter-uris' not in crypto_config or \ crypto_config['crypto-adapter-uris'] is None: crypto_config['crypto-adapter-uris'] = [] adapter_uris = crypto_config['crypto-adapter-uris'] if 'crypto-domain-configurations' not in crypto_config or \ crypto_config['crypto-domain-configurations'] is None: crypto_config['crypto-domain-configurations'] = [] domain_configs = crypto_config['crypto-domain-configurations'] return adapter_uris, domain_configs
python
def ensure_crypto_config(partition): if 'crypto-configuration' not in partition.properties or \ partition.properties['crypto-configuration'] is None: partition.properties['crypto-configuration'] = {} crypto_config = partition.properties['crypto-configuration'] if 'crypto-adapter-uris' not in crypto_config or \ crypto_config['crypto-adapter-uris'] is None: crypto_config['crypto-adapter-uris'] = [] adapter_uris = crypto_config['crypto-adapter-uris'] if 'crypto-domain-configurations' not in crypto_config or \ crypto_config['crypto-domain-configurations'] is None: crypto_config['crypto-domain-configurations'] = [] domain_configs = crypto_config['crypto-domain-configurations'] return adapter_uris, domain_configs
[ "def", "ensure_crypto_config", "(", "partition", ")", ":", "if", "'crypto-configuration'", "not", "in", "partition", ".", "properties", "or", "partition", ".", "properties", "[", "'crypto-configuration'", "]", "is", "None", ":", "partition", ".", "properties", "["...
Ensure that the 'crypto-configuration' property on the faked partition is initialized.
[ "Ensure", "that", "the", "crypto", "-", "configuration", "property", "on", "the", "faked", "partition", "is", "initialized", "." ]
9657563e5d9184c51d3c903442a58b9725fdf335
https://github.com/zhmcclient/python-zhmcclient/blob/9657563e5d9184c51d3c903442a58b9725fdf335/zhmcclient_mock/_urihandler.py#L1648-L1669
15,146
zhmcclient/python-zhmcclient
zhmcclient/_partition.py
PartitionManager.create
def create(self, properties): """ Create and configure a Partition in this CPC. Authorization requirements: * Object-access permission to this CPC. * Task permission to the "New Partition" task. Parameters: properties (dict): Initial property values. Allowable properties are defined in section 'Request body contents' in section 'Create Partition' in the :term:`HMC API` book. Returns: Partition: The resource object for the new Partition. The object will have its 'object-uri' property set as returned by the HMC, and will also have the input properties set. Raises: :exc:`~zhmcclient.HTTPError` :exc:`~zhmcclient.ParseError` :exc:`~zhmcclient.AuthError` :exc:`~zhmcclient.ConnectionError` """ result = self.session.post(self.cpc.uri + '/partitions', body=properties) # There should not be overlaps, but just in case there are, the # returned props should overwrite the input props: props = copy.deepcopy(properties) props.update(result) name = props.get(self._name_prop, None) uri = props[self._uri_prop] part = Partition(self, uri, name, props) self._name_uri_cache.update(name, uri) return part
python
def create(self, properties): result = self.session.post(self.cpc.uri + '/partitions', body=properties) # There should not be overlaps, but just in case there are, the # returned props should overwrite the input props: props = copy.deepcopy(properties) props.update(result) name = props.get(self._name_prop, None) uri = props[self._uri_prop] part = Partition(self, uri, name, props) self._name_uri_cache.update(name, uri) return part
[ "def", "create", "(", "self", ",", "properties", ")", ":", "result", "=", "self", ".", "session", ".", "post", "(", "self", ".", "cpc", ".", "uri", "+", "'/partitions'", ",", "body", "=", "properties", ")", "# There should not be overlaps, but just in case the...
Create and configure a Partition in this CPC. Authorization requirements: * Object-access permission to this CPC. * Task permission to the "New Partition" task. Parameters: properties (dict): Initial property values. Allowable properties are defined in section 'Request body contents' in section 'Create Partition' in the :term:`HMC API` book. Returns: Partition: The resource object for the new Partition. The object will have its 'object-uri' property set as returned by the HMC, and will also have the input properties set. Raises: :exc:`~zhmcclient.HTTPError` :exc:`~zhmcclient.ParseError` :exc:`~zhmcclient.AuthError` :exc:`~zhmcclient.ConnectionError`
[ "Create", "and", "configure", "a", "Partition", "in", "this", "CPC", "." ]
9657563e5d9184c51d3c903442a58b9725fdf335
https://github.com/zhmcclient/python-zhmcclient/blob/9657563e5d9184c51d3c903442a58b9725fdf335/zhmcclient/_partition.py#L168-L207
15,147
zhmcclient/python-zhmcclient
zhmcclient/_partition.py
Partition.feature_enabled
def feature_enabled(self, feature_name): """ Indicates whether the specified feature is enabled for the CPC of this partition. The HMC must generally support features, and the specified feature must be available for the CPC. For a list of available features, see section "Features" in the :term:`HMC API`, or use the :meth:`feature_info` method. Authorization requirements: * Object-access permission to this partition. Parameters: feature_name (:term:`string`): The name of the feature. Returns: bool: `True` if the feature is enabled, or `False` if the feature is disabled (but available). Raises: :exc:`ValueError`: Features are not supported on the HMC. :exc:`ValueError`: The specified feature is not available for the CPC. :exc:`~zhmcclient.HTTPError` :exc:`~zhmcclient.ParseError` :exc:`~zhmcclient.AuthError` :exc:`~zhmcclient.ConnectionError` """ feature_list = self.prop('available-features-list', None) if feature_list is None: raise ValueError("Firmware features are not supported on CPC %s" % self.manager.cpc.name) for feature in feature_list: if feature['name'] == feature_name: break else: raise ValueError("Firmware feature %s is not available on CPC %s" % (feature_name, self.manager.cpc.name)) return feature['state']
python
def feature_enabled(self, feature_name): feature_list = self.prop('available-features-list', None) if feature_list is None: raise ValueError("Firmware features are not supported on CPC %s" % self.manager.cpc.name) for feature in feature_list: if feature['name'] == feature_name: break else: raise ValueError("Firmware feature %s is not available on CPC %s" % (feature_name, self.manager.cpc.name)) return feature['state']
[ "def", "feature_enabled", "(", "self", ",", "feature_name", ")", ":", "feature_list", "=", "self", ".", "prop", "(", "'available-features-list'", ",", "None", ")", "if", "feature_list", "is", "None", ":", "raise", "ValueError", "(", "\"Firmware features are not su...
Indicates whether the specified feature is enabled for the CPC of this partition. The HMC must generally support features, and the specified feature must be available for the CPC. For a list of available features, see section "Features" in the :term:`HMC API`, or use the :meth:`feature_info` method. Authorization requirements: * Object-access permission to this partition. Parameters: feature_name (:term:`string`): The name of the feature. Returns: bool: `True` if the feature is enabled, or `False` if the feature is disabled (but available). Raises: :exc:`ValueError`: Features are not supported on the HMC. :exc:`ValueError`: The specified feature is not available for the CPC. :exc:`~zhmcclient.HTTPError` :exc:`~zhmcclient.ParseError` :exc:`~zhmcclient.AuthError` :exc:`~zhmcclient.ConnectionError`
[ "Indicates", "whether", "the", "specified", "feature", "is", "enabled", "for", "the", "CPC", "of", "this", "partition", "." ]
9657563e5d9184c51d3c903442a58b9725fdf335
https://github.com/zhmcclient/python-zhmcclient/blob/9657563e5d9184c51d3c903442a58b9725fdf335/zhmcclient/_partition.py#L284-L328
15,148
zhmcclient/python-zhmcclient
zhmcclient/_partition.py
Partition.feature_info
def feature_info(self): """ Returns information about the features available for the CPC of this partition. Authorization requirements: * Object-access permission to this partition. Returns: :term:`iterable`: An iterable where each item represents one feature that is available for the CPC of this partition. Each item is a dictionary with the following items: * `name` (:term:`unicode string`): Name of the feature. * `description` (:term:`unicode string`): Short description of the feature. * `state` (bool): Enablement state of the feature (`True` if the enabled, `False` if disabled). Raises: :exc:`ValueError`: Features are not supported on the HMC. :exc:`~zhmcclient.HTTPError` :exc:`~zhmcclient.ParseError` :exc:`~zhmcclient.AuthError` :exc:`~zhmcclient.ConnectionError` """ feature_list = self.prop('available-features-list', None) if feature_list is None: raise ValueError("Firmware features are not supported on CPC %s" % self.manager.cpc.name) return feature_list
python
def feature_info(self): feature_list = self.prop('available-features-list', None) if feature_list is None: raise ValueError("Firmware features are not supported on CPC %s" % self.manager.cpc.name) return feature_list
[ "def", "feature_info", "(", "self", ")", ":", "feature_list", "=", "self", ".", "prop", "(", "'available-features-list'", ",", "None", ")", "if", "feature_list", "is", "None", ":", "raise", "ValueError", "(", "\"Firmware features are not supported on CPC %s\"", "%",...
Returns information about the features available for the CPC of this partition. Authorization requirements: * Object-access permission to this partition. Returns: :term:`iterable`: An iterable where each item represents one feature that is available for the CPC of this partition. Each item is a dictionary with the following items: * `name` (:term:`unicode string`): Name of the feature. * `description` (:term:`unicode string`): Short description of the feature. * `state` (bool): Enablement state of the feature (`True` if the enabled, `False` if disabled). Raises: :exc:`ValueError`: Features are not supported on the HMC. :exc:`~zhmcclient.HTTPError` :exc:`~zhmcclient.ParseError` :exc:`~zhmcclient.AuthError` :exc:`~zhmcclient.ConnectionError`
[ "Returns", "information", "about", "the", "features", "available", "for", "the", "CPC", "of", "this", "partition", "." ]
9657563e5d9184c51d3c903442a58b9725fdf335
https://github.com/zhmcclient/python-zhmcclient/blob/9657563e5d9184c51d3c903442a58b9725fdf335/zhmcclient/_partition.py#L331-L366
15,149
zhmcclient/python-zhmcclient
zhmcclient/_partition.py
Partition.dump_partition
def dump_partition(self, parameters, wait_for_completion=True, operation_timeout=None): """ Dump this Partition, by loading a standalone dump program from a SCSI device and starting its execution, using the HMC operation 'Dump Partition'. Authorization requirements: * Object-access permission to this Partition. * Task permission to the "Dump Partition" task. Parameters: parameters (dict): Input parameters for the operation. Allowable input parameters are defined in section 'Request body contents' in section 'Dump Partition' in the :term:`HMC API` book. wait_for_completion (bool): Boolean controlling whether this method should wait for completion of the requested asynchronous HMC operation, as follows: * If `True`, this method will wait for completion of the asynchronous job performing the operation. * If `False`, this method will return immediately once the HMC has accepted the request to perform the operation. operation_timeout (:term:`number`): Timeout in seconds, for waiting for completion of the asynchronous job performing the operation. The special value 0 means that no timeout is set. `None` means that the default async operation timeout of the session is used. If the timeout expires when `wait_for_completion=True`, a :exc:`~zhmcclient.OperationTimeout` is raised. Returns: :class:`py:dict` or :class:`~zhmcclient.Job`: If `wait_for_completion` is `True`, returns an empty :class:`py:dict` object. If `wait_for_completion` is `False`, returns a :class:`~zhmcclient.Job` object representing the asynchronously executing job on the HMC. Raises: :exc:`~zhmcclient.HTTPError` :exc:`~zhmcclient.ParseError` :exc:`~zhmcclient.AuthError` :exc:`~zhmcclient.ConnectionError` :exc:`~zhmcclient.OperationTimeout`: The timeout expired while waiting for completion of the operation. """ result = self.manager.session.post( self.uri + '/operations/scsi-dump', wait_for_completion=wait_for_completion, operation_timeout=operation_timeout, body=parameters) return result
python
def dump_partition(self, parameters, wait_for_completion=True, operation_timeout=None): result = self.manager.session.post( self.uri + '/operations/scsi-dump', wait_for_completion=wait_for_completion, operation_timeout=operation_timeout, body=parameters) return result
[ "def", "dump_partition", "(", "self", ",", "parameters", ",", "wait_for_completion", "=", "True", ",", "operation_timeout", "=", "None", ")", ":", "result", "=", "self", ".", "manager", ".", "session", ".", "post", "(", "self", ".", "uri", "+", "'/operatio...
Dump this Partition, by loading a standalone dump program from a SCSI device and starting its execution, using the HMC operation 'Dump Partition'. Authorization requirements: * Object-access permission to this Partition. * Task permission to the "Dump Partition" task. Parameters: parameters (dict): Input parameters for the operation. Allowable input parameters are defined in section 'Request body contents' in section 'Dump Partition' in the :term:`HMC API` book. wait_for_completion (bool): Boolean controlling whether this method should wait for completion of the requested asynchronous HMC operation, as follows: * If `True`, this method will wait for completion of the asynchronous job performing the operation. * If `False`, this method will return immediately once the HMC has accepted the request to perform the operation. operation_timeout (:term:`number`): Timeout in seconds, for waiting for completion of the asynchronous job performing the operation. The special value 0 means that no timeout is set. `None` means that the default async operation timeout of the session is used. If the timeout expires when `wait_for_completion=True`, a :exc:`~zhmcclient.OperationTimeout` is raised. Returns: :class:`py:dict` or :class:`~zhmcclient.Job`: If `wait_for_completion` is `True`, returns an empty :class:`py:dict` object. If `wait_for_completion` is `False`, returns a :class:`~zhmcclient.Job` object representing the asynchronously executing job on the HMC. Raises: :exc:`~zhmcclient.HTTPError` :exc:`~zhmcclient.ParseError` :exc:`~zhmcclient.AuthError` :exc:`~zhmcclient.ConnectionError` :exc:`~zhmcclient.OperationTimeout`: The timeout expired while waiting for completion of the operation.
[ "Dump", "this", "Partition", "by", "loading", "a", "standalone", "dump", "program", "from", "a", "SCSI", "device", "and", "starting", "its", "execution", "using", "the", "HMC", "operation", "Dump", "Partition", "." ]
9657563e5d9184c51d3c903442a58b9725fdf335
https://github.com/zhmcclient/python-zhmcclient/blob/9657563e5d9184c51d3c903442a58b9725fdf335/zhmcclient/_partition.py#L566-L628
15,150
zhmcclient/python-zhmcclient
zhmcclient/_partition.py
Partition.mount_iso_image
def mount_iso_image(self, image, image_name, ins_file_name): """ Upload an ISO image and associate it to this Partition using the HMC operation 'Mount ISO Image'. When the partition already has an ISO image associated, the newly uploaded image replaces the current one. Authorization requirements: * Object-access permission to this Partition. * Task permission to the "Partition Details" task. Parameters: image (:term:`byte string` or file-like object): The content of the ISO image. Images larger than 2GB cannot be specified as a Byte string; they must be specified as a file-like object. File-like objects must have opened the file in binary mode. image_name (:term:`string`): The displayable name of the image. This value must be a valid Linux file name without directories, must not contain blanks, and must end with '.iso' in lower case. This value will be shown in the 'boot-iso-image-name' property of this partition. ins_file_name (:term:`string`): The path name of the INS file within the file system of the ISO image. This value will be shown in the 'boot-iso-ins-file' property of this partition. Raises: :exc:`~zhmcclient.HTTPError` :exc:`~zhmcclient.ParseError` :exc:`~zhmcclient.AuthError` :exc:`~zhmcclient.ConnectionError` """ query_parms_str = '?image-name={}&ins-file-name={}'. \ format(quote(image_name, safe=''), quote(ins_file_name, safe='')) self.manager.session.post( self.uri + '/operations/mount-iso-image' + query_parms_str, body=image)
python
def mount_iso_image(self, image, image_name, ins_file_name): query_parms_str = '?image-name={}&ins-file-name={}'. \ format(quote(image_name, safe=''), quote(ins_file_name, safe='')) self.manager.session.post( self.uri + '/operations/mount-iso-image' + query_parms_str, body=image)
[ "def", "mount_iso_image", "(", "self", ",", "image", ",", "image_name", ",", "ins_file_name", ")", ":", "query_parms_str", "=", "'?image-name={}&ins-file-name={}'", ".", "format", "(", "quote", "(", "image_name", ",", "safe", "=", "''", ")", ",", "quote", "(",...
Upload an ISO image and associate it to this Partition using the HMC operation 'Mount ISO Image'. When the partition already has an ISO image associated, the newly uploaded image replaces the current one. Authorization requirements: * Object-access permission to this Partition. * Task permission to the "Partition Details" task. Parameters: image (:term:`byte string` or file-like object): The content of the ISO image. Images larger than 2GB cannot be specified as a Byte string; they must be specified as a file-like object. File-like objects must have opened the file in binary mode. image_name (:term:`string`): The displayable name of the image. This value must be a valid Linux file name without directories, must not contain blanks, and must end with '.iso' in lower case. This value will be shown in the 'boot-iso-image-name' property of this partition. ins_file_name (:term:`string`): The path name of the INS file within the file system of the ISO image. This value will be shown in the 'boot-iso-ins-file' property of this partition. Raises: :exc:`~zhmcclient.HTTPError` :exc:`~zhmcclient.ParseError` :exc:`~zhmcclient.AuthError` :exc:`~zhmcclient.ConnectionError`
[ "Upload", "an", "ISO", "image", "and", "associate", "it", "to", "this", "Partition", "using", "the", "HMC", "operation", "Mount", "ISO", "Image", "." ]
9657563e5d9184c51d3c903442a58b9725fdf335
https://github.com/zhmcclient/python-zhmcclient/blob/9657563e5d9184c51d3c903442a58b9725fdf335/zhmcclient/_partition.py#L688-L736
15,151
zhmcclient/python-zhmcclient
zhmcclient/_partition.py
Partition.open_os_message_channel
def open_os_message_channel(self, include_refresh_messages=True): """ Open a JMS message channel to this partition's operating system, returning the string "topic" representing the message channel. Parameters: include_refresh_messages (bool): Boolean controlling whether refresh operating systems messages should be sent, as follows: * If `True`, refresh messages will be recieved when the user connects to the topic. The default. * If `False`, refresh messages will not be recieved when the user connects to the topic. Returns: :term:`string`: Returns a string representing the os-message-notification JMS topic. The user can connect to this topic to start the flow of operating system messages. Raises: :exc:`~zhmcclient.HTTPError` :exc:`~zhmcclient.ParseError` :exc:`~zhmcclient.AuthError` :exc:`~zhmcclient.ConnectionError` """ body = {'include-refresh-messages': include_refresh_messages} result = self.manager.session.post( self.uri + '/operations/open-os-message-channel', body) return result['topic-name']
python
def open_os_message_channel(self, include_refresh_messages=True): body = {'include-refresh-messages': include_refresh_messages} result = self.manager.session.post( self.uri + '/operations/open-os-message-channel', body) return result['topic-name']
[ "def", "open_os_message_channel", "(", "self", ",", "include_refresh_messages", "=", "True", ")", ":", "body", "=", "{", "'include-refresh-messages'", ":", "include_refresh_messages", "}", "result", "=", "self", ".", "manager", ".", "session", ".", "post", "(", ...
Open a JMS message channel to this partition's operating system, returning the string "topic" representing the message channel. Parameters: include_refresh_messages (bool): Boolean controlling whether refresh operating systems messages should be sent, as follows: * If `True`, refresh messages will be recieved when the user connects to the topic. The default. * If `False`, refresh messages will not be recieved when the user connects to the topic. Returns: :term:`string`: Returns a string representing the os-message-notification JMS topic. The user can connect to this topic to start the flow of operating system messages. Raises: :exc:`~zhmcclient.HTTPError` :exc:`~zhmcclient.ParseError` :exc:`~zhmcclient.AuthError` :exc:`~zhmcclient.ConnectionError`
[ "Open", "a", "JMS", "message", "channel", "to", "this", "partition", "s", "operating", "system", "returning", "the", "string", "topic", "representing", "the", "message", "channel", "." ]
9657563e5d9184c51d3c903442a58b9725fdf335
https://github.com/zhmcclient/python-zhmcclient/blob/9657563e5d9184c51d3c903442a58b9725fdf335/zhmcclient/_partition.py#L761-L796
15,152
zhmcclient/python-zhmcclient
zhmcclient/_partition.py
Partition.send_os_command
def send_os_command(self, os_command_text, is_priority=False): """ Send a command to the operating system running in this partition. Parameters: os_command_text (string): The text of the operating system command. is_priority (bool): Boolean controlling whether this is a priority operating system command, as follows: * If `True`, this message is treated as a priority operating system command. * If `False`, this message is not treated as a priority operating system command. The default. Returns: None Raises: :exc:`~zhmcclient.HTTPError` :exc:`~zhmcclient.ParseError` :exc:`~zhmcclient.AuthError` :exc:`~zhmcclient.ConnectionError` """ body = {'is-priority': is_priority, 'operating-system-command-text': os_command_text} self.manager.session.post( self.uri + '/operations/send-os-cmd', body)
python
def send_os_command(self, os_command_text, is_priority=False): body = {'is-priority': is_priority, 'operating-system-command-text': os_command_text} self.manager.session.post( self.uri + '/operations/send-os-cmd', body)
[ "def", "send_os_command", "(", "self", ",", "os_command_text", ",", "is_priority", "=", "False", ")", ":", "body", "=", "{", "'is-priority'", ":", "is_priority", ",", "'operating-system-command-text'", ":", "os_command_text", "}", "self", ".", "manager", ".", "s...
Send a command to the operating system running in this partition. Parameters: os_command_text (string): The text of the operating system command. is_priority (bool): Boolean controlling whether this is a priority operating system command, as follows: * If `True`, this message is treated as a priority operating system command. * If `False`, this message is not treated as a priority operating system command. The default. Returns: None Raises: :exc:`~zhmcclient.HTTPError` :exc:`~zhmcclient.ParseError` :exc:`~zhmcclient.AuthError` :exc:`~zhmcclient.ConnectionError`
[ "Send", "a", "command", "to", "the", "operating", "system", "running", "in", "this", "partition", "." ]
9657563e5d9184c51d3c903442a58b9725fdf335
https://github.com/zhmcclient/python-zhmcclient/blob/9657563e5d9184c51d3c903442a58b9725fdf335/zhmcclient/_partition.py#L799-L831
15,153
zhmcclient/python-zhmcclient
zhmcclient/_partition.py
Partition.wait_for_status
def wait_for_status(self, status, status_timeout=None): """ Wait until the status of this partition has a desired value. Parameters: status (:term:`string` or iterable of :term:`string`): Desired partition status or set of status values to reach; one or more of the values defined for the 'status' property in the data model for partitions in the :term:`HMC API` book. status_timeout (:term:`number`): Timeout in seconds, for waiting that the status of the partition has reached one of the desired status values. The special value 0 means that no timeout is set. `None` means that the default status timeout will be used. If the timeout expires, a :exc:`~zhmcclient.StatusTimeout` is raised. Raises: :exc:`~zhmcclient.HTTPError` :exc:`~zhmcclient.ParseError` :exc:`~zhmcclient.AuthError` :exc:`~zhmcclient.ConnectionError` :exc:`~zhmcclient.StatusTimeout`: The status timeout expired while waiting for the desired partition status. """ if status_timeout is None: status_timeout = \ self.manager.session.retry_timeout_config.status_timeout if status_timeout > 0: end_time = time.time() + status_timeout if isinstance(status, (list, tuple)): statuses = status else: statuses = [status] while True: # Fastest way to get actual status value: parts = self.manager.cpc.partitions.list( filter_args={'name': self.name}) assert len(parts) == 1 this_part = parts[0] actual_status = this_part.get_property('status') if actual_status in statuses: return if status_timeout > 0 and time.time() > end_time: raise StatusTimeout( "Waiting for partition {} to reach status(es) '{}' timed " "out after {} s - current status is '{}'". format(self.name, statuses, status_timeout, actual_status), actual_status, statuses, status_timeout) time.sleep(1)
python
def wait_for_status(self, status, status_timeout=None): if status_timeout is None: status_timeout = \ self.manager.session.retry_timeout_config.status_timeout if status_timeout > 0: end_time = time.time() + status_timeout if isinstance(status, (list, tuple)): statuses = status else: statuses = [status] while True: # Fastest way to get actual status value: parts = self.manager.cpc.partitions.list( filter_args={'name': self.name}) assert len(parts) == 1 this_part = parts[0] actual_status = this_part.get_property('status') if actual_status in statuses: return if status_timeout > 0 and time.time() > end_time: raise StatusTimeout( "Waiting for partition {} to reach status(es) '{}' timed " "out after {} s - current status is '{}'". format(self.name, statuses, status_timeout, actual_status), actual_status, statuses, status_timeout) time.sleep(1)
[ "def", "wait_for_status", "(", "self", ",", "status", ",", "status_timeout", "=", "None", ")", ":", "if", "status_timeout", "is", "None", ":", "status_timeout", "=", "self", ".", "manager", ".", "session", ".", "retry_timeout_config", ".", "status_timeout", "i...
Wait until the status of this partition has a desired value. Parameters: status (:term:`string` or iterable of :term:`string`): Desired partition status or set of status values to reach; one or more of the values defined for the 'status' property in the data model for partitions in the :term:`HMC API` book. status_timeout (:term:`number`): Timeout in seconds, for waiting that the status of the partition has reached one of the desired status values. The special value 0 means that no timeout is set. `None` means that the default status timeout will be used. If the timeout expires, a :exc:`~zhmcclient.StatusTimeout` is raised. Raises: :exc:`~zhmcclient.HTTPError` :exc:`~zhmcclient.ParseError` :exc:`~zhmcclient.AuthError` :exc:`~zhmcclient.ConnectionError` :exc:`~zhmcclient.StatusTimeout`: The status timeout expired while waiting for the desired partition status.
[ "Wait", "until", "the", "status", "of", "this", "partition", "has", "a", "desired", "value", "." ]
9657563e5d9184c51d3c903442a58b9725fdf335
https://github.com/zhmcclient/python-zhmcclient/blob/9657563e5d9184c51d3c903442a58b9725fdf335/zhmcclient/_partition.py#L834-L890
15,154
zhmcclient/python-zhmcclient
zhmcclient/_partition.py
Partition.change_crypto_domain_config
def change_crypto_domain_config(self, crypto_domain_index, access_mode): """ Change the access mode for a crypto domain that is currently included in the crypto configuration of this partition. The access mode will be changed for the specified crypto domain on all crypto adapters currently included in the crypto configuration of this partition. For the general principle for maintaining crypto configurations of partitions, see :meth:`~zhmcclient.Partition.increase_crypto_config`. Authorization requirements: * Object-access permission to this Partition. * Task permission to the "Partition Details" task. Parameters: crypto_domain_index (:term:`integer`): Domain index of the crypto domain to be changed. For values, see :meth:`~zhmcclient.Partition.increase_crypto_config`. access_mode (:term:`string`): The new access mode for the crypto domain. For values, see :meth:`~zhmcclient.Partition.increase_crypto_config`. Raises: :exc:`~zhmcclient.HTTPError` :exc:`~zhmcclient.ParseError` :exc:`~zhmcclient.AuthError` :exc:`~zhmcclient.ConnectionError` """ body = {'domain-index': crypto_domain_index, 'access-mode': access_mode} self.manager.session.post( self.uri + '/operations/change-crypto-domain-configuration', body)
python
def change_crypto_domain_config(self, crypto_domain_index, access_mode): body = {'domain-index': crypto_domain_index, 'access-mode': access_mode} self.manager.session.post( self.uri + '/operations/change-crypto-domain-configuration', body)
[ "def", "change_crypto_domain_config", "(", "self", ",", "crypto_domain_index", ",", "access_mode", ")", ":", "body", "=", "{", "'domain-index'", ":", "crypto_domain_index", ",", "'access-mode'", ":", "access_mode", "}", "self", ".", "manager", ".", "session", ".",...
Change the access mode for a crypto domain that is currently included in the crypto configuration of this partition. The access mode will be changed for the specified crypto domain on all crypto adapters currently included in the crypto configuration of this partition. For the general principle for maintaining crypto configurations of partitions, see :meth:`~zhmcclient.Partition.increase_crypto_config`. Authorization requirements: * Object-access permission to this Partition. * Task permission to the "Partition Details" task. Parameters: crypto_domain_index (:term:`integer`): Domain index of the crypto domain to be changed. For values, see :meth:`~zhmcclient.Partition.increase_crypto_config`. access_mode (:term:`string`): The new access mode for the crypto domain. For values, see :meth:`~zhmcclient.Partition.increase_crypto_config`. Raises: :exc:`~zhmcclient.HTTPError` :exc:`~zhmcclient.ParseError` :exc:`~zhmcclient.AuthError` :exc:`~zhmcclient.ConnectionError`
[ "Change", "the", "access", "mode", "for", "a", "crypto", "domain", "that", "is", "currently", "included", "in", "the", "crypto", "configuration", "of", "this", "partition", "." ]
9657563e5d9184c51d3c903442a58b9725fdf335
https://github.com/zhmcclient/python-zhmcclient/blob/9657563e5d9184c51d3c903442a58b9725fdf335/zhmcclient/_partition.py#L1012-L1049
15,155
zhmcclient/python-zhmcclient
zhmcclient/_partition.py
Partition.zeroize_crypto_domain
def zeroize_crypto_domain(self, crypto_adapter, crypto_domain_index): """ Zeroize a single crypto domain on a crypto adapter. Zeroizing a crypto domain clears the cryptographic keys and non-compliance mode settings in the crypto domain. The crypto domain must be attached to this partition in "control-usage" access mode. Supported CPC versions: z14 GA2 and above, and the corresponding LinuxOne systems. Authorization requirements: * Object-access permission to this Partition and to the Crypto Adapter. * Task permission to the "Zeroize Crypto Domain" task. Parameters: crypto_adapter (:class:`~zhmcclient.Adapter`): Crypto adapter with the crypto domain to be zeroized. crypto_domain_index (:term:`integer`): Domain index of the crypto domain to be zeroized. Raises: :exc:`~zhmcclient.HTTPError` :exc:`~zhmcclient.ParseError` :exc:`~zhmcclient.AuthError` :exc:`~zhmcclient.ConnectionError` """ body = { 'crypto-adapter-uri': crypto_adapter.uri, 'domain-index': crypto_domain_index } self.manager.session.post( self.uri + '/operations/zeroize-crypto-domain', body)
python
def zeroize_crypto_domain(self, crypto_adapter, crypto_domain_index): body = { 'crypto-adapter-uri': crypto_adapter.uri, 'domain-index': crypto_domain_index } self.manager.session.post( self.uri + '/operations/zeroize-crypto-domain', body)
[ "def", "zeroize_crypto_domain", "(", "self", ",", "crypto_adapter", ",", "crypto_domain_index", ")", ":", "body", "=", "{", "'crypto-adapter-uri'", ":", "crypto_adapter", ".", "uri", ",", "'domain-index'", ":", "crypto_domain_index", "}", "self", ".", "manager", "...
Zeroize a single crypto domain on a crypto adapter. Zeroizing a crypto domain clears the cryptographic keys and non-compliance mode settings in the crypto domain. The crypto domain must be attached to this partition in "control-usage" access mode. Supported CPC versions: z14 GA2 and above, and the corresponding LinuxOne systems. Authorization requirements: * Object-access permission to this Partition and to the Crypto Adapter. * Task permission to the "Zeroize Crypto Domain" task. Parameters: crypto_adapter (:class:`~zhmcclient.Adapter`): Crypto adapter with the crypto domain to be zeroized. crypto_domain_index (:term:`integer`): Domain index of the crypto domain to be zeroized. Raises: :exc:`~zhmcclient.HTTPError` :exc:`~zhmcclient.ParseError` :exc:`~zhmcclient.AuthError` :exc:`~zhmcclient.ConnectionError`
[ "Zeroize", "a", "single", "crypto", "domain", "on", "a", "crypto", "adapter", "." ]
9657563e5d9184c51d3c903442a58b9725fdf335
https://github.com/zhmcclient/python-zhmcclient/blob/9657563e5d9184c51d3c903442a58b9725fdf335/zhmcclient/_partition.py#L1052-L1090
15,156
zhmcclient/python-zhmcclient
zhmcclient/_partition.py
Partition.list_attached_storage_groups
def list_attached_storage_groups(self, full_properties=False): """ Return the storage groups that are attached to this partition. The CPC must have the "dpm-storage-management" feature enabled. Authorization requirements: * Object-access permission to this partition. * Task permission to the "Partition Details" task. Parameters: full_properties (bool): Controls that the full set of resource properties for each returned storage group is being retrieved, vs. only the following short set: "object-uri", "object-id", "class", "parent". TODO: Verify short list of properties. Returns: List of :class:`~zhmcclient.StorageGroup` objects representing the storage groups that are attached to this partition. Raises: :exc:`~zhmcclient.HTTPError` :exc:`~zhmcclient.ParseError` :exc:`~zhmcclient.AuthError` :exc:`~zhmcclient.ConnectionError` """ sg_list = [] sg_uris = self.get_property('storage-group-uris') if sg_uris: cpc = self.manager.cpc for sg_uri in sg_uris: sg = cpc.storage_groups.resource_object(sg_uri) sg_list.append(sg) if full_properties: sg.pull_full_properties() return sg_list
python
def list_attached_storage_groups(self, full_properties=False): sg_list = [] sg_uris = self.get_property('storage-group-uris') if sg_uris: cpc = self.manager.cpc for sg_uri in sg_uris: sg = cpc.storage_groups.resource_object(sg_uri) sg_list.append(sg) if full_properties: sg.pull_full_properties() return sg_list
[ "def", "list_attached_storage_groups", "(", "self", ",", "full_properties", "=", "False", ")", ":", "sg_list", "=", "[", "]", "sg_uris", "=", "self", ".", "get_property", "(", "'storage-group-uris'", ")", "if", "sg_uris", ":", "cpc", "=", "self", ".", "manag...
Return the storage groups that are attached to this partition. The CPC must have the "dpm-storage-management" feature enabled. Authorization requirements: * Object-access permission to this partition. * Task permission to the "Partition Details" task. Parameters: full_properties (bool): Controls that the full set of resource properties for each returned storage group is being retrieved, vs. only the following short set: "object-uri", "object-id", "class", "parent". TODO: Verify short list of properties. Returns: List of :class:`~zhmcclient.StorageGroup` objects representing the storage groups that are attached to this partition. Raises: :exc:`~zhmcclient.HTTPError` :exc:`~zhmcclient.ParseError` :exc:`~zhmcclient.AuthError` :exc:`~zhmcclient.ConnectionError`
[ "Return", "the", "storage", "groups", "that", "are", "attached", "to", "this", "partition", "." ]
9657563e5d9184c51d3c903442a58b9725fdf335
https://github.com/zhmcclient/python-zhmcclient/blob/9657563e5d9184c51d3c903442a58b9725fdf335/zhmcclient/_partition.py#L1170-L1211
15,157
zhmcclient/python-zhmcclient
zhmcclient/_password_rule.py
PasswordRule.update_properties
def update_properties(self, properties): """ Update writeable properties of this PasswordRule. The Password Rule must be user-defined. System-defined Password Rules cannot be updated. Authorization requirements: * Task permission to the "Manage Password Rules" task. Parameters: properties (dict): New values for the properties to be updated. Properties not to be updated are omitted. Allowable properties are the properties with qualifier (w) in section 'Data model' in section 'Password Rule object' in the :term:`HMC API` book. Raises: :exc:`~zhmcclient.HTTPError` :exc:`~zhmcclient.ParseError` :exc:`~zhmcclient.AuthError` :exc:`~zhmcclient.ConnectionError` """ self.manager.session.post(self.uri, body=properties) # The name of Password Rules cannot be updated. An attempt to do so # should cause HTTPError to be raised in the POST above, so we assert # that here, because we omit the extra code for handling name updates: assert self.manager._name_prop not in properties self.properties.update(copy.deepcopy(properties))
python
def update_properties(self, properties): self.manager.session.post(self.uri, body=properties) # The name of Password Rules cannot be updated. An attempt to do so # should cause HTTPError to be raised in the POST above, so we assert # that here, because we omit the extra code for handling name updates: assert self.manager._name_prop not in properties self.properties.update(copy.deepcopy(properties))
[ "def", "update_properties", "(", "self", ",", "properties", ")", ":", "self", ".", "manager", ".", "session", ".", "post", "(", "self", ".", "uri", ",", "body", "=", "properties", ")", "# The name of Password Rules cannot be updated. An attempt to do so", "# should ...
Update writeable properties of this PasswordRule. The Password Rule must be user-defined. System-defined Password Rules cannot be updated. Authorization requirements: * Task permission to the "Manage Password Rules" task. Parameters: properties (dict): New values for the properties to be updated. Properties not to be updated are omitted. Allowable properties are the properties with qualifier (w) in section 'Data model' in section 'Password Rule object' in the :term:`HMC API` book. Raises: :exc:`~zhmcclient.HTTPError` :exc:`~zhmcclient.ParseError` :exc:`~zhmcclient.AuthError` :exc:`~zhmcclient.ConnectionError`
[ "Update", "writeable", "properties", "of", "this", "PasswordRule", "." ]
9657563e5d9184c51d3c903442a58b9725fdf335
https://github.com/zhmcclient/python-zhmcclient/blob/9657563e5d9184c51d3c903442a58b9725fdf335/zhmcclient/_password_rule.py#L237-L269
15,158
zhmcclient/python-zhmcclient
zhmcclient/_client.py
Client.version_info
def version_info(self): """ Returns API version information for the HMC. This operation does not require authentication. Returns: :term:`HMC API version`: The HMC API version supported by the HMC. Raises: :exc:`~zhmcclient.HTTPError` :exc:`~zhmcclient.ParseError` :exc:`~zhmcclient.ConnectionError` """ if self._api_version is None: self.query_api_version() return self._api_version['api-major-version'],\ self._api_version['api-minor-version']
python
def version_info(self): if self._api_version is None: self.query_api_version() return self._api_version['api-major-version'],\ self._api_version['api-minor-version']
[ "def", "version_info", "(", "self", ")", ":", "if", "self", ".", "_api_version", "is", "None", ":", "self", ".", "query_api_version", "(", ")", "return", "self", ".", "_api_version", "[", "'api-major-version'", "]", ",", "self", ".", "_api_version", "[", "...
Returns API version information for the HMC. This operation does not require authentication. Returns: :term:`HMC API version`: The HMC API version supported by the HMC. Raises: :exc:`~zhmcclient.HTTPError` :exc:`~zhmcclient.ParseError` :exc:`~zhmcclient.ConnectionError`
[ "Returns", "API", "version", "information", "for", "the", "HMC", "." ]
9657563e5d9184c51d3c903442a58b9725fdf335
https://github.com/zhmcclient/python-zhmcclient/blob/9657563e5d9184c51d3c903442a58b9725fdf335/zhmcclient/_client.py#L88-L107
15,159
zhmcclient/python-zhmcclient
zhmcclient/_client.py
Client.query_api_version
def query_api_version(self): """ The Query API Version operation returns information about the level of Web Services API supported by the HMC. This operation does not require authentication. Returns: :term:`json object`: A JSON object with members ``api-major-version``, ``api-minor-version``, ``hmc-version`` and ``hmc-name``. For details about these properties, see section 'Response body contents' in section 'Query API Version' in the :term:`HMC API` book. Raises: :exc:`~zhmcclient.HTTPError` :exc:`~zhmcclient.ParseError` :exc:`~zhmcclient.ConnectionError` """ version_resp = self._session.get('/api/version', logon_required=False) self._api_version = version_resp return self._api_version
python
def query_api_version(self): version_resp = self._session.get('/api/version', logon_required=False) self._api_version = version_resp return self._api_version
[ "def", "query_api_version", "(", "self", ")", ":", "version_resp", "=", "self", ".", "_session", ".", "get", "(", "'/api/version'", ",", "logon_required", "=", "False", ")", "self", ".", "_api_version", "=", "version_resp", "return", "self", ".", "_api_version...
The Query API Version operation returns information about the level of Web Services API supported by the HMC. This operation does not require authentication. Returns: :term:`json object`: A JSON object with members ``api-major-version``, ``api-minor-version``, ``hmc-version`` and ``hmc-name``. For details about these properties, see section 'Response body contents' in section 'Query API Version' in the :term:`HMC API` book. Raises: :exc:`~zhmcclient.HTTPError` :exc:`~zhmcclient.ParseError` :exc:`~zhmcclient.ConnectionError`
[ "The", "Query", "API", "Version", "operation", "returns", "information", "about", "the", "level", "of", "Web", "Services", "API", "supported", "by", "the", "HMC", "." ]
9657563e5d9184c51d3c903442a58b9725fdf335
https://github.com/zhmcclient/python-zhmcclient/blob/9657563e5d9184c51d3c903442a58b9725fdf335/zhmcclient/_client.py#L110-L135
15,160
zhmcclient/python-zhmcclient
zhmcclient/_client.py
Client.get_inventory
def get_inventory(self, resources): """ Returns a JSON object with the requested resources and their properties, that are managed by the HMC. This method performs the 'Get Inventory' HMC operation. Parameters: resources (:term:`iterable` of :term:`string`): Resource classes and/or resource classifiers specifying the types of resources that should be included in the result. For valid values, see the 'Get Inventory' operation in the :term:`HMC API` book. Element resources of the specified resource types are automatically included as children (for example, requesting 'partition' includes all of its 'hba', 'nic' and 'virtual-function' element resources). Must not be `None`. Returns: :term:`JSON object`: The resources with their properties, for the requested resource classes and resource classifiers. Example: resource_classes = ['partition', 'adapter'] result_dict = client.get_inventory(resource_classes) Raises: :exc:`~zhmcclient.HTTPError` :exc:`~zhmcclient.ParseError` :exc:`~zhmcclient.ConnectionError` """ uri = '/api/services/inventory' body = {'resources': resources} result = self.session.post(uri, body=body) return result
python
def get_inventory(self, resources): uri = '/api/services/inventory' body = {'resources': resources} result = self.session.post(uri, body=body) return result
[ "def", "get_inventory", "(", "self", ",", "resources", ")", ":", "uri", "=", "'/api/services/inventory'", "body", "=", "{", "'resources'", ":", "resources", "}", "result", "=", "self", ".", "session", ".", "post", "(", "uri", ",", "body", "=", "body", ")...
Returns a JSON object with the requested resources and their properties, that are managed by the HMC. This method performs the 'Get Inventory' HMC operation. Parameters: resources (:term:`iterable` of :term:`string`): Resource classes and/or resource classifiers specifying the types of resources that should be included in the result. For valid values, see the 'Get Inventory' operation in the :term:`HMC API` book. Element resources of the specified resource types are automatically included as children (for example, requesting 'partition' includes all of its 'hba', 'nic' and 'virtual-function' element resources). Must not be `None`. Returns: :term:`JSON object`: The resources with their properties, for the requested resource classes and resource classifiers. Example: resource_classes = ['partition', 'adapter'] result_dict = client.get_inventory(resource_classes) Raises: :exc:`~zhmcclient.HTTPError` :exc:`~zhmcclient.ParseError` :exc:`~zhmcclient.ConnectionError`
[ "Returns", "a", "JSON", "object", "with", "the", "requested", "resources", "and", "their", "properties", "that", "are", "managed", "by", "the", "HMC", "." ]
9657563e5d9184c51d3c903442a58b9725fdf335
https://github.com/zhmcclient/python-zhmcclient/blob/9657563e5d9184c51d3c903442a58b9725fdf335/zhmcclient/_client.py#L138-L179
15,161
zhmcclient/python-zhmcclient
zhmcclient/_resource.py
BaseResource.pull_full_properties
def pull_full_properties(self): """ Retrieve the full set of resource properties and cache them in this object. Authorization requirements: * Object-access permission to this resource. Raises: :exc:`~zhmcclient.HTTPError` :exc:`~zhmcclient.ParseError` :exc:`~zhmcclient.AuthError` :exc:`~zhmcclient.ConnectionError` """ full_properties = self.manager.session.get(self._uri) self._properties = dict(full_properties) self._properties_timestamp = int(time.time()) self._full_properties = True
python
def pull_full_properties(self): full_properties = self.manager.session.get(self._uri) self._properties = dict(full_properties) self._properties_timestamp = int(time.time()) self._full_properties = True
[ "def", "pull_full_properties", "(", "self", ")", ":", "full_properties", "=", "self", ".", "manager", ".", "session", ".", "get", "(", "self", ".", "_uri", ")", "self", ".", "_properties", "=", "dict", "(", "full_properties", ")", "self", ".", "_properties...
Retrieve the full set of resource properties and cache them in this object. Authorization requirements: * Object-access permission to this resource. Raises: :exc:`~zhmcclient.HTTPError` :exc:`~zhmcclient.ParseError` :exc:`~zhmcclient.AuthError` :exc:`~zhmcclient.ConnectionError`
[ "Retrieve", "the", "full", "set", "of", "resource", "properties", "and", "cache", "them", "in", "this", "object", "." ]
9657563e5d9184c51d3c903442a58b9725fdf335
https://github.com/zhmcclient/python-zhmcclient/blob/9657563e5d9184c51d3c903442a58b9725fdf335/zhmcclient/_resource.py#L188-L207
15,162
zhmcclient/python-zhmcclient
zhmcclient/_resource.py
BaseResource.get_property
def get_property(self, name): """ Return the value of a resource property. If the resource property is not cached in this object yet, the full set of resource properties is retrieved and cached in this object, and the resource property is again attempted to be returned. Authorization requirements: * Object-access permission to this resource. Parameters: name (:term:`string`): Name of the resource property, using the names defined in the respective 'Data model' sections in the :term:`HMC API` book. Returns: The value of the resource property. Raises: KeyError: The resource property could not be found (also not in the full set of resource properties). :exc:`~zhmcclient.HTTPError` :exc:`~zhmcclient.ParseError` :exc:`~zhmcclient.AuthError` :exc:`~zhmcclient.ConnectionError` """ try: return self._properties[name] except KeyError: if self._full_properties: raise self.pull_full_properties() return self._properties[name]
python
def get_property(self, name): try: return self._properties[name] except KeyError: if self._full_properties: raise self.pull_full_properties() return self._properties[name]
[ "def", "get_property", "(", "self", ",", "name", ")", ":", "try", ":", "return", "self", ".", "_properties", "[", "name", "]", "except", "KeyError", ":", "if", "self", ".", "_full_properties", ":", "raise", "self", ".", "pull_full_properties", "(", ")", ...
Return the value of a resource property. If the resource property is not cached in this object yet, the full set of resource properties is retrieved and cached in this object, and the resource property is again attempted to be returned. Authorization requirements: * Object-access permission to this resource. Parameters: name (:term:`string`): Name of the resource property, using the names defined in the respective 'Data model' sections in the :term:`HMC API` book. Returns: The value of the resource property. Raises: KeyError: The resource property could not be found (also not in the full set of resource properties). :exc:`~zhmcclient.HTTPError` :exc:`~zhmcclient.ParseError` :exc:`~zhmcclient.AuthError` :exc:`~zhmcclient.ConnectionError`
[ "Return", "the", "value", "of", "a", "resource", "property", "." ]
9657563e5d9184c51d3c903442a58b9725fdf335
https://github.com/zhmcclient/python-zhmcclient/blob/9657563e5d9184c51d3c903442a58b9725fdf335/zhmcclient/_resource.py#L210-L247
15,163
zhmcclient/python-zhmcclient
docs/notebooks/tututils.py
make_client
def make_client(zhmc, userid=None, password=None): """ Create a `Session` object for the specified HMC and log that on. Create a `Client` object using that `Session` object, and return it. If no userid and password are specified, and if no previous call to this method was made, userid and password are interactively inquired. Userid and password are saved in module-global variables for future calls to this method. """ global USERID, PASSWORD # pylint: disable=global-statement USERID = userid or USERID or \ six.input('Enter userid for HMC {}: '.format(zhmc)) PASSWORD = password or PASSWORD or \ getpass.getpass('Enter password for {}: '.format(USERID)) session = zhmcclient.Session(zhmc, USERID, PASSWORD) session.logon() client = zhmcclient.Client(session) print('Established logged-on session with HMC {} using userid {}'. format(zhmc, USERID)) return client
python
def make_client(zhmc, userid=None, password=None): global USERID, PASSWORD # pylint: disable=global-statement USERID = userid or USERID or \ six.input('Enter userid for HMC {}: '.format(zhmc)) PASSWORD = password or PASSWORD or \ getpass.getpass('Enter password for {}: '.format(USERID)) session = zhmcclient.Session(zhmc, USERID, PASSWORD) session.logon() client = zhmcclient.Client(session) print('Established logged-on session with HMC {} using userid {}'. format(zhmc, USERID)) return client
[ "def", "make_client", "(", "zhmc", ",", "userid", "=", "None", ",", "password", "=", "None", ")", ":", "global", "USERID", ",", "PASSWORD", "# pylint: disable=global-statement", "USERID", "=", "userid", "or", "USERID", "or", "six", ".", "input", "(", "'Enter...
Create a `Session` object for the specified HMC and log that on. Create a `Client` object using that `Session` object, and return it. If no userid and password are specified, and if no previous call to this method was made, userid and password are interactively inquired. Userid and password are saved in module-global variables for future calls to this method.
[ "Create", "a", "Session", "object", "for", "the", "specified", "HMC", "and", "log", "that", "on", ".", "Create", "a", "Client", "object", "using", "that", "Session", "object", "and", "return", "it", "." ]
9657563e5d9184c51d3c903442a58b9725fdf335
https://github.com/zhmcclient/python-zhmcclient/blob/9657563e5d9184c51d3c903442a58b9725fdf335/docs/notebooks/tututils.py#L31-L54
15,164
zhmcclient/python-zhmcclient
zhmcclient/_utils.py
repr_list
def repr_list(_list, indent): """Return a debug representation of a list or tuple.""" # pprint represents lists and tuples in one row if possible. We want one # per row, so we iterate ourselves. if _list is None: return 'None' if isinstance(_list, MutableSequence): bm = '[' em = ']' elif isinstance(_list, Iterable): bm = '(' em = ')' else: raise TypeError("Object must be an iterable, but is a %s" % type(_list)) ret = bm + '\n' for value in _list: ret += _indent('%r,\n' % value, 2) ret += em ret = repr_text(ret, indent=indent) return ret.lstrip(' ')
python
def repr_list(_list, indent): # pprint represents lists and tuples in one row if possible. We want one # per row, so we iterate ourselves. if _list is None: return 'None' if isinstance(_list, MutableSequence): bm = '[' em = ']' elif isinstance(_list, Iterable): bm = '(' em = ')' else: raise TypeError("Object must be an iterable, but is a %s" % type(_list)) ret = bm + '\n' for value in _list: ret += _indent('%r,\n' % value, 2) ret += em ret = repr_text(ret, indent=indent) return ret.lstrip(' ')
[ "def", "repr_list", "(", "_list", ",", "indent", ")", ":", "# pprint represents lists and tuples in one row if possible. We want one", "# per row, so we iterate ourselves.", "if", "_list", "is", "None", ":", "return", "'None'", "if", "isinstance", "(", "_list", ",", "Muta...
Return a debug representation of a list or tuple.
[ "Return", "a", "debug", "representation", "of", "a", "list", "or", "tuple", "." ]
9657563e5d9184c51d3c903442a58b9725fdf335
https://github.com/zhmcclient/python-zhmcclient/blob/9657563e5d9184c51d3c903442a58b9725fdf335/zhmcclient/_utils.py#L48-L68
15,165
zhmcclient/python-zhmcclient
zhmcclient/_utils.py
repr_dict
def repr_dict(_dict, indent): """Return a debug representation of a dict or OrderedDict.""" # pprint represents OrderedDict objects using the tuple init syntax, # which is not very readable. Therefore, dictionaries are iterated over. if _dict is None: return 'None' if not isinstance(_dict, Mapping): raise TypeError("Object must be a mapping, but is a %s" % type(_dict)) if isinstance(_dict, OrderedDict): kind = 'ordered' ret = '%s {\n' % kind # non standard syntax for the kind indicator for key in six.iterkeys(_dict): value = _dict[key] ret += _indent('%r: %r,\n' % (key, value), 2) else: # dict kind = 'sorted' ret = '%s {\n' % kind # non standard syntax for the kind indicator for key in sorted(six.iterkeys(_dict)): value = _dict[key] ret += _indent('%r: %r,\n' % (key, value), 2) ret += '}' ret = repr_text(ret, indent=indent) return ret.lstrip(' ')
python
def repr_dict(_dict, indent): # pprint represents OrderedDict objects using the tuple init syntax, # which is not very readable. Therefore, dictionaries are iterated over. if _dict is None: return 'None' if not isinstance(_dict, Mapping): raise TypeError("Object must be a mapping, but is a %s" % type(_dict)) if isinstance(_dict, OrderedDict): kind = 'ordered' ret = '%s {\n' % kind # non standard syntax for the kind indicator for key in six.iterkeys(_dict): value = _dict[key] ret += _indent('%r: %r,\n' % (key, value), 2) else: # dict kind = 'sorted' ret = '%s {\n' % kind # non standard syntax for the kind indicator for key in sorted(six.iterkeys(_dict)): value = _dict[key] ret += _indent('%r: %r,\n' % (key, value), 2) ret += '}' ret = repr_text(ret, indent=indent) return ret.lstrip(' ')
[ "def", "repr_dict", "(", "_dict", ",", "indent", ")", ":", "# pprint represents OrderedDict objects using the tuple init syntax,", "# which is not very readable. Therefore, dictionaries are iterated over.", "if", "_dict", "is", "None", ":", "return", "'None'", "if", "not", "isi...
Return a debug representation of a dict or OrderedDict.
[ "Return", "a", "debug", "representation", "of", "a", "dict", "or", "OrderedDict", "." ]
9657563e5d9184c51d3c903442a58b9725fdf335
https://github.com/zhmcclient/python-zhmcclient/blob/9657563e5d9184c51d3c903442a58b9725fdf335/zhmcclient/_utils.py#L71-L94
15,166
zhmcclient/python-zhmcclient
zhmcclient/_utils.py
repr_timestamp
def repr_timestamp(timestamp): """Return a debug representation of an HMC timestamp number.""" if timestamp is None: return 'None' dt = datetime_from_timestamp(timestamp) ret = "%d (%s)" % (timestamp, dt.strftime('%Y-%m-%d %H:%M:%S.%f %Z')) return ret
python
def repr_timestamp(timestamp): if timestamp is None: return 'None' dt = datetime_from_timestamp(timestamp) ret = "%d (%s)" % (timestamp, dt.strftime('%Y-%m-%d %H:%M:%S.%f %Z')) return ret
[ "def", "repr_timestamp", "(", "timestamp", ")", ":", "if", "timestamp", "is", "None", ":", "return", "'None'", "dt", "=", "datetime_from_timestamp", "(", "timestamp", ")", "ret", "=", "\"%d (%s)\"", "%", "(", "timestamp", ",", "dt", ".", "strftime", "(", "...
Return a debug representation of an HMC timestamp number.
[ "Return", "a", "debug", "representation", "of", "an", "HMC", "timestamp", "number", "." ]
9657563e5d9184c51d3c903442a58b9725fdf335
https://github.com/zhmcclient/python-zhmcclient/blob/9657563e5d9184c51d3c903442a58b9725fdf335/zhmcclient/_utils.py#L97-L104
15,167
zhmcclient/python-zhmcclient
zhmcclient/_storage_group.py
StorageGroupManager.create
def create(self, properties): """ Create and configure a storage group. The new storage group will be associated with the CPC identified by the `cpc-uri` input property. Authorization requirements: * Object-access permission to the CPC that will be associated with the new storage group. * Task permission to the "Configure Storage - System Programmer" task. Parameters: properties (dict): Initial property values. Allowable properties are defined in section 'Request body contents' in section 'Create Storage Group' in the :term:`HMC API` book. The 'cpc-uri' property identifies the CPC to which the new storage group will be associated, and is required to be specified in this parameter. Returns: :class:`~zhmcclient.StorageGroup`: The resource object for the new storage group. The object will have its 'object-uri' property set as returned by the HMC, and will also have the input properties set. Raises: :exc:`~zhmcclient.HTTPError` :exc:`~zhmcclient.ParseError` :exc:`~zhmcclient.AuthError` :exc:`~zhmcclient.ConnectionError` """ if properties is None: properties = {} result = self.session.post(self._base_uri, body=properties) # There should not be overlaps, but just in case there are, the # returned props should overwrite the input props: props = copy.deepcopy(properties) props.update(result) name = props.get(self._name_prop, None) uri = props[self._uri_prop] storage_group = StorageGroup(self, uri, name, props) self._name_uri_cache.update(name, uri) return storage_group
python
def create(self, properties): if properties is None: properties = {} result = self.session.post(self._base_uri, body=properties) # There should not be overlaps, but just in case there are, the # returned props should overwrite the input props: props = copy.deepcopy(properties) props.update(result) name = props.get(self._name_prop, None) uri = props[self._uri_prop] storage_group = StorageGroup(self, uri, name, props) self._name_uri_cache.update(name, uri) return storage_group
[ "def", "create", "(", "self", ",", "properties", ")", ":", "if", "properties", "is", "None", ":", "properties", "=", "{", "}", "result", "=", "self", ".", "session", ".", "post", "(", "self", ".", "_base_uri", ",", "body", "=", "properties", ")", "# ...
Create and configure a storage group. The new storage group will be associated with the CPC identified by the `cpc-uri` input property. Authorization requirements: * Object-access permission to the CPC that will be associated with the new storage group. * Task permission to the "Configure Storage - System Programmer" task. Parameters: properties (dict): Initial property values. Allowable properties are defined in section 'Request body contents' in section 'Create Storage Group' in the :term:`HMC API` book. The 'cpc-uri' property identifies the CPC to which the new storage group will be associated, and is required to be specified in this parameter. Returns: :class:`~zhmcclient.StorageGroup`: The resource object for the new storage group. The object will have its 'object-uri' property set as returned by the HMC, and will also have the input properties set. Raises: :exc:`~zhmcclient.HTTPError` :exc:`~zhmcclient.ParseError` :exc:`~zhmcclient.AuthError` :exc:`~zhmcclient.ConnectionError`
[ "Create", "and", "configure", "a", "storage", "group", "." ]
9657563e5d9184c51d3c903442a58b9725fdf335
https://github.com/zhmcclient/python-zhmcclient/blob/9657563e5d9184c51d3c903442a58b9725fdf335/zhmcclient/_storage_group.py#L219-L268
15,168
zhmcclient/python-zhmcclient
zhmcclient/_storage_group.py
StorageGroup.list_attached_partitions
def list_attached_partitions(self, name=None, status=None): """ Return the partitions to which this storage group is currently attached, optionally filtered by partition name and status. Authorization requirements: * Object-access permission to this storage group. * Task permission to the "Configure Storage - System Programmer" task. Parameters: name (:term:`string`): Filter pattern (regular expression) to limit returned partitions to those that have a matching name. If `None`, no filtering for the partition name takes place. status (:term:`string`): Filter string to limit returned partitions to those that have a matching status. The value must be a valid partition status property value. If `None`, no filtering for the partition status takes place. Returns: List of :class:`~zhmcclient.Partition` objects representing the partitions to whivch this storage group is currently attached, with a minimal set of properties ('object-id', 'name', 'status'). Raises: :exc:`~zhmcclient.HTTPError` :exc:`~zhmcclient.ParseError` :exc:`~zhmcclient.AuthError` :exc:`~zhmcclient.ConnectionError` """ query_parms = [] if name is not None: self.manager._append_query_parms(query_parms, 'name', name) if status is not None: self.manager._append_query_parms(query_parms, 'status', status) query_parms_str = '&'.join(query_parms) if query_parms_str: query_parms_str = '?{}'.format(query_parms_str) uri = '{}/operations/get-partitions{}'.format( self.uri, query_parms_str) sg_cpc = self.cpc part_mgr = sg_cpc.partitions result = self.manager.session.get(uri) props_list = result['partitions'] part_list = [] for props in props_list: part = part_mgr.resource_object(props['object-uri'], props) part_list.append(part) return part_list
python
def list_attached_partitions(self, name=None, status=None): query_parms = [] if name is not None: self.manager._append_query_parms(query_parms, 'name', name) if status is not None: self.manager._append_query_parms(query_parms, 'status', status) query_parms_str = '&'.join(query_parms) if query_parms_str: query_parms_str = '?{}'.format(query_parms_str) uri = '{}/operations/get-partitions{}'.format( self.uri, query_parms_str) sg_cpc = self.cpc part_mgr = sg_cpc.partitions result = self.manager.session.get(uri) props_list = result['partitions'] part_list = [] for props in props_list: part = part_mgr.resource_object(props['object-uri'], props) part_list.append(part) return part_list
[ "def", "list_attached_partitions", "(", "self", ",", "name", "=", "None", ",", "status", "=", "None", ")", ":", "query_parms", "=", "[", "]", "if", "name", "is", "not", "None", ":", "self", ".", "manager", ".", "_append_query_parms", "(", "query_parms", ...
Return the partitions to which this storage group is currently attached, optionally filtered by partition name and status. Authorization requirements: * Object-access permission to this storage group. * Task permission to the "Configure Storage - System Programmer" task. Parameters: name (:term:`string`): Filter pattern (regular expression) to limit returned partitions to those that have a matching name. If `None`, no filtering for the partition name takes place. status (:term:`string`): Filter string to limit returned partitions to those that have a matching status. The value must be a valid partition status property value. If `None`, no filtering for the partition status takes place. Returns: List of :class:`~zhmcclient.Partition` objects representing the partitions to whivch this storage group is currently attached, with a minimal set of properties ('object-id', 'name', 'status'). Raises: :exc:`~zhmcclient.HTTPError` :exc:`~zhmcclient.ParseError` :exc:`~zhmcclient.AuthError` :exc:`~zhmcclient.ConnectionError`
[ "Return", "the", "partitions", "to", "which", "this", "storage", "group", "is", "currently", "attached", "optionally", "filtered", "by", "partition", "name", "and", "status", "." ]
9657563e5d9184c51d3c903442a58b9725fdf335
https://github.com/zhmcclient/python-zhmcclient/blob/9657563e5d9184c51d3c903442a58b9725fdf335/zhmcclient/_storage_group.py#L344-L400
15,169
zhmcclient/python-zhmcclient
zhmcclient/_storage_group.py
StorageGroup.add_candidate_adapter_ports
def add_candidate_adapter_ports(self, ports): """ Add a list of storage adapter ports to this storage group's candidate adapter ports list. This operation only applies to storage groups of type "fcp". These adapter ports become candidates for use as backing adapters when creating virtual storage resources when the storage group is attached to a partition. The adapter ports should have connectivity to the storage area network (SAN). Candidate adapter ports may only be added before the CPC discovers a working communications path, indicated by a "verified" status on at least one of this storage group's WWPNs. After that point, all adapter ports in the storage group are automatically detected and manually adding them is no longer possible. Because the CPC discovers working communications paths automatically, candidate adapter ports do not need to be added by the user. Any ports that are added, are validated by the CPC during discovery, and may or may not actually be used. Authorization requirements: * Object-access permission to this storage group. * Object-access permission to the adapter of each specified port. * Task permission to the "Configure Storage - System Programmer" task. Parameters: ports (:class:`py:list`): List of :class:`~zhmcclient.Port` objects representing the ports to be added. All specified ports must not already be members of this storage group's candidate adapter ports list. Raises: :exc:`~zhmcclient.HTTPError` :exc:`~zhmcclient.ParseError` :exc:`~zhmcclient.AuthError` :exc:`~zhmcclient.ConnectionError` """ body = { 'adapter-port-uris': [p.uri for p in ports], } self.manager.session.post( self.uri + '/operations/add-candidate-adapter-ports', body=body)
python
def add_candidate_adapter_ports(self, ports): body = { 'adapter-port-uris': [p.uri for p in ports], } self.manager.session.post( self.uri + '/operations/add-candidate-adapter-ports', body=body)
[ "def", "add_candidate_adapter_ports", "(", "self", ",", "ports", ")", ":", "body", "=", "{", "'adapter-port-uris'", ":", "[", "p", ".", "uri", "for", "p", "in", "ports", "]", ",", "}", "self", ".", "manager", ".", "session", ".", "post", "(", "self", ...
Add a list of storage adapter ports to this storage group's candidate adapter ports list. This operation only applies to storage groups of type "fcp". These adapter ports become candidates for use as backing adapters when creating virtual storage resources when the storage group is attached to a partition. The adapter ports should have connectivity to the storage area network (SAN). Candidate adapter ports may only be added before the CPC discovers a working communications path, indicated by a "verified" status on at least one of this storage group's WWPNs. After that point, all adapter ports in the storage group are automatically detected and manually adding them is no longer possible. Because the CPC discovers working communications paths automatically, candidate adapter ports do not need to be added by the user. Any ports that are added, are validated by the CPC during discovery, and may or may not actually be used. Authorization requirements: * Object-access permission to this storage group. * Object-access permission to the adapter of each specified port. * Task permission to the "Configure Storage - System Programmer" task. Parameters: ports (:class:`py:list`): List of :class:`~zhmcclient.Port` objects representing the ports to be added. All specified ports must not already be members of this storage group's candidate adapter ports list. Raises: :exc:`~zhmcclient.HTTPError` :exc:`~zhmcclient.ParseError` :exc:`~zhmcclient.AuthError` :exc:`~zhmcclient.ConnectionError`
[ "Add", "a", "list", "of", "storage", "adapter", "ports", "to", "this", "storage", "group", "s", "candidate", "adapter", "ports", "list", "." ]
9657563e5d9184c51d3c903442a58b9725fdf335
https://github.com/zhmcclient/python-zhmcclient/blob/9657563e5d9184c51d3c903442a58b9725fdf335/zhmcclient/_storage_group.py#L514-L562
15,170
zhmcclient/python-zhmcclient
zhmcclient/_storage_group.py
StorageGroup.list_candidate_adapter_ports
def list_candidate_adapter_ports(self, full_properties=False): """ Return the current candidate storage adapter port list of this storage group. The result reflects the actual list of ports used by the CPC, including any changes that have been made during discovery. The source for this information is the 'candidate-adapter-port-uris' property of the storage group object. Parameters: full_properties (bool): Controls that the full set of resource properties for each returned candidate storage adapter port is being retrieved, vs. only the following short set: "element-uri", "element-id", "class", "parent". TODO: Verify short list of properties. Returns: List of :class:`~zhmcclient.Port` objects representing the current candidate storage adapter ports of this storage group. Raises: :exc:`~zhmcclient.HTTPError` :exc:`~zhmcclient.ParseError` :exc:`~zhmcclient.AuthError` :exc:`~zhmcclient.ConnectionError` """ sg_cpc = self.cpc adapter_mgr = sg_cpc.adapters port_list = [] port_uris = self.get_property('candidate-adapter-port-uris') if port_uris: for port_uri in port_uris: m = re.match(r'^(/api/adapters/[^/]*)/.*', port_uri) adapter_uri = m.group(1) adapter = adapter_mgr.resource_object(adapter_uri) port_mgr = adapter.ports port = port_mgr.resource_object(port_uri) port_list.append(port) if full_properties: port.pull_full_properties() return port_list
python
def list_candidate_adapter_ports(self, full_properties=False): sg_cpc = self.cpc adapter_mgr = sg_cpc.adapters port_list = [] port_uris = self.get_property('candidate-adapter-port-uris') if port_uris: for port_uri in port_uris: m = re.match(r'^(/api/adapters/[^/]*)/.*', port_uri) adapter_uri = m.group(1) adapter = adapter_mgr.resource_object(adapter_uri) port_mgr = adapter.ports port = port_mgr.resource_object(port_uri) port_list.append(port) if full_properties: port.pull_full_properties() return port_list
[ "def", "list_candidate_adapter_ports", "(", "self", ",", "full_properties", "=", "False", ")", ":", "sg_cpc", "=", "self", ".", "cpc", "adapter_mgr", "=", "sg_cpc", ".", "adapters", "port_list", "=", "[", "]", "port_uris", "=", "self", ".", "get_property", "...
Return the current candidate storage adapter port list of this storage group. The result reflects the actual list of ports used by the CPC, including any changes that have been made during discovery. The source for this information is the 'candidate-adapter-port-uris' property of the storage group object. Parameters: full_properties (bool): Controls that the full set of resource properties for each returned candidate storage adapter port is being retrieved, vs. only the following short set: "element-uri", "element-id", "class", "parent". TODO: Verify short list of properties. Returns: List of :class:`~zhmcclient.Port` objects representing the current candidate storage adapter ports of this storage group. Raises: :exc:`~zhmcclient.HTTPError` :exc:`~zhmcclient.ParseError` :exc:`~zhmcclient.AuthError` :exc:`~zhmcclient.ConnectionError`
[ "Return", "the", "current", "candidate", "storage", "adapter", "port", "list", "of", "this", "storage", "group", "." ]
9657563e5d9184c51d3c903442a58b9725fdf335
https://github.com/zhmcclient/python-zhmcclient/blob/9657563e5d9184c51d3c903442a58b9725fdf335/zhmcclient/_storage_group.py#L606-L655
15,171
zhmcclient/python-zhmcclient
zhmcclient/_adapter.py
AdapterManager.create_hipersocket
def create_hipersocket(self, properties): """ Create and configure a HiperSockets Adapter in this CPC. Authorization requirements: * Object-access permission to the scoping CPC. * Task permission to the "Create HiperSockets Adapter" task. Parameters: properties (dict): Initial property values. Allowable properties are defined in section 'Request body contents' in section 'Create Hipersocket' in the :term:`HMC API` book. Returns: :class:`~zhmcclient.Adapter`: The resource object for the new HiperSockets Adapter. The object will have its 'object-uri' property set as returned by the HMC, and will also have the input properties set. Raises: :exc:`~zhmcclient.HTTPError` :exc:`~zhmcclient.ParseError` :exc:`~zhmcclient.AuthError` :exc:`~zhmcclient.ConnectionError` """ result = self.session.post(self.cpc.uri + '/adapters', body=properties) # There should not be overlaps, but just in case there are, the # returned props should overwrite the input props: props = copy.deepcopy(properties) props.update(result) name = props.get(self._name_prop, None) uri = props[self._uri_prop] adapter = Adapter(self, uri, name, props) self._name_uri_cache.update(name, uri) return adapter
python
def create_hipersocket(self, properties): result = self.session.post(self.cpc.uri + '/adapters', body=properties) # There should not be overlaps, but just in case there are, the # returned props should overwrite the input props: props = copy.deepcopy(properties) props.update(result) name = props.get(self._name_prop, None) uri = props[self._uri_prop] adapter = Adapter(self, uri, name, props) self._name_uri_cache.update(name, uri) return adapter
[ "def", "create_hipersocket", "(", "self", ",", "properties", ")", ":", "result", "=", "self", ".", "session", ".", "post", "(", "self", ".", "cpc", ".", "uri", "+", "'/adapters'", ",", "body", "=", "properties", ")", "# There should not be overlaps, but just i...
Create and configure a HiperSockets Adapter in this CPC. Authorization requirements: * Object-access permission to the scoping CPC. * Task permission to the "Create HiperSockets Adapter" task. Parameters: properties (dict): Initial property values. Allowable properties are defined in section 'Request body contents' in section 'Create Hipersocket' in the :term:`HMC API` book. Returns: :class:`~zhmcclient.Adapter`: The resource object for the new HiperSockets Adapter. The object will have its 'object-uri' property set as returned by the HMC, and will also have the input properties set. Raises: :exc:`~zhmcclient.HTTPError` :exc:`~zhmcclient.ParseError` :exc:`~zhmcclient.AuthError` :exc:`~zhmcclient.ConnectionError`
[ "Create", "and", "configure", "a", "HiperSockets", "Adapter", "in", "this", "CPC", "." ]
9657563e5d9184c51d3c903442a58b9725fdf335
https://github.com/zhmcclient/python-zhmcclient/blob/9657563e5d9184c51d3c903442a58b9725fdf335/zhmcclient/_adapter.py#L204-L242
15,172
zhmcclient/python-zhmcclient
zhmcclient/_adapter.py
Adapter.change_crypto_type
def change_crypto_type(self, crypto_type, zeroize=None): """ Reconfigures a cryptographic adapter to a different crypto type. This operation is only supported for cryptographic adapters. The cryptographic adapter must be varied offline before its crypto type can be reconfigured. Authorization requirements: * Object-access permission to this Adapter. * Task permission to the "Adapter Details" task. Parameters: crypto_type (:term:`string`): - ``"accelerator"``: Crypto Express5S Accelerator - ``"cca-coprocessor"``: Crypto Express5S CCA Coprocessor - ``"ep11-coprocessor"``: Crypto Express5S EP11 Coprocessor zeroize (bool): Specifies whether the cryptographic adapter will be zeroized when it is reconfigured to a crypto type of ``"accelerator"``. `None` means that the HMC-implemented default of `True` will be used. Raises: :exc:`~zhmcclient.HTTPError` :exc:`~zhmcclient.ParseError` :exc:`~zhmcclient.AuthError` :exc:`~zhmcclient.ConnectionError` """ body = {'crypto-type': crypto_type} if zeroize is not None: body['zeroize'] = zeroize self.manager.session.post( self.uri + '/operations/change-crypto-type', body)
python
def change_crypto_type(self, crypto_type, zeroize=None): body = {'crypto-type': crypto_type} if zeroize is not None: body['zeroize'] = zeroize self.manager.session.post( self.uri + '/operations/change-crypto-type', body)
[ "def", "change_crypto_type", "(", "self", ",", "crypto_type", ",", "zeroize", "=", "None", ")", ":", "body", "=", "{", "'crypto-type'", ":", "crypto_type", "}", "if", "zeroize", "is", "not", "None", ":", "body", "[", "'zeroize'", "]", "=", "zeroize", "se...
Reconfigures a cryptographic adapter to a different crypto type. This operation is only supported for cryptographic adapters. The cryptographic adapter must be varied offline before its crypto type can be reconfigured. Authorization requirements: * Object-access permission to this Adapter. * Task permission to the "Adapter Details" task. Parameters: crypto_type (:term:`string`): - ``"accelerator"``: Crypto Express5S Accelerator - ``"cca-coprocessor"``: Crypto Express5S CCA Coprocessor - ``"ep11-coprocessor"``: Crypto Express5S EP11 Coprocessor zeroize (bool): Specifies whether the cryptographic adapter will be zeroized when it is reconfigured to a crypto type of ``"accelerator"``. `None` means that the HMC-implemented default of `True` will be used. Raises: :exc:`~zhmcclient.HTTPError` :exc:`~zhmcclient.ParseError` :exc:`~zhmcclient.AuthError` :exc:`~zhmcclient.ConnectionError`
[ "Reconfigures", "a", "cryptographic", "adapter", "to", "a", "different", "crypto", "type", ".", "This", "operation", "is", "only", "supported", "for", "cryptographic", "adapters", "." ]
9657563e5d9184c51d3c903442a58b9725fdf335
https://github.com/zhmcclient/python-zhmcclient/blob/9657563e5d9184c51d3c903442a58b9725fdf335/zhmcclient/_adapter.py#L488-L525
15,173
zhmcclient/python-zhmcclient
zhmcclient/_lpar.py
Lpar.stop
def stop(self, wait_for_completion=True, operation_timeout=None, status_timeout=None, allow_status_exceptions=False): """ Stop this LPAR, using the HMC operation "Stop Logical Partition". The stop operation stops the processors from processing instructions. This HMC operation has deferred status behavior: If the asynchronous job on the HMC is complete, it takes a few seconds until the LPAR status has reached the desired value. If `wait_for_completion=True`, this method repeatedly checks the status of the LPAR after the HMC operation has completed, and waits until the status is in the desired state "operating", or if `allow_status_exceptions` was set additionally in the state "exceptions". Authorization requirements: * Object-access permission to the CPC containing this LPAR. * Object-access permission to this LPAR. * Task permission for the "Stop" task. Parameters: wait_for_completion (bool): Boolean controlling whether this method should wait for completion of the requested asynchronous HMC operation, as follows: * If `True`, this method will wait for completion of the asynchronous job performing the operation, and for the status becoming "operating" (or in addition "exceptions", if `allow_status_exceptions` was set. * If `False`, this method will return immediately once the HMC has accepted the request to perform the operation. operation_timeout (:term:`number`): Timeout in seconds, for waiting for completion of the asynchronous job performing the operation. The special value 0 means that no timeout is set. `None` means that the default async operation timeout of the session is used. If the timeout expires when `wait_for_completion=True`, a :exc:`~zhmcclient.OperationTimeout` is raised. status_timeout (:term:`number`): Timeout in seconds, for waiting that the status of the LPAR has reached the desired status, after the HMC operation has completed. The special value 0 means that no timeout is set. `None` means that the default async operation timeout of the session is used. If the timeout expires when `wait_for_completion=True`, a :exc:`~zhmcclient.StatusTimeout` is raised. allow_status_exceptions (bool): Boolean controlling whether LPAR status "exceptions" is considered an additional acceptable end status when `wait_for_completion` is set. Returns: `None` or :class:`~zhmcclient.Job`: If `wait_for_completion` is `True`, returns `None`. If `wait_for_completion` is `False`, returns a :class:`~zhmcclient.Job` object representing the asynchronously executing job on the HMC. Raises: :exc:`~zhmcclient.HTTPError` :exc:`~zhmcclient.ParseError` :exc:`~zhmcclient.AuthError` :exc:`~zhmcclient.ConnectionError` :exc:`~zhmcclient.OperationTimeout`: The timeout expired while waiting for completion of the operation. :exc:`~zhmcclient.StatusTimeout`: The timeout expired while waiting for the desired LPAR status. """ body = {} result = self.manager.session.post( self.uri + '/operations/stop', body, wait_for_completion=wait_for_completion, operation_timeout=operation_timeout) if wait_for_completion: statuses = ["operating"] if allow_status_exceptions: statuses.append("exceptions") self.wait_for_status(statuses, status_timeout) return result
python
def stop(self, wait_for_completion=True, operation_timeout=None, status_timeout=None, allow_status_exceptions=False): body = {} result = self.manager.session.post( self.uri + '/operations/stop', body, wait_for_completion=wait_for_completion, operation_timeout=operation_timeout) if wait_for_completion: statuses = ["operating"] if allow_status_exceptions: statuses.append("exceptions") self.wait_for_status(statuses, status_timeout) return result
[ "def", "stop", "(", "self", ",", "wait_for_completion", "=", "True", ",", "operation_timeout", "=", "None", ",", "status_timeout", "=", "None", ",", "allow_status_exceptions", "=", "False", ")", ":", "body", "=", "{", "}", "result", "=", "self", ".", "mana...
Stop this LPAR, using the HMC operation "Stop Logical Partition". The stop operation stops the processors from processing instructions. This HMC operation has deferred status behavior: If the asynchronous job on the HMC is complete, it takes a few seconds until the LPAR status has reached the desired value. If `wait_for_completion=True`, this method repeatedly checks the status of the LPAR after the HMC operation has completed, and waits until the status is in the desired state "operating", or if `allow_status_exceptions` was set additionally in the state "exceptions". Authorization requirements: * Object-access permission to the CPC containing this LPAR. * Object-access permission to this LPAR. * Task permission for the "Stop" task. Parameters: wait_for_completion (bool): Boolean controlling whether this method should wait for completion of the requested asynchronous HMC operation, as follows: * If `True`, this method will wait for completion of the asynchronous job performing the operation, and for the status becoming "operating" (or in addition "exceptions", if `allow_status_exceptions` was set. * If `False`, this method will return immediately once the HMC has accepted the request to perform the operation. operation_timeout (:term:`number`): Timeout in seconds, for waiting for completion of the asynchronous job performing the operation. The special value 0 means that no timeout is set. `None` means that the default async operation timeout of the session is used. If the timeout expires when `wait_for_completion=True`, a :exc:`~zhmcclient.OperationTimeout` is raised. status_timeout (:term:`number`): Timeout in seconds, for waiting that the status of the LPAR has reached the desired status, after the HMC operation has completed. The special value 0 means that no timeout is set. `None` means that the default async operation timeout of the session is used. If the timeout expires when `wait_for_completion=True`, a :exc:`~zhmcclient.StatusTimeout` is raised. allow_status_exceptions (bool): Boolean controlling whether LPAR status "exceptions" is considered an additional acceptable end status when `wait_for_completion` is set. Returns: `None` or :class:`~zhmcclient.Job`: If `wait_for_completion` is `True`, returns `None`. If `wait_for_completion` is `False`, returns a :class:`~zhmcclient.Job` object representing the asynchronously executing job on the HMC. Raises: :exc:`~zhmcclient.HTTPError` :exc:`~zhmcclient.ParseError` :exc:`~zhmcclient.AuthError` :exc:`~zhmcclient.ConnectionError` :exc:`~zhmcclient.OperationTimeout`: The timeout expired while waiting for completion of the operation. :exc:`~zhmcclient.StatusTimeout`: The timeout expired while waiting for the desired LPAR status.
[ "Stop", "this", "LPAR", "using", "the", "HMC", "operation", "Stop", "Logical", "Partition", ".", "The", "stop", "operation", "stops", "the", "processors", "from", "processing", "instructions", "." ]
9657563e5d9184c51d3c903442a58b9725fdf335
https://github.com/zhmcclient/python-zhmcclient/blob/9657563e5d9184c51d3c903442a58b9725fdf335/zhmcclient/_lpar.py#L698-L786
15,174
zhmcclient/python-zhmcclient
zhmcclient/_session.py
_result_object
def _result_object(result): """ Return the JSON payload in the HTTP response as a Python dict. Parameters: result (requests.Response): HTTP response object. Raises: zhmcclient.ParseError: Error parsing the returned JSON. """ content_type = result.headers.get('content-type', None) if content_type is None or content_type.startswith('application/json'): # This function is only called when there is content expected. # Therefore, a response without content will result in a ParseError. try: return result.json(object_pairs_hook=OrderedDict) except ValueError as exc: raise ParseError( "JSON parse error in HTTP response: {}. " "HTTP request: {} {}. " "Response status {}. " "Response content-type: {!r}. " "Content (max.1000, decoded using {}): {}". format(exc.args[0], result.request.method, result.request.url, result.status_code, content_type, result.encoding, _text_repr(result.text, 1000))) elif content_type.startswith('text/html'): # We are in some error situation. The HMC returns HTML content # for some 5xx status codes. We try to deal with it somehow, # but we are not going as far as real HTML parsing. m = re.search(r'charset=([^;,]+)', content_type) if m: encoding = m.group(1) # e.g. RFC "ISO-8859-1" else: encoding = 'utf-8' try: html_uni = result.content.decode(encoding) except LookupError: html_uni = result.content.decode() # We convert to one line to be regexp-friendly. html_oneline = html_uni.replace('\r\n', '\\n').replace('\r', '\\n').\ replace('\n', '\\n') # Check for some well-known errors: if re.search(r'javax\.servlet\.ServletException: ' r'Web Services are not enabled\.', html_oneline): html_title = "Console Configuration Error" html_details = "Web Services API is not enabled on the HMC." html_reason = HTML_REASON_WEB_SERVICES_DISABLED else: m = re.search( r'<title>([^<]*)</title>.*' r'<h2>Details:</h2>(.*)(<hr size="1" noshade>)?</body>', html_oneline) if m: html_title = m.group(1) # Spend a reasonable effort to make the HTML readable: html_details = m.group(2).replace('<p>', '\\n').\ replace('<br>', '\\n').replace('\\n\\n', '\\n').strip() else: html_title = "Console Internal Error" html_details = "Response body: {!r}".format(html_uni) html_reason = HTML_REASON_OTHER message = "{}: {}".format(html_title, html_details) # We create a minimal JSON error object (to the extent we use it # when processing it): result_obj = { 'http-status': result.status_code, 'reason': html_reason, 'message': message, 'request-uri': result.request.url, 'request-method': result.request.method, } return result_obj elif content_type.startswith('application/vnd.ibm-z-zmanager-metrics'): content_bytes = result.content assert isinstance(content_bytes, six.binary_type) return content_bytes.decode('utf-8') # as a unicode object else: raise ParseError( "Unknown content type in HTTP response: {}. " "HTTP request: {} {}. " "Response status {}. " "Response content-type: {!r}. " "Content (max.1000, decoded using {}): {}". format(content_type, result.request.method, result.request.url, result.status_code, content_type, result.encoding, _text_repr(result.text, 1000)))
python
def _result_object(result): content_type = result.headers.get('content-type', None) if content_type is None or content_type.startswith('application/json'): # This function is only called when there is content expected. # Therefore, a response without content will result in a ParseError. try: return result.json(object_pairs_hook=OrderedDict) except ValueError as exc: raise ParseError( "JSON parse error in HTTP response: {}. " "HTTP request: {} {}. " "Response status {}. " "Response content-type: {!r}. " "Content (max.1000, decoded using {}): {}". format(exc.args[0], result.request.method, result.request.url, result.status_code, content_type, result.encoding, _text_repr(result.text, 1000))) elif content_type.startswith('text/html'): # We are in some error situation. The HMC returns HTML content # for some 5xx status codes. We try to deal with it somehow, # but we are not going as far as real HTML parsing. m = re.search(r'charset=([^;,]+)', content_type) if m: encoding = m.group(1) # e.g. RFC "ISO-8859-1" else: encoding = 'utf-8' try: html_uni = result.content.decode(encoding) except LookupError: html_uni = result.content.decode() # We convert to one line to be regexp-friendly. html_oneline = html_uni.replace('\r\n', '\\n').replace('\r', '\\n').\ replace('\n', '\\n') # Check for some well-known errors: if re.search(r'javax\.servlet\.ServletException: ' r'Web Services are not enabled\.', html_oneline): html_title = "Console Configuration Error" html_details = "Web Services API is not enabled on the HMC." html_reason = HTML_REASON_WEB_SERVICES_DISABLED else: m = re.search( r'<title>([^<]*)</title>.*' r'<h2>Details:</h2>(.*)(<hr size="1" noshade>)?</body>', html_oneline) if m: html_title = m.group(1) # Spend a reasonable effort to make the HTML readable: html_details = m.group(2).replace('<p>', '\\n').\ replace('<br>', '\\n').replace('\\n\\n', '\\n').strip() else: html_title = "Console Internal Error" html_details = "Response body: {!r}".format(html_uni) html_reason = HTML_REASON_OTHER message = "{}: {}".format(html_title, html_details) # We create a minimal JSON error object (to the extent we use it # when processing it): result_obj = { 'http-status': result.status_code, 'reason': html_reason, 'message': message, 'request-uri': result.request.url, 'request-method': result.request.method, } return result_obj elif content_type.startswith('application/vnd.ibm-z-zmanager-metrics'): content_bytes = result.content assert isinstance(content_bytes, six.binary_type) return content_bytes.decode('utf-8') # as a unicode object else: raise ParseError( "Unknown content type in HTTP response: {}. " "HTTP request: {} {}. " "Response status {}. " "Response content-type: {!r}. " "Content (max.1000, decoded using {}): {}". format(content_type, result.request.method, result.request.url, result.status_code, content_type, result.encoding, _text_repr(result.text, 1000)))
[ "def", "_result_object", "(", "result", ")", ":", "content_type", "=", "result", ".", "headers", ".", "get", "(", "'content-type'", ",", "None", ")", "if", "content_type", "is", "None", "or", "content_type", ".", "startswith", "(", "'application/json'", ")", ...
Return the JSON payload in the HTTP response as a Python dict. Parameters: result (requests.Response): HTTP response object. Raises: zhmcclient.ParseError: Error parsing the returned JSON.
[ "Return", "the", "JSON", "payload", "in", "the", "HTTP", "response", "as", "a", "Python", "dict", "." ]
9657563e5d9184c51d3c903442a58b9725fdf335
https://github.com/zhmcclient/python-zhmcclient/blob/9657563e5d9184c51d3c903442a58b9725fdf335/zhmcclient/_session.py#L1313-L1405
15,175
zhmcclient/python-zhmcclient
zhmcclient/_session.py
RetryTimeoutConfig.override_with
def override_with(self, override_config): """ Return a new configuration object that represents the configuration from this configuration object acting as a default, and the specified configuration object overriding that default. Parameters: override_config (:class:`~zhmcclient.RetryTimeoutConfig`): The configuration object overriding the defaults defined in this configuration object. Returns: :class:`~zhmcclient.RetryTimeoutConfig`: A new configuration object representing this configuration object, overridden by the specified configuration object. """ ret = RetryTimeoutConfig() for attr in RetryTimeoutConfig._attrs: value = getattr(self, attr) if override_config and getattr(override_config, attr) is not None: value = getattr(override_config, attr) setattr(ret, attr, value) return ret
python
def override_with(self, override_config): ret = RetryTimeoutConfig() for attr in RetryTimeoutConfig._attrs: value = getattr(self, attr) if override_config and getattr(override_config, attr) is not None: value = getattr(override_config, attr) setattr(ret, attr, value) return ret
[ "def", "override_with", "(", "self", ",", "override_config", ")", ":", "ret", "=", "RetryTimeoutConfig", "(", ")", "for", "attr", "in", "RetryTimeoutConfig", ".", "_attrs", ":", "value", "=", "getattr", "(", "self", ",", "attr", ")", "if", "override_config",...
Return a new configuration object that represents the configuration from this configuration object acting as a default, and the specified configuration object overriding that default. Parameters: override_config (:class:`~zhmcclient.RetryTimeoutConfig`): The configuration object overriding the defaults defined in this configuration object. Returns: :class:`~zhmcclient.RetryTimeoutConfig`: A new configuration object representing this configuration object, overridden by the specified configuration object.
[ "Return", "a", "new", "configuration", "object", "that", "represents", "the", "configuration", "from", "this", "configuration", "object", "acting", "as", "a", "default", "and", "the", "specified", "configuration", "object", "overriding", "that", "default", "." ]
9657563e5d9184c51d3c903442a58b9725fdf335
https://github.com/zhmcclient/python-zhmcclient/blob/9657563e5d9184c51d3c903442a58b9725fdf335/zhmcclient/_session.py#L192-L216
15,176
zhmcclient/python-zhmcclient
zhmcclient/_session.py
Session.is_logon
def is_logon(self, verify=False): """ Return a boolean indicating whether the session is currently logged on to the HMC. By default, this method checks whether there is a session-id set and considers that sufficient for determining that the session is logged on. The `verify` parameter can be used to verify the validity of a session-id that is already set, by issuing a dummy operation ("Get Console Properties") to the HMC. Parameters: verify (bool): If a session-id is already set, verify its validity. """ if self._session_id is None: return False if verify: try: self.get('/api/console', logon_required=True) except ServerAuthError: return False return True
python
def is_logon(self, verify=False): if self._session_id is None: return False if verify: try: self.get('/api/console', logon_required=True) except ServerAuthError: return False return True
[ "def", "is_logon", "(", "self", ",", "verify", "=", "False", ")", ":", "if", "self", ".", "_session_id", "is", "None", ":", "return", "False", "if", "verify", ":", "try", ":", "self", ".", "get", "(", "'/api/console'", ",", "logon_required", "=", "True...
Return a boolean indicating whether the session is currently logged on to the HMC. By default, this method checks whether there is a session-id set and considers that sufficient for determining that the session is logged on. The `verify` parameter can be used to verify the validity of a session-id that is already set, by issuing a dummy operation ("Get Console Properties") to the HMC. Parameters: verify (bool): If a session-id is already set, verify its validity.
[ "Return", "a", "boolean", "indicating", "whether", "the", "session", "is", "currently", "logged", "on", "to", "the", "HMC", "." ]
9657563e5d9184c51d3c903442a58b9725fdf335
https://github.com/zhmcclient/python-zhmcclient/blob/9657563e5d9184c51d3c903442a58b9725fdf335/zhmcclient/_session.py#L542-L564
15,177
zhmcclient/python-zhmcclient
zhmcclient/_session.py
Session._do_logon
def _do_logon(self): """ Log on, unconditionally. This can be used to re-logon. This requires credentials to be provided. Raises: :exc:`~zhmcclient.ClientAuthError` :exc:`~zhmcclient.ServerAuthError` :exc:`~zhmcclient.ConnectionError` :exc:`~zhmcclient.ParseError` :exc:`~zhmcclient.HTTPError` """ if self._userid is None: raise ClientAuthError("Userid is not provided.") if self._password is None: if self._get_password: self._password = self._get_password(self._host, self._userid) else: raise ClientAuthError("Password is not provided.") logon_uri = '/api/sessions' logon_body = { 'userid': self._userid, 'password': self._password } self._headers.pop('X-API-Session', None) # Just in case self._session = self._new_session(self.retry_timeout_config) logon_res = self.post(logon_uri, logon_body, logon_required=False) self._session_id = logon_res['api-session'] self._headers['X-API-Session'] = self._session_id
python
def _do_logon(self): if self._userid is None: raise ClientAuthError("Userid is not provided.") if self._password is None: if self._get_password: self._password = self._get_password(self._host, self._userid) else: raise ClientAuthError("Password is not provided.") logon_uri = '/api/sessions' logon_body = { 'userid': self._userid, 'password': self._password } self._headers.pop('X-API-Session', None) # Just in case self._session = self._new_session(self.retry_timeout_config) logon_res = self.post(logon_uri, logon_body, logon_required=False) self._session_id = logon_res['api-session'] self._headers['X-API-Session'] = self._session_id
[ "def", "_do_logon", "(", "self", ")", ":", "if", "self", ".", "_userid", "is", "None", ":", "raise", "ClientAuthError", "(", "\"Userid is not provided.\"", ")", "if", "self", ".", "_password", "is", "None", ":", "if", "self", ".", "_get_password", ":", "se...
Log on, unconditionally. This can be used to re-logon. This requires credentials to be provided. Raises: :exc:`~zhmcclient.ClientAuthError` :exc:`~zhmcclient.ServerAuthError` :exc:`~zhmcclient.ConnectionError` :exc:`~zhmcclient.ParseError` :exc:`~zhmcclient.HTTPError`
[ "Log", "on", "unconditionally", ".", "This", "can", "be", "used", "to", "re", "-", "logon", ".", "This", "requires", "credentials", "to", "be", "provided", "." ]
9657563e5d9184c51d3c903442a58b9725fdf335
https://github.com/zhmcclient/python-zhmcclient/blob/9657563e5d9184c51d3c903442a58b9725fdf335/zhmcclient/_session.py#L566-L595
15,178
zhmcclient/python-zhmcclient
zhmcclient/_session.py
Session._new_session
def _new_session(retry_timeout_config): """ Return a new `requests.Session` object. """ retry = requests.packages.urllib3.Retry( total=None, connect=retry_timeout_config.connect_retries, read=retry_timeout_config.read_retries, method_whitelist=retry_timeout_config.method_whitelist, redirect=retry_timeout_config.max_redirects) session = requests.Session() session.mount('https://', requests.adapters.HTTPAdapter(max_retries=retry)) session.mount('http://', requests.adapters.HTTPAdapter(max_retries=retry)) return session
python
def _new_session(retry_timeout_config): retry = requests.packages.urllib3.Retry( total=None, connect=retry_timeout_config.connect_retries, read=retry_timeout_config.read_retries, method_whitelist=retry_timeout_config.method_whitelist, redirect=retry_timeout_config.max_redirects) session = requests.Session() session.mount('https://', requests.adapters.HTTPAdapter(max_retries=retry)) session.mount('http://', requests.adapters.HTTPAdapter(max_retries=retry)) return session
[ "def", "_new_session", "(", "retry_timeout_config", ")", ":", "retry", "=", "requests", ".", "packages", ".", "urllib3", ".", "Retry", "(", "total", "=", "None", ",", "connect", "=", "retry_timeout_config", ".", "connect_retries", ",", "read", "=", "retry_time...
Return a new `requests.Session` object.
[ "Return", "a", "new", "requests", ".", "Session", "object", "." ]
9657563e5d9184c51d3c903442a58b9725fdf335
https://github.com/zhmcclient/python-zhmcclient/blob/9657563e5d9184c51d3c903442a58b9725fdf335/zhmcclient/_session.py#L598-L613
15,179
zhmcclient/python-zhmcclient
zhmcclient/_session.py
Session._do_logoff
def _do_logoff(self): """ Log off, unconditionally. Raises: :exc:`~zhmcclient.ServerAuthError` :exc:`~zhmcclient.ConnectionError` :exc:`~zhmcclient.ParseError` :exc:`~zhmcclient.HTTPError` """ session_uri = '/api/sessions/this-session' self.delete(session_uri, logon_required=False) self._session_id = None self._session = None self._headers.pop('X-API-Session', None)
python
def _do_logoff(self): session_uri = '/api/sessions/this-session' self.delete(session_uri, logon_required=False) self._session_id = None self._session = None self._headers.pop('X-API-Session', None)
[ "def", "_do_logoff", "(", "self", ")", ":", "session_uri", "=", "'/api/sessions/this-session'", "self", ".", "delete", "(", "session_uri", ",", "logon_required", "=", "False", ")", "self", ".", "_session_id", "=", "None", "self", ".", "_session", "=", "None", ...
Log off, unconditionally. Raises: :exc:`~zhmcclient.ServerAuthError` :exc:`~zhmcclient.ConnectionError` :exc:`~zhmcclient.ParseError` :exc:`~zhmcclient.HTTPError`
[ "Log", "off", "unconditionally", "." ]
9657563e5d9184c51d3c903442a58b9725fdf335
https://github.com/zhmcclient/python-zhmcclient/blob/9657563e5d9184c51d3c903442a58b9725fdf335/zhmcclient/_session.py#L615-L630
15,180
zhmcclient/python-zhmcclient
zhmcclient/_session.py
Session._log_http_request
def _log_http_request(method, url, headers=None, content=None): """ Log the HTTP request of an HMC REST API call, at the debug level. Parameters: method (:term:`string`): HTTP method name in upper case, e.g. 'GET' url (:term:`string`): HTTP URL (base URL and operation URI) headers (iterable): HTTP headers used for the request content (:term:`string`): HTTP body (aka content) used for the request """ if method == 'POST' and url.endswith('/api/sessions'): # In Python 3 up to 3.5, json.loads() requires unicode strings. if sys.version_info[0] == 3 and sys.version_info[1] in (4, 5) and \ isinstance(content, six.binary_type): content = content.decode('utf-8') # Because zhmcclient has built the request, we are not handling # any JSON parse errors from json.loads(). content_dict = json.loads(content) content_dict['password'] = '********' content = json.dumps(content_dict) if headers and 'X-API-Session' in headers: headers = headers.copy() headers['X-API-Session'] = '********' HMC_LOGGER.debug("Request: %s %s, headers: %r, " "content(max.1000): %.1000r", method, url, headers, content)
python
def _log_http_request(method, url, headers=None, content=None): if method == 'POST' and url.endswith('/api/sessions'): # In Python 3 up to 3.5, json.loads() requires unicode strings. if sys.version_info[0] == 3 and sys.version_info[1] in (4, 5) and \ isinstance(content, six.binary_type): content = content.decode('utf-8') # Because zhmcclient has built the request, we are not handling # any JSON parse errors from json.loads(). content_dict = json.loads(content) content_dict['password'] = '********' content = json.dumps(content_dict) if headers and 'X-API-Session' in headers: headers = headers.copy() headers['X-API-Session'] = '********' HMC_LOGGER.debug("Request: %s %s, headers: %r, " "content(max.1000): %.1000r", method, url, headers, content)
[ "def", "_log_http_request", "(", "method", ",", "url", ",", "headers", "=", "None", ",", "content", "=", "None", ")", ":", "if", "method", "==", "'POST'", "and", "url", ".", "endswith", "(", "'/api/sessions'", ")", ":", "# In Python 3 up to 3.5, json.loads() r...
Log the HTTP request of an HMC REST API call, at the debug level. Parameters: method (:term:`string`): HTTP method name in upper case, e.g. 'GET' url (:term:`string`): HTTP URL (base URL and operation URI) headers (iterable): HTTP headers used for the request content (:term:`string`): HTTP body (aka content) used for the request
[ "Log", "the", "HTTP", "request", "of", "an", "HMC", "REST", "API", "call", "at", "the", "debug", "level", "." ]
9657563e5d9184c51d3c903442a58b9725fdf335
https://github.com/zhmcclient/python-zhmcclient/blob/9657563e5d9184c51d3c903442a58b9725fdf335/zhmcclient/_session.py#L633-L663
15,181
zhmcclient/python-zhmcclient
zhmcclient/_session.py
Session._log_http_response
def _log_http_response(method, url, status, headers=None, content=None): """ Log the HTTP response of an HMC REST API call, at the debug level. Parameters: method (:term:`string`): HTTP method name in upper case, e.g. 'GET' url (:term:`string`): HTTP URL (base URL and operation URI) status (integer): HTTP status code headers (iterable): HTTP headers returned in the response content (:term:`string`): HTTP body (aka content) returned in the response """ if method == 'POST' and url.endswith('/api/sessions'): # In Python 3 up to 3.5, json.loads() requires unicode strings. if sys.version_info[0] == 3 and sys.version_info[1] in (4, 5) and \ isinstance(content, six.binary_type): content = content.decode('utf-8') try: content_dict = json.loads(content) except ValueError as exc: content = '"Error: Cannot parse JSON payload of response: ' \ '{}"'.format(exc) else: content_dict['api-session'] = '********' content_dict['session-credential'] = '********' content = json.dumps(content_dict) if headers and 'X-API-Session' in headers: headers = headers.copy() headers['X-API-Session'] = '********' HMC_LOGGER.debug("Respons: %s %s, status: %s, headers: %r, " "content(max.1000): %.1000r", method, url, status, headers, content)
python
def _log_http_response(method, url, status, headers=None, content=None): if method == 'POST' and url.endswith('/api/sessions'): # In Python 3 up to 3.5, json.loads() requires unicode strings. if sys.version_info[0] == 3 and sys.version_info[1] in (4, 5) and \ isinstance(content, six.binary_type): content = content.decode('utf-8') try: content_dict = json.loads(content) except ValueError as exc: content = '"Error: Cannot parse JSON payload of response: ' \ '{}"'.format(exc) else: content_dict['api-session'] = '********' content_dict['session-credential'] = '********' content = json.dumps(content_dict) if headers and 'X-API-Session' in headers: headers = headers.copy() headers['X-API-Session'] = '********' HMC_LOGGER.debug("Respons: %s %s, status: %s, headers: %r, " "content(max.1000): %.1000r", method, url, status, headers, content)
[ "def", "_log_http_response", "(", "method", ",", "url", ",", "status", ",", "headers", "=", "None", ",", "content", "=", "None", ")", ":", "if", "method", "==", "'POST'", "and", "url", ".", "endswith", "(", "'/api/sessions'", ")", ":", "# In Python 3 up to...
Log the HTTP response of an HMC REST API call, at the debug level. Parameters: method (:term:`string`): HTTP method name in upper case, e.g. 'GET' url (:term:`string`): HTTP URL (base URL and operation URI) status (integer): HTTP status code headers (iterable): HTTP headers returned in the response content (:term:`string`): HTTP body (aka content) returned in the response
[ "Log", "the", "HTTP", "response", "of", "an", "HMC", "REST", "API", "call", "at", "the", "debug", "level", "." ]
9657563e5d9184c51d3c903442a58b9725fdf335
https://github.com/zhmcclient/python-zhmcclient/blob/9657563e5d9184c51d3c903442a58b9725fdf335/zhmcclient/_session.py#L666-L702
15,182
zhmcclient/python-zhmcclient
zhmcclient/_session.py
Session.delete
def delete(self, uri, logon_required=True): """ Perform the HTTP DELETE method against the resource identified by a URI. A set of standard HTTP headers is automatically part of the request. If the HMC session token is expired, this method re-logs on and retries the operation. Parameters: uri (:term:`string`): Relative URI path of the resource, e.g. "/api/session/{session-id}". This URI is relative to the base URL of the session (see the :attr:`~zhmcclient.Session.base_url` property). Must not be `None`. logon_required (bool): Boolean indicating whether the operation requires that the session is logged on to the HMC. For example, for the logoff operation, it does not make sense to first log on. Raises: :exc:`~zhmcclient.HTTPError` :exc:`~zhmcclient.ParseError` :exc:`~zhmcclient.ClientAuthError` :exc:`~zhmcclient.ServerAuthError` :exc:`~zhmcclient.ConnectionError` """ if logon_required: self.logon() url = self.base_url + uri self._log_http_request('DELETE', url, headers=self.headers) stats = self.time_stats_keeper.get_stats('delete ' + uri) stats.begin() req = self._session or requests req_timeout = (self.retry_timeout_config.connect_timeout, self.retry_timeout_config.read_timeout) try: result = req.delete(url, headers=self.headers, verify=False, timeout=req_timeout) except requests.exceptions.RequestException as exc: _handle_request_exc(exc, self.retry_timeout_config) finally: stats.end() self._log_http_response('DELETE', url, status=result.status_code, headers=result.headers, content=result.content) if result.status_code in (200, 204): return elif result.status_code == 403: result_object = _result_object(result) reason = result_object.get('reason', None) if reason == 5: # API session token expired: re-logon and retry self._do_logon() self.delete(uri, logon_required) return else: msg = result_object.get('message', None) raise ServerAuthError("HTTP authentication failed: {}". format(msg), HTTPError(result_object)) else: result_object = _result_object(result) raise HTTPError(result_object)
python
def delete(self, uri, logon_required=True): if logon_required: self.logon() url = self.base_url + uri self._log_http_request('DELETE', url, headers=self.headers) stats = self.time_stats_keeper.get_stats('delete ' + uri) stats.begin() req = self._session or requests req_timeout = (self.retry_timeout_config.connect_timeout, self.retry_timeout_config.read_timeout) try: result = req.delete(url, headers=self.headers, verify=False, timeout=req_timeout) except requests.exceptions.RequestException as exc: _handle_request_exc(exc, self.retry_timeout_config) finally: stats.end() self._log_http_response('DELETE', url, status=result.status_code, headers=result.headers, content=result.content) if result.status_code in (200, 204): return elif result.status_code == 403: result_object = _result_object(result) reason = result_object.get('reason', None) if reason == 5: # API session token expired: re-logon and retry self._do_logon() self.delete(uri, logon_required) return else: msg = result_object.get('message', None) raise ServerAuthError("HTTP authentication failed: {}". format(msg), HTTPError(result_object)) else: result_object = _result_object(result) raise HTTPError(result_object)
[ "def", "delete", "(", "self", ",", "uri", ",", "logon_required", "=", "True", ")", ":", "if", "logon_required", ":", "self", ".", "logon", "(", ")", "url", "=", "self", ".", "base_url", "+", "uri", "self", ".", "_log_http_request", "(", "'DELETE'", ","...
Perform the HTTP DELETE method against the resource identified by a URI. A set of standard HTTP headers is automatically part of the request. If the HMC session token is expired, this method re-logs on and retries the operation. Parameters: uri (:term:`string`): Relative URI path of the resource, e.g. "/api/session/{session-id}". This URI is relative to the base URL of the session (see the :attr:`~zhmcclient.Session.base_url` property). Must not be `None`. logon_required (bool): Boolean indicating whether the operation requires that the session is logged on to the HMC. For example, for the logoff operation, it does not make sense to first log on. Raises: :exc:`~zhmcclient.HTTPError` :exc:`~zhmcclient.ParseError` :exc:`~zhmcclient.ClientAuthError` :exc:`~zhmcclient.ServerAuthError` :exc:`~zhmcclient.ConnectionError`
[ "Perform", "the", "HTTP", "DELETE", "method", "against", "the", "resource", "identified", "by", "a", "URI", "." ]
9657563e5d9184c51d3c903442a58b9725fdf335
https://github.com/zhmcclient/python-zhmcclient/blob/9657563e5d9184c51d3c903442a58b9725fdf335/zhmcclient/_session.py#L982-L1051
15,183
zhmcclient/python-zhmcclient
zhmcclient/_session.py
Job.check_for_completion
def check_for_completion(self): """ Check once for completion of the job and return completion status and result if it has completed. If the job completed in error, an :exc:`~zhmcclient.HTTPError` exception is raised. Returns: : A tuple (status, result) with: * status (:term:`string`): Completion status of the job, as returned in the ``status`` field of the response body of the "Query Job Status" HMC operation, as follows: * ``"complete"``: Job completed (successfully). * any other value: Job is not yet complete. * result (:term:`json object` or `None`): `None` for incomplete jobs. For completed jobs, the result of the original asynchronous operation that was performed by the job, from the ``job-results`` field of the response body of the "Query Job Status" HMC operation. That result is a :term:`json object` as described for the asynchronous operation, or `None` if the operation has no result. Raises: :exc:`~zhmcclient.HTTPError`: The job completed in error, or the job status cannot be retrieved, or the job cannot be deleted. :exc:`~zhmcclient.ParseError` :exc:`~zhmcclient.ClientAuthError` :exc:`~zhmcclient.ServerAuthError` :exc:`~zhmcclient.ConnectionError` """ job_result_obj = self.session.get(self.uri) job_status = job_result_obj['status'] if job_status == 'complete': self.session.delete(self.uri) op_status_code = job_result_obj['job-status-code'] if op_status_code in (200, 201): op_result_obj = job_result_obj.get('job-results', None) elif op_status_code == 204: # No content op_result_obj = None else: error_result_obj = job_result_obj.get('job-results', None) if not error_result_obj: message = None elif 'message' in error_result_obj: message = error_result_obj['message'] elif 'error' in error_result_obj: message = error_result_obj['error'] else: message = None error_obj = { 'http-status': op_status_code, 'reason': job_result_obj['job-reason-code'], 'message': message, 'request-method': self.op_method, 'request-uri': self.op_uri, } raise HTTPError(error_obj) else: op_result_obj = None return job_status, op_result_obj
python
def check_for_completion(self): job_result_obj = self.session.get(self.uri) job_status = job_result_obj['status'] if job_status == 'complete': self.session.delete(self.uri) op_status_code = job_result_obj['job-status-code'] if op_status_code in (200, 201): op_result_obj = job_result_obj.get('job-results', None) elif op_status_code == 204: # No content op_result_obj = None else: error_result_obj = job_result_obj.get('job-results', None) if not error_result_obj: message = None elif 'message' in error_result_obj: message = error_result_obj['message'] elif 'error' in error_result_obj: message = error_result_obj['error'] else: message = None error_obj = { 'http-status': op_status_code, 'reason': job_result_obj['job-reason-code'], 'message': message, 'request-method': self.op_method, 'request-uri': self.op_uri, } raise HTTPError(error_obj) else: op_result_obj = None return job_status, op_result_obj
[ "def", "check_for_completion", "(", "self", ")", ":", "job_result_obj", "=", "self", ".", "session", ".", "get", "(", "self", ".", "uri", ")", "job_status", "=", "job_result_obj", "[", "'status'", "]", "if", "job_status", "==", "'complete'", ":", "self", "...
Check once for completion of the job and return completion status and result if it has completed. If the job completed in error, an :exc:`~zhmcclient.HTTPError` exception is raised. Returns: : A tuple (status, result) with: * status (:term:`string`): Completion status of the job, as returned in the ``status`` field of the response body of the "Query Job Status" HMC operation, as follows: * ``"complete"``: Job completed (successfully). * any other value: Job is not yet complete. * result (:term:`json object` or `None`): `None` for incomplete jobs. For completed jobs, the result of the original asynchronous operation that was performed by the job, from the ``job-results`` field of the response body of the "Query Job Status" HMC operation. That result is a :term:`json object` as described for the asynchronous operation, or `None` if the operation has no result. Raises: :exc:`~zhmcclient.HTTPError`: The job completed in error, or the job status cannot be retrieved, or the job cannot be deleted. :exc:`~zhmcclient.ParseError` :exc:`~zhmcclient.ClientAuthError` :exc:`~zhmcclient.ServerAuthError` :exc:`~zhmcclient.ConnectionError`
[ "Check", "once", "for", "completion", "of", "the", "job", "and", "return", "completion", "status", "and", "result", "if", "it", "has", "completed", "." ]
9657563e5d9184c51d3c903442a58b9725fdf335
https://github.com/zhmcclient/python-zhmcclient/blob/9657563e5d9184c51d3c903442a58b9725fdf335/zhmcclient/_session.py#L1159-L1225
15,184
zhmcclient/python-zhmcclient
zhmcclient/_session.py
Job.wait_for_completion
def wait_for_completion(self, operation_timeout=None): """ Wait for completion of the job, then delete the job on the HMC and return the result of the original asynchronous HMC operation, if it completed successfully. If the job completed in error, an :exc:`~zhmcclient.HTTPError` exception is raised. Parameters: operation_timeout (:term:`number`): Timeout in seconds, when waiting for completion of the job. The special value 0 means that no timeout is set. `None` means that the default async operation timeout of the session is used. If the timeout expires, a :exc:`~zhmcclient.OperationTimeout` is raised. This method gives completion of the job priority over strictly achieving the timeout. This may cause a slightly longer duration of the method than prescribed by the timeout. Returns: :term:`json object` or `None`: The result of the original asynchronous operation that was performed by the job, from the ``job-results`` field of the response body of the "Query Job Status" HMC operation. That result is a :term:`json object` as described for the asynchronous operation, or `None` if the operation has no result. Raises: :exc:`~zhmcclient.HTTPError`: The job completed in error, or the job status cannot be retrieved, or the job cannot be deleted. :exc:`~zhmcclient.ParseError` :exc:`~zhmcclient.ClientAuthError` :exc:`~zhmcclient.ServerAuthError` :exc:`~zhmcclient.ConnectionError` :exc:`~zhmcclient.OperationTimeout`: The timeout expired while waiting for job completion. """ if operation_timeout is None: operation_timeout = \ self.session.retry_timeout_config.operation_timeout if operation_timeout > 0: start_time = time.time() while True: job_status, op_result_obj = self.check_for_completion() # We give completion of status priority over strictly achieving # the timeout, so we check status first. This may cause a longer # duration of the method than prescribed by the timeout. if job_status == 'complete': return op_result_obj if operation_timeout > 0: current_time = time.time() if current_time > start_time + operation_timeout: raise OperationTimeout( "Waiting for completion of job {} timed out " "(operation timeout: {} s)". format(self.uri, operation_timeout), operation_timeout) time.sleep(1)
python
def wait_for_completion(self, operation_timeout=None): if operation_timeout is None: operation_timeout = \ self.session.retry_timeout_config.operation_timeout if operation_timeout > 0: start_time = time.time() while True: job_status, op_result_obj = self.check_for_completion() # We give completion of status priority over strictly achieving # the timeout, so we check status first. This may cause a longer # duration of the method than prescribed by the timeout. if job_status == 'complete': return op_result_obj if operation_timeout > 0: current_time = time.time() if current_time > start_time + operation_timeout: raise OperationTimeout( "Waiting for completion of job {} timed out " "(operation timeout: {} s)". format(self.uri, operation_timeout), operation_timeout) time.sleep(1)
[ "def", "wait_for_completion", "(", "self", ",", "operation_timeout", "=", "None", ")", ":", "if", "operation_timeout", "is", "None", ":", "operation_timeout", "=", "self", ".", "session", ".", "retry_timeout_config", ".", "operation_timeout", "if", "operation_timeou...
Wait for completion of the job, then delete the job on the HMC and return the result of the original asynchronous HMC operation, if it completed successfully. If the job completed in error, an :exc:`~zhmcclient.HTTPError` exception is raised. Parameters: operation_timeout (:term:`number`): Timeout in seconds, when waiting for completion of the job. The special value 0 means that no timeout is set. `None` means that the default async operation timeout of the session is used. If the timeout expires, a :exc:`~zhmcclient.OperationTimeout` is raised. This method gives completion of the job priority over strictly achieving the timeout. This may cause a slightly longer duration of the method than prescribed by the timeout. Returns: :term:`json object` or `None`: The result of the original asynchronous operation that was performed by the job, from the ``job-results`` field of the response body of the "Query Job Status" HMC operation. That result is a :term:`json object` as described for the asynchronous operation, or `None` if the operation has no result. Raises: :exc:`~zhmcclient.HTTPError`: The job completed in error, or the job status cannot be retrieved, or the job cannot be deleted. :exc:`~zhmcclient.ParseError` :exc:`~zhmcclient.ClientAuthError` :exc:`~zhmcclient.ServerAuthError` :exc:`~zhmcclient.ConnectionError` :exc:`~zhmcclient.OperationTimeout`: The timeout expired while waiting for job completion.
[ "Wait", "for", "completion", "of", "the", "job", "then", "delete", "the", "job", "on", "the", "HMC", "and", "return", "the", "result", "of", "the", "original", "asynchronous", "HMC", "operation", "if", "it", "completed", "successfully", "." ]
9657563e5d9184c51d3c903442a58b9725fdf335
https://github.com/zhmcclient/python-zhmcclient/blob/9657563e5d9184c51d3c903442a58b9725fdf335/zhmcclient/_session.py#L1228-L1296
15,185
zhmcclient/python-zhmcclient
zhmcclient/_logging.py
logged_api_call
def logged_api_call(func): """ Function decorator that causes the decorated API function or method to log calls to itself to a logger. The logger's name is the dotted module name of the module defining the decorated function (e.g. 'zhmcclient._cpc'). Parameters: func (function object): The original function being decorated. Returns: function object: The function wrappering the original function being decorated. Raises: TypeError: The @logged_api_call decorator must be used on a function or method (and not on top of the @property decorator). """ # Note that in this decorator function, we are in a module loading context, # where the decorated functions are being defined. When this decorator # function is called, its call stack represents the definition of the # decorated functions. Not all global definitions in the module have been # defined yet, and methods of classes that are decorated with this # decorator are still functions at this point (and not yet methods). module = inspect.getmodule(func) if not inspect.isfunction(func) or not hasattr(module, '__name__'): raise TypeError("The @logged_api_call decorator must be used on a " "function or method (and not on top of the @property " "decorator)") try: # We avoid the use of inspect.getouterframes() because it is slow, # and use the pointers up the stack frame, instead. this_frame = inspect.currentframe() # this decorator function here apifunc_frame = this_frame.f_back # the decorated API function apifunc_owner = inspect.getframeinfo(apifunc_frame)[2] finally: # Recommended way to deal with frame objects to avoid ref cycles del this_frame del apifunc_frame # TODO: For inner functions, show all outer levels instead of just one. if apifunc_owner == '<module>': # The decorated API function is defined globally (at module level) apifunc_str = '{func}()'.format(func=func.__name__) else: # The decorated API function is defined in a class or in a function apifunc_str = '{owner}.{func}()'.format(owner=apifunc_owner, func=func.__name__) logger = get_logger(API_LOGGER_NAME) def is_external_call(): """ Return a boolean indicating whether the call to the decorated API function is an external call (vs. b eing an internal call). """ try: # We avoid the use of inspect.getouterframes() because it is slow, # and use the pointers up the stack frame, instead. log_it_frame = inspect.currentframe() # this log_it() function log_api_call_frame = log_it_frame.f_back # the log_api_call() func apifunc_frame = log_api_call_frame.f_back # the decorated API func apicaller_frame = apifunc_frame.f_back # caller of API function apicaller_module = inspect.getmodule(apicaller_frame) if apicaller_module is None: apicaller_module_name = "<unknown>" else: apicaller_module_name = apicaller_module.__name__ finally: # Recommended way to deal with frame objects to avoid ref cycles del log_it_frame del log_api_call_frame del apifunc_frame del apicaller_frame del apicaller_module # Log only if the caller is not from the zhmcclient package return apicaller_module_name.split('.')[0] != 'zhmcclient' def log_api_call(func, *args, **kwargs): """ Log entry to and exit from the decorated function, at the debug level. Note that this wrapper function is called every time the decorated function/method is called, but that the log message only needs to be constructed when logging for this logger and for this log level is turned on. Therefore, we do as much as possible in the decorator function, plus we use %-formatting and lazy interpolation provided by the log functions, in order to save resources in this function here. Parameters: func (function object): The decorated function. *args: Any positional arguments for the decorated function. **kwargs: Any keyword arguments for the decorated function. """ # Note that in this function, we are in the context where the # decorated function is actually called. _log_it = is_external_call() and logger.isEnabledFor(logging.DEBUG) if _log_it: logger.debug("Called: {}, args: {:.500}, kwargs: {:.500}". format(apifunc_str, log_escaped(repr(args)), log_escaped(repr(kwargs)))) result = func(*args, **kwargs) if _log_it: logger.debug("Return: {}, result: {:.1000}". format(apifunc_str, log_escaped(repr(result)))) return result if 'decorate' in globals(): return decorate(func, log_api_call) else: return decorator(log_api_call, func)
python
def logged_api_call(func): # Note that in this decorator function, we are in a module loading context, # where the decorated functions are being defined. When this decorator # function is called, its call stack represents the definition of the # decorated functions. Not all global definitions in the module have been # defined yet, and methods of classes that are decorated with this # decorator are still functions at this point (and not yet methods). module = inspect.getmodule(func) if not inspect.isfunction(func) or not hasattr(module, '__name__'): raise TypeError("The @logged_api_call decorator must be used on a " "function or method (and not on top of the @property " "decorator)") try: # We avoid the use of inspect.getouterframes() because it is slow, # and use the pointers up the stack frame, instead. this_frame = inspect.currentframe() # this decorator function here apifunc_frame = this_frame.f_back # the decorated API function apifunc_owner = inspect.getframeinfo(apifunc_frame)[2] finally: # Recommended way to deal with frame objects to avoid ref cycles del this_frame del apifunc_frame # TODO: For inner functions, show all outer levels instead of just one. if apifunc_owner == '<module>': # The decorated API function is defined globally (at module level) apifunc_str = '{func}()'.format(func=func.__name__) else: # The decorated API function is defined in a class or in a function apifunc_str = '{owner}.{func}()'.format(owner=apifunc_owner, func=func.__name__) logger = get_logger(API_LOGGER_NAME) def is_external_call(): """ Return a boolean indicating whether the call to the decorated API function is an external call (vs. b eing an internal call). """ try: # We avoid the use of inspect.getouterframes() because it is slow, # and use the pointers up the stack frame, instead. log_it_frame = inspect.currentframe() # this log_it() function log_api_call_frame = log_it_frame.f_back # the log_api_call() func apifunc_frame = log_api_call_frame.f_back # the decorated API func apicaller_frame = apifunc_frame.f_back # caller of API function apicaller_module = inspect.getmodule(apicaller_frame) if apicaller_module is None: apicaller_module_name = "<unknown>" else: apicaller_module_name = apicaller_module.__name__ finally: # Recommended way to deal with frame objects to avoid ref cycles del log_it_frame del log_api_call_frame del apifunc_frame del apicaller_frame del apicaller_module # Log only if the caller is not from the zhmcclient package return apicaller_module_name.split('.')[0] != 'zhmcclient' def log_api_call(func, *args, **kwargs): """ Log entry to and exit from the decorated function, at the debug level. Note that this wrapper function is called every time the decorated function/method is called, but that the log message only needs to be constructed when logging for this logger and for this log level is turned on. Therefore, we do as much as possible in the decorator function, plus we use %-formatting and lazy interpolation provided by the log functions, in order to save resources in this function here. Parameters: func (function object): The decorated function. *args: Any positional arguments for the decorated function. **kwargs: Any keyword arguments for the decorated function. """ # Note that in this function, we are in the context where the # decorated function is actually called. _log_it = is_external_call() and logger.isEnabledFor(logging.DEBUG) if _log_it: logger.debug("Called: {}, args: {:.500}, kwargs: {:.500}". format(apifunc_str, log_escaped(repr(args)), log_escaped(repr(kwargs)))) result = func(*args, **kwargs) if _log_it: logger.debug("Return: {}, result: {:.1000}". format(apifunc_str, log_escaped(repr(result)))) return result if 'decorate' in globals(): return decorate(func, log_api_call) else: return decorator(log_api_call, func)
[ "def", "logged_api_call", "(", "func", ")", ":", "# Note that in this decorator function, we are in a module loading context,", "# where the decorated functions are being defined. When this decorator", "# function is called, its call stack represents the definition of the", "# decorated functions....
Function decorator that causes the decorated API function or method to log calls to itself to a logger. The logger's name is the dotted module name of the module defining the decorated function (e.g. 'zhmcclient._cpc'). Parameters: func (function object): The original function being decorated. Returns: function object: The function wrappering the original function being decorated. Raises: TypeError: The @logged_api_call decorator must be used on a function or method (and not on top of the @property decorator).
[ "Function", "decorator", "that", "causes", "the", "decorated", "API", "function", "or", "method", "to", "log", "calls", "to", "itself", "to", "a", "logger", "." ]
9657563e5d9184c51d3c903442a58b9725fdf335
https://github.com/zhmcclient/python-zhmcclient/blob/9657563e5d9184c51d3c903442a58b9725fdf335/zhmcclient/_logging.py#L102-L234
15,186
honeybadger-io/honeybadger-python
examples/flask/app.py
generic_div
def generic_div(a, b): """Simple function to divide two numbers""" logger.debug('Called generic_div({}, {})'.format(a, b)) return a / b
python
def generic_div(a, b): logger.debug('Called generic_div({}, {})'.format(a, b)) return a / b
[ "def", "generic_div", "(", "a", ",", "b", ")", ":", "logger", ".", "debug", "(", "'Called generic_div({}, {})'", ".", "format", "(", "a", ",", "b", ")", ")", "return", "a", "/", "b" ]
Simple function to divide two numbers
[ "Simple", "function", "to", "divide", "two", "numbers" ]
81519b40d3e446b62035f64e34900e08ff91938c
https://github.com/honeybadger-io/honeybadger-python/blob/81519b40d3e446b62035f64e34900e08ff91938c/examples/flask/app.py#L9-L12
15,187
honeybadger-io/honeybadger-python
examples/django_app/app/views.py
buggy_div
def buggy_div(request): """ A buggy endpoint to perform division between query parameters a and b. It will fail if b is equal to 0 or either a or b are not float. :param request: request object :return: """ a = float(request.GET.get('a', '0')) b = float(request.GET.get('b', '0')) return JsonResponse({'result': a / b})
python
def buggy_div(request): a = float(request.GET.get('a', '0')) b = float(request.GET.get('b', '0')) return JsonResponse({'result': a / b})
[ "def", "buggy_div", "(", "request", ")", ":", "a", "=", "float", "(", "request", ".", "GET", ".", "get", "(", "'a'", ",", "'0'", ")", ")", "b", "=", "float", "(", "request", ".", "GET", ".", "get", "(", "'b'", ",", "'0'", ")", ")", "return", ...
A buggy endpoint to perform division between query parameters a and b. It will fail if b is equal to 0 or either a or b are not float. :param request: request object :return:
[ "A", "buggy", "endpoint", "to", "perform", "division", "between", "query", "parameters", "a", "and", "b", ".", "It", "will", "fail", "if", "b", "is", "equal", "to", "0", "or", "either", "a", "or", "b", "are", "not", "float", "." ]
81519b40d3e446b62035f64e34900e08ff91938c
https://github.com/honeybadger-io/honeybadger-python/blob/81519b40d3e446b62035f64e34900e08ff91938c/examples/django_app/app/views.py#L14-L24
15,188
SwissDataScienceCenter/renku-python
renku/cli/_format/graph.py
ascii
def ascii(graph): """Format graph as an ASCII art.""" from .._ascii import DAG from .._echo import echo_via_pager echo_via_pager(str(DAG(graph)))
python
def ascii(graph): from .._ascii import DAG from .._echo import echo_via_pager echo_via_pager(str(DAG(graph)))
[ "def", "ascii", "(", "graph", ")", ":", "from", ".", ".", "_ascii", "import", "DAG", "from", ".", ".", "_echo", "import", "echo_via_pager", "echo_via_pager", "(", "str", "(", "DAG", "(", "graph", ")", ")", ")" ]
Format graph as an ASCII art.
[ "Format", "graph", "as", "an", "ASCII", "art", "." ]
691644d695b055a01e0ca22b2620e55bbd928c0d
https://github.com/SwissDataScienceCenter/renku-python/blob/691644d695b055a01e0ca22b2620e55bbd928c0d/renku/cli/_format/graph.py#L25-L30
15,189
SwissDataScienceCenter/renku-python
renku/cli/_format/graph.py
_jsonld
def _jsonld(graph, format, *args, **kwargs): """Return formatted graph in JSON-LD ``format`` function.""" import json from pyld import jsonld from renku.models._jsonld import asjsonld output = getattr(jsonld, format)([ asjsonld(action) for action in graph.activities.values() ]) return json.dumps(output, indent=2)
python
def _jsonld(graph, format, *args, **kwargs): import json from pyld import jsonld from renku.models._jsonld import asjsonld output = getattr(jsonld, format)([ asjsonld(action) for action in graph.activities.values() ]) return json.dumps(output, indent=2)
[ "def", "_jsonld", "(", "graph", ",", "format", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "import", "json", "from", "pyld", "import", "jsonld", "from", "renku", ".", "models", ".", "_jsonld", "import", "asjsonld", "output", "=", "getattr", "(...
Return formatted graph in JSON-LD ``format`` function.
[ "Return", "formatted", "graph", "in", "JSON", "-", "LD", "format", "function", "." ]
691644d695b055a01e0ca22b2620e55bbd928c0d
https://github.com/SwissDataScienceCenter/renku-python/blob/691644d695b055a01e0ca22b2620e55bbd928c0d/renku/cli/_format/graph.py#L33-L43
15,190
SwissDataScienceCenter/renku-python
renku/cli/_format/graph.py
dot
def dot(graph, simple=True, debug=False, landscape=False): """Format graph as a dot file.""" import sys from rdflib import ConjunctiveGraph from rdflib.plugin import register, Parser from rdflib.tools.rdf2dot import rdf2dot register('json-ld', Parser, 'rdflib_jsonld.parser', 'JsonLDParser') g = ConjunctiveGraph().parse( data=_jsonld(graph, 'expand'), format='json-ld', ) g.bind('prov', 'http://www.w3.org/ns/prov#') g.bind('wfdesc', 'http://purl.org/wf4ever/wfdesc#') g.bind('wf', 'http://www.w3.org/2005/01/wf/flow#') g.bind('wfprov', 'http://purl.org/wf4ever/wfprov#') if debug: rdf2dot(g, sys.stdout) return sys.stdout.write('digraph { \n node [ fontname="DejaVu Sans" ] ; \n ') if landscape: sys.stdout.write('rankdir="LR" \n') if simple: _rdf2dot_simple(g, sys.stdout) return _rdf2dot_reduced(g, sys.stdout)
python
def dot(graph, simple=True, debug=False, landscape=False): import sys from rdflib import ConjunctiveGraph from rdflib.plugin import register, Parser from rdflib.tools.rdf2dot import rdf2dot register('json-ld', Parser, 'rdflib_jsonld.parser', 'JsonLDParser') g = ConjunctiveGraph().parse( data=_jsonld(graph, 'expand'), format='json-ld', ) g.bind('prov', 'http://www.w3.org/ns/prov#') g.bind('wfdesc', 'http://purl.org/wf4ever/wfdesc#') g.bind('wf', 'http://www.w3.org/2005/01/wf/flow#') g.bind('wfprov', 'http://purl.org/wf4ever/wfprov#') if debug: rdf2dot(g, sys.stdout) return sys.stdout.write('digraph { \n node [ fontname="DejaVu Sans" ] ; \n ') if landscape: sys.stdout.write('rankdir="LR" \n') if simple: _rdf2dot_simple(g, sys.stdout) return _rdf2dot_reduced(g, sys.stdout)
[ "def", "dot", "(", "graph", ",", "simple", "=", "True", ",", "debug", "=", "False", ",", "landscape", "=", "False", ")", ":", "import", "sys", "from", "rdflib", "import", "ConjunctiveGraph", "from", "rdflib", ".", "plugin", "import", "register", ",", "Pa...
Format graph as a dot file.
[ "Format", "graph", "as", "a", "dot", "file", "." ]
691644d695b055a01e0ca22b2620e55bbd928c0d
https://github.com/SwissDataScienceCenter/renku-python/blob/691644d695b055a01e0ca22b2620e55bbd928c0d/renku/cli/_format/graph.py#L46-L76
15,191
SwissDataScienceCenter/renku-python
renku/cli/_format/graph.py
_rdf2dot_simple
def _rdf2dot_simple(g, stream): """Create a simple graph of processes and artifacts.""" from itertools import chain import re path_re = re.compile( r'file:///(?P<type>[a-zA-Z]+)/' r'(?P<commit>\w+)' r'(?P<path>.+)?' ) inputs = g.query( """ SELECT ?input ?role ?activity ?comment WHERE { ?activity (prov:qualifiedUsage/prov:entity) ?input . ?activity prov:qualifiedUsage ?qual . ?qual prov:hadRole ?role . ?qual prov:entity ?input . ?qual rdf:type ?type . ?activity rdf:type wfprov:ProcessRun . ?activity rdfs:comment ?comment . FILTER NOT EXISTS {?activity rdf:type wfprov:WorkflowRun} } """ ) outputs = g.query( """ SELECT ?activity ?role ?output ?comment WHERE { ?output (prov:qualifiedGeneration/prov:activity) ?activity . ?output prov:qualifiedGeneration ?qual . ?qual prov:hadRole ?role . ?qual prov:activity ?activity . ?qual rdf:type ?type . ?activity rdf:type wfprov:ProcessRun ; rdfs:comment ?comment . FILTER NOT EXISTS {?activity rdf:type wfprov:WorkflowRun} } """ ) activity_nodes = {} artifact_nodes = {} for source, role, target, comment, in chain(inputs, outputs): # extract the pieces of the process URI src_path = path_re.match(source).groupdict() tgt_path = path_re.match(target).groupdict() # write the edge stream.write( '\t"{src_commit}:{src_path}" -> ' '"{tgt_commit}:{tgt_path}" ' '[label={role}] \n'.format( src_commit=src_path['commit'][:5], src_path=src_path.get('path') or '', tgt_commit=tgt_path['commit'][:5], tgt_path=tgt_path.get('path') or '', role=role ) ) if src_path.get('type') == 'commit': activity_nodes.setdefault(source, {'comment': comment}) artifact_nodes.setdefault(target, {}) if tgt_path.get('type') == 'commit': activity_nodes.setdefault(target, {'comment': comment}) artifact_nodes.setdefault(source, {}) # customize the nodes for node, content in activity_nodes.items(): node_path = path_re.match(node).groupdict() stream.write( '\t"{commit}:{path}" ' '[shape=box label="#{commit}:{path}:{comment}"] \n'.format( comment=content['comment'], commit=node_path['commit'][:5], path=node_path.get('path') or '' ) ) for node, content in artifact_nodes.items(): node_path = path_re.match(node).groupdict() stream.write( '\t"{commit}:{path}" ' '[label="#{commit}:{path}"] \n'.format( commit=node_path['commit'][:5], path=node_path.get('path') or '' ) ) stream.write('}\n')
python
def _rdf2dot_simple(g, stream): from itertools import chain import re path_re = re.compile( r'file:///(?P<type>[a-zA-Z]+)/' r'(?P<commit>\w+)' r'(?P<path>.+)?' ) inputs = g.query( """ SELECT ?input ?role ?activity ?comment WHERE { ?activity (prov:qualifiedUsage/prov:entity) ?input . ?activity prov:qualifiedUsage ?qual . ?qual prov:hadRole ?role . ?qual prov:entity ?input . ?qual rdf:type ?type . ?activity rdf:type wfprov:ProcessRun . ?activity rdfs:comment ?comment . FILTER NOT EXISTS {?activity rdf:type wfprov:WorkflowRun} } """ ) outputs = g.query( """ SELECT ?activity ?role ?output ?comment WHERE { ?output (prov:qualifiedGeneration/prov:activity) ?activity . ?output prov:qualifiedGeneration ?qual . ?qual prov:hadRole ?role . ?qual prov:activity ?activity . ?qual rdf:type ?type . ?activity rdf:type wfprov:ProcessRun ; rdfs:comment ?comment . FILTER NOT EXISTS {?activity rdf:type wfprov:WorkflowRun} } """ ) activity_nodes = {} artifact_nodes = {} for source, role, target, comment, in chain(inputs, outputs): # extract the pieces of the process URI src_path = path_re.match(source).groupdict() tgt_path = path_re.match(target).groupdict() # write the edge stream.write( '\t"{src_commit}:{src_path}" -> ' '"{tgt_commit}:{tgt_path}" ' '[label={role}] \n'.format( src_commit=src_path['commit'][:5], src_path=src_path.get('path') or '', tgt_commit=tgt_path['commit'][:5], tgt_path=tgt_path.get('path') or '', role=role ) ) if src_path.get('type') == 'commit': activity_nodes.setdefault(source, {'comment': comment}) artifact_nodes.setdefault(target, {}) if tgt_path.get('type') == 'commit': activity_nodes.setdefault(target, {'comment': comment}) artifact_nodes.setdefault(source, {}) # customize the nodes for node, content in activity_nodes.items(): node_path = path_re.match(node).groupdict() stream.write( '\t"{commit}:{path}" ' '[shape=box label="#{commit}:{path}:{comment}"] \n'.format( comment=content['comment'], commit=node_path['commit'][:5], path=node_path.get('path') or '' ) ) for node, content in artifact_nodes.items(): node_path = path_re.match(node).groupdict() stream.write( '\t"{commit}:{path}" ' '[label="#{commit}:{path}"] \n'.format( commit=node_path['commit'][:5], path=node_path.get('path') or '' ) ) stream.write('}\n')
[ "def", "_rdf2dot_simple", "(", "g", ",", "stream", ")", ":", "from", "itertools", "import", "chain", "import", "re", "path_re", "=", "re", ".", "compile", "(", "r'file:///(?P<type>[a-zA-Z]+)/'", "r'(?P<commit>\\w+)'", "r'(?P<path>.+)?'", ")", "inputs", "=", "g", ...
Create a simple graph of processes and artifacts.
[ "Create", "a", "simple", "graph", "of", "processes", "and", "artifacts", "." ]
691644d695b055a01e0ca22b2620e55bbd928c0d
https://github.com/SwissDataScienceCenter/renku-python/blob/691644d695b055a01e0ca22b2620e55bbd928c0d/renku/cli/_format/graph.py#L86-L175
15,192
SwissDataScienceCenter/renku-python
renku/cli/_format/graph.py
makefile
def makefile(graph): """Format graph as Makefile.""" from renku.models.provenance.activities import ProcessRun, WorkflowRun for activity in graph.activities.values(): if not isinstance(activity, ProcessRun): continue elif isinstance(activity, WorkflowRun): steps = activity.subprocesses.values() else: steps = [activity] for step in steps: click.echo(' '.join(step.outputs) + ': ' + ' '.join(step.inputs)) tool = step.process click.echo( '\t@' + ' '.join(tool.to_argv()) + ' ' + ' '.join( tool.STD_STREAMS_REPR[key] + ' ' + str(path) for key, path in tool._std_streams().items() ) )
python
def makefile(graph): from renku.models.provenance.activities import ProcessRun, WorkflowRun for activity in graph.activities.values(): if not isinstance(activity, ProcessRun): continue elif isinstance(activity, WorkflowRun): steps = activity.subprocesses.values() else: steps = [activity] for step in steps: click.echo(' '.join(step.outputs) + ': ' + ' '.join(step.inputs)) tool = step.process click.echo( '\t@' + ' '.join(tool.to_argv()) + ' ' + ' '.join( tool.STD_STREAMS_REPR[key] + ' ' + str(path) for key, path in tool._std_streams().items() ) )
[ "def", "makefile", "(", "graph", ")", ":", "from", "renku", ".", "models", ".", "provenance", ".", "activities", "import", "ProcessRun", ",", "WorkflowRun", "for", "activity", "in", "graph", ".", "activities", ".", "values", "(", ")", ":", "if", "not", "...
Format graph as Makefile.
[ "Format", "graph", "as", "Makefile", "." ]
691644d695b055a01e0ca22b2620e55bbd928c0d
https://github.com/SwissDataScienceCenter/renku-python/blob/691644d695b055a01e0ca22b2620e55bbd928c0d/renku/cli/_format/graph.py#L281-L301
15,193
SwissDataScienceCenter/renku-python
renku/cli/_format/graph.py
nt
def nt(graph): """Format graph as n-tuples.""" from rdflib import ConjunctiveGraph from rdflib.plugin import register, Parser register('json-ld', Parser, 'rdflib_jsonld.parser', 'JsonLDParser') click.echo( ConjunctiveGraph().parse( data=_jsonld(graph, 'expand'), format='json-ld', ).serialize(format='nt') )
python
def nt(graph): from rdflib import ConjunctiveGraph from rdflib.plugin import register, Parser register('json-ld', Parser, 'rdflib_jsonld.parser', 'JsonLDParser') click.echo( ConjunctiveGraph().parse( data=_jsonld(graph, 'expand'), format='json-ld', ).serialize(format='nt') )
[ "def", "nt", "(", "graph", ")", ":", "from", "rdflib", "import", "ConjunctiveGraph", "from", "rdflib", ".", "plugin", "import", "register", ",", "Parser", "register", "(", "'json-ld'", ",", "Parser", ",", "'rdflib_jsonld.parser'", ",", "'JsonLDParser'", ")", "...
Format graph as n-tuples.
[ "Format", "graph", "as", "n", "-", "tuples", "." ]
691644d695b055a01e0ca22b2620e55bbd928c0d
https://github.com/SwissDataScienceCenter/renku-python/blob/691644d695b055a01e0ca22b2620e55bbd928c0d/renku/cli/_format/graph.py#L314-L326
15,194
SwissDataScienceCenter/renku-python
renku/cli/githooks.py
install
def install(client, force): """Install Git hooks.""" import pkg_resources from git.index.fun import hook_path as get_hook_path for hook in HOOKS: hook_path = Path(get_hook_path(hook, client.repo.git_dir)) if hook_path.exists(): if not force: click.echo( 'Hook already exists. Skipping {0}'.format(str(hook_path)), err=True ) continue else: hook_path.unlink() # Make sure the hooks directory exists. hook_path.parent.mkdir(parents=True, exist_ok=True) Path(hook_path).write_bytes( pkg_resources.resource_string( 'renku.data', '{hook}.sh'.format(hook=hook) ) ) hook_path.chmod(hook_path.stat().st_mode | stat.S_IEXEC)
python
def install(client, force): import pkg_resources from git.index.fun import hook_path as get_hook_path for hook in HOOKS: hook_path = Path(get_hook_path(hook, client.repo.git_dir)) if hook_path.exists(): if not force: click.echo( 'Hook already exists. Skipping {0}'.format(str(hook_path)), err=True ) continue else: hook_path.unlink() # Make sure the hooks directory exists. hook_path.parent.mkdir(parents=True, exist_ok=True) Path(hook_path).write_bytes( pkg_resources.resource_string( 'renku.data', '{hook}.sh'.format(hook=hook) ) ) hook_path.chmod(hook_path.stat().st_mode | stat.S_IEXEC)
[ "def", "install", "(", "client", ",", "force", ")", ":", "import", "pkg_resources", "from", "git", ".", "index", ".", "fun", "import", "hook_path", "as", "get_hook_path", "for", "hook", "in", "HOOKS", ":", "hook_path", "=", "Path", "(", "get_hook_path", "(...
Install Git hooks.
[ "Install", "Git", "hooks", "." ]
691644d695b055a01e0ca22b2620e55bbd928c0d
https://github.com/SwissDataScienceCenter/renku-python/blob/691644d695b055a01e0ca22b2620e55bbd928c0d/renku/cli/githooks.py#L60-L85
15,195
SwissDataScienceCenter/renku-python
renku/cli/githooks.py
uninstall
def uninstall(client): """Uninstall Git hooks.""" from git.index.fun import hook_path as get_hook_path for hook in HOOKS: hook_path = Path(get_hook_path(hook, client.repo.git_dir)) if hook_path.exists(): hook_path.unlink()
python
def uninstall(client): from git.index.fun import hook_path as get_hook_path for hook in HOOKS: hook_path = Path(get_hook_path(hook, client.repo.git_dir)) if hook_path.exists(): hook_path.unlink()
[ "def", "uninstall", "(", "client", ")", ":", "from", "git", ".", "index", ".", "fun", "import", "hook_path", "as", "get_hook_path", "for", "hook", "in", "HOOKS", ":", "hook_path", "=", "Path", "(", "get_hook_path", "(", "hook", ",", "client", ".", "repo"...
Uninstall Git hooks.
[ "Uninstall", "Git", "hooks", "." ]
691644d695b055a01e0ca22b2620e55bbd928c0d
https://github.com/SwissDataScienceCenter/renku-python/blob/691644d695b055a01e0ca22b2620e55bbd928c0d/renku/cli/githooks.py#L90-L97
15,196
SwissDataScienceCenter/renku-python
renku/models/_tabulate.py
format_cell
def format_cell(cell, datetime_fmt=None): """Format a cell.""" if datetime_fmt and isinstance(cell, datetime): return cell.strftime(datetime_fmt) return cell
python
def format_cell(cell, datetime_fmt=None): if datetime_fmt and isinstance(cell, datetime): return cell.strftime(datetime_fmt) return cell
[ "def", "format_cell", "(", "cell", ",", "datetime_fmt", "=", "None", ")", ":", "if", "datetime_fmt", "and", "isinstance", "(", "cell", ",", "datetime", ")", ":", "return", "cell", ".", "strftime", "(", "datetime_fmt", ")", "return", "cell" ]
Format a cell.
[ "Format", "a", "cell", "." ]
691644d695b055a01e0ca22b2620e55bbd928c0d
https://github.com/SwissDataScienceCenter/renku-python/blob/691644d695b055a01e0ca22b2620e55bbd928c0d/renku/models/_tabulate.py#L26-L30
15,197
SwissDataScienceCenter/renku-python
renku/models/_tabulate.py
tabulate
def tabulate(collection, headers, datetime_fmt='%Y-%m-%d %H:%M:%S', **kwargs): """Pretty-print a collection.""" if isinstance(headers, dict): attrs = headers.keys() # if mapping is not specified keep original names = [ key if value is None else value for key, value in headers.items() ] else: attrs = names = headers table = [( format_cell(cell, datetime_fmt=datetime_fmt) for cell in attrgetter(*attrs)(c) ) for c in collection] return tblte(table, headers=[h.upper() for h in names], **kwargs)
python
def tabulate(collection, headers, datetime_fmt='%Y-%m-%d %H:%M:%S', **kwargs): if isinstance(headers, dict): attrs = headers.keys() # if mapping is not specified keep original names = [ key if value is None else value for key, value in headers.items() ] else: attrs = names = headers table = [( format_cell(cell, datetime_fmt=datetime_fmt) for cell in attrgetter(*attrs)(c) ) for c in collection] return tblte(table, headers=[h.upper() for h in names], **kwargs)
[ "def", "tabulate", "(", "collection", ",", "headers", ",", "datetime_fmt", "=", "'%Y-%m-%d %H:%M:%S'", ",", "*", "*", "kwargs", ")", ":", "if", "isinstance", "(", "headers", ",", "dict", ")", ":", "attrs", "=", "headers", ".", "keys", "(", ")", "# if map...
Pretty-print a collection.
[ "Pretty", "-", "print", "a", "collection", "." ]
691644d695b055a01e0ca22b2620e55bbd928c0d
https://github.com/SwissDataScienceCenter/renku-python/blob/691644d695b055a01e0ca22b2620e55bbd928c0d/renku/models/_tabulate.py#L33-L47
15,198
SwissDataScienceCenter/renku-python
renku/models/datasets.py
_convert_dataset_files
def _convert_dataset_files(value): """Convert dataset files.""" output = {} for k, v in value.items(): inst = DatasetFile.from_jsonld(v) output[inst.path] = inst return output
python
def _convert_dataset_files(value): output = {} for k, v in value.items(): inst = DatasetFile.from_jsonld(v) output[inst.path] = inst return output
[ "def", "_convert_dataset_files", "(", "value", ")", ":", "output", "=", "{", "}", "for", "k", ",", "v", "in", "value", ".", "items", "(", ")", ":", "inst", "=", "DatasetFile", ".", "from_jsonld", "(", "v", ")", "output", "[", "inst", ".", "path", "...
Convert dataset files.
[ "Convert", "dataset", "files", "." ]
691644d695b055a01e0ca22b2620e55bbd928c0d
https://github.com/SwissDataScienceCenter/renku-python/blob/691644d695b055a01e0ca22b2620e55bbd928c0d/renku/models/datasets.py#L151-L157
15,199
SwissDataScienceCenter/renku-python
renku/cli/remove.py
remove
def remove(ctx, client, sources): """Remove files and check repository for potential problems.""" from renku.api._git import _expand_directories def fmt_path(path): """Format path as relative to the client path.""" return str(Path(path).absolute().relative_to(client.path)) files = { fmt_path(source): fmt_path(file_or_dir) for file_or_dir in sources for source in _expand_directories((file_or_dir, )) } # 1. Update dataset metadata files. with progressbar( client.datasets.values(), item_show_func=lambda item: str(item.short_id) if item else '', label='Updating dataset metadata', width=0, ) as bar: for dataset in bar: remove = [] for key, file_ in dataset.files.items(): filepath = fmt_path(file_.full_path) if filepath in files: remove.append(key) if remove: for key in remove: dataset.unlink_file(key) dataset.to_yaml() # 2. Manage .gitattributes for external storage. tracked = tuple( path for path, attr in client.find_attr(*files).items() if attr.get('filter') == 'lfs' ) client.untrack_paths_from_storage(*tracked) existing = client.find_attr(*tracked) if existing: click.echo(WARNING + 'There are custom .gitattributes.\n') if click.confirm( 'Do you want to edit ".gitattributes" now?', default=False ): click.edit(filename=str(client.path / '.gitattributes')) # Finally remove the files. final_sources = list(set(files.values())) if final_sources: run(['git', 'rm', '-rf'] + final_sources, check=True)
python
def remove(ctx, client, sources): from renku.api._git import _expand_directories def fmt_path(path): """Format path as relative to the client path.""" return str(Path(path).absolute().relative_to(client.path)) files = { fmt_path(source): fmt_path(file_or_dir) for file_or_dir in sources for source in _expand_directories((file_or_dir, )) } # 1. Update dataset metadata files. with progressbar( client.datasets.values(), item_show_func=lambda item: str(item.short_id) if item else '', label='Updating dataset metadata', width=0, ) as bar: for dataset in bar: remove = [] for key, file_ in dataset.files.items(): filepath = fmt_path(file_.full_path) if filepath in files: remove.append(key) if remove: for key in remove: dataset.unlink_file(key) dataset.to_yaml() # 2. Manage .gitattributes for external storage. tracked = tuple( path for path, attr in client.find_attr(*files).items() if attr.get('filter') == 'lfs' ) client.untrack_paths_from_storage(*tracked) existing = client.find_attr(*tracked) if existing: click.echo(WARNING + 'There are custom .gitattributes.\n') if click.confirm( 'Do you want to edit ".gitattributes" now?', default=False ): click.edit(filename=str(client.path / '.gitattributes')) # Finally remove the files. final_sources = list(set(files.values())) if final_sources: run(['git', 'rm', '-rf'] + final_sources, check=True)
[ "def", "remove", "(", "ctx", ",", "client", ",", "sources", ")", ":", "from", "renku", ".", "api", ".", "_git", "import", "_expand_directories", "def", "fmt_path", "(", "path", ")", ":", "\"\"\"Format path as relative to the client path.\"\"\"", "return", "str", ...
Remove files and check repository for potential problems.
[ "Remove", "files", "and", "check", "repository", "for", "potential", "problems", "." ]
691644d695b055a01e0ca22b2620e55bbd928c0d
https://github.com/SwissDataScienceCenter/renku-python/blob/691644d695b055a01e0ca22b2620e55bbd928c0d/renku/cli/remove.py#L39-L90