sentence1 stringlengths 52 3.87M | sentence2 stringlengths 1 47.2k | label stringclasses 1 value |
|---|---|---|
def _temp_bool_prop(propname, doc="", default=False):
"""Creates a property that uses the :class:`_TempBool` class
Parameters
----------
propname: str
The attribute name to use. The _TempBool instance will be stored in the
``'_' + propname`` attribute of the corresponding instance
doc: str
The documentation of the property
default: bool
The default value of the _TempBool class"""
def getx(self):
if getattr(self, '_' + propname, None) is not None:
return getattr(self, '_' + propname)
else:
setattr(self, '_' + propname, _TempBool(default))
return getattr(self, '_' + propname)
def setx(self, value):
getattr(self, propname).value = bool(value)
def delx(self):
getattr(self, propname).value = default
return property(getx, setx, delx, doc) | Creates a property that uses the :class:`_TempBool` class
Parameters
----------
propname: str
The attribute name to use. The _TempBool instance will be stored in the
``'_' + propname`` attribute of the corresponding instance
doc: str
The documentation of the property
default: bool
The default value of the _TempBool class | entailment |
def check_key(key, possible_keys, raise_error=True,
name='formatoption keyword',
msg=("See show_fmtkeys function for possible formatopion "
"keywords"),
*args, **kwargs):
"""
Checks whether the key is in a list of possible keys
This function checks whether the given `key` is in `possible_keys` and if
not looks for similar sounding keys
Parameters
----------
key: str
Key to check
possible_keys: list of strings
a list of possible keys to use
raise_error: bool
If not True, a list of similar keys is returned
name: str
The name of the key that shall be used in the error message
msg: str
The additional message that shall be used if no close match to
key is found
``*args,**kwargs``
They are passed to the :func:`difflib.get_close_matches` function
(i.e. `n` to increase the number of returned similar keys and
`cutoff` to change the sensibility)
Returns
-------
str
The `key` if it is a valid string, else an empty string
list
A list of similar formatoption strings (if found)
str
An error message which includes
Raises
------
KeyError
If the key is not a valid formatoption and `raise_error` is True"""
if key not in possible_keys:
similarkeys = get_close_matches(key, possible_keys, *args, **kwargs)
if similarkeys:
msg = ('Unknown %s %s! Possible similiar '
'frasings are %s.') % (name, key, ', '.join(similarkeys))
else:
msg = ("Unknown %s %s! ") % (name, key) + msg
if not raise_error:
return '', similarkeys, msg
raise KeyError(msg)
else:
return key, [key], '' | Checks whether the key is in a list of possible keys
This function checks whether the given `key` is in `possible_keys` and if
not looks for similar sounding keys
Parameters
----------
key: str
Key to check
possible_keys: list of strings
a list of possible keys to use
raise_error: bool
If not True, a list of similar keys is returned
name: str
The name of the key that shall be used in the error message
msg: str
The additional message that shall be used if no close match to
key is found
``*args,**kwargs``
They are passed to the :func:`difflib.get_close_matches` function
(i.e. `n` to increase the number of returned similar keys and
`cutoff` to change the sensibility)
Returns
-------
str
The `key` if it is a valid string, else an empty string
list
A list of similar formatoption strings (if found)
str
An error message which includes
Raises
------
KeyError
If the key is not a valid formatoption and `raise_error` is True | entailment |
def sort_kwargs(kwargs, *param_lists):
"""Function to sort keyword arguments and sort them into dictionaries
This function returns dictionaries that contain the keyword arguments
from `kwargs` corresponding given iterables in ``*params``
Parameters
----------
kwargs: dict
Original dictionary
``*param_lists``
iterables of strings, each standing for a possible key in kwargs
Returns
-------
list
len(params) + 1 dictionaries. Each dictionary contains the items of
`kwargs` corresponding to the specified list in ``*param_lists``. The
last dictionary contains the remaining items"""
return chain(
({key: kwargs.pop(key) for key in params.intersection(kwargs)}
for params in map(set, param_lists)), [kwargs]) | Function to sort keyword arguments and sort them into dictionaries
This function returns dictionaries that contain the keyword arguments
from `kwargs` corresponding given iterables in ``*params``
Parameters
----------
kwargs: dict
Original dictionary
``*param_lists``
iterables of strings, each standing for a possible key in kwargs
Returns
-------
list
len(params) + 1 dictionaries. Each dictionary contains the items of
`kwargs` corresponding to the specified list in ``*param_lists``. The
last dictionary contains the remaining items | entailment |
def hashable(val):
"""Test if `val` is hashable and if not, get it's string representation
Parameters
----------
val: object
Any (possibly not hashable) python object
Returns
-------
val or string
The given `val` if it is hashable or it's string representation"""
if val is None:
return val
try:
hash(val)
except TypeError:
return repr(val)
else:
return val | Test if `val` is hashable and if not, get it's string representation
Parameters
----------
val: object
Any (possibly not hashable) python object
Returns
-------
val or string
The given `val` if it is hashable or it's string representation | entailment |
def join_dicts(dicts, delimiter=None, keep_all=False):
"""Join multiple dictionaries into one
Parameters
----------
dicts: list of dict
A list of dictionaries
delimiter: str
The string that shall be used as the delimiter in case that there
are multiple values for one attribute in the arrays. If None, they
will be returned as sets
keep_all: bool
If True, all formatoptions are kept. Otherwise only the intersection
Returns
-------
dict
The combined dictionary"""
if not dicts:
return {}
if keep_all:
all_keys = set(chain(*(d.keys() for d in dicts)))
else:
all_keys = set(dicts[0])
for d in dicts[1:]:
all_keys.intersection_update(d)
ret = {}
for key in all_keys:
vals = {hashable(d.get(key, None)) for d in dicts} - {None}
if len(vals) == 1:
ret[key] = next(iter(vals))
elif delimiter is None:
ret[key] = vals
else:
ret[key] = delimiter.join(map(str, vals))
return ret | Join multiple dictionaries into one
Parameters
----------
dicts: list of dict
A list of dictionaries
delimiter: str
The string that shall be used as the delimiter in case that there
are multiple values for one attribute in the arrays. If None, they
will be returned as sets
keep_all: bool
If True, all formatoptions are kept. Otherwise only the intersection
Returns
-------
dict
The combined dictionary | entailment |
def check_guest_exist(check_index=0):
"""Check guest exist in database.
:param check_index: The parameter index of userid(s), default as 0
"""
def outer(f):
@six.wraps(f)
def inner(self, *args, **kw):
userids = args[check_index]
if isinstance(userids, list):
# convert all userids to upper case
userids = [uid.upper() for uid in userids]
new_args = (args[:check_index] + (userids,) +
args[check_index + 1:])
else:
# convert the userid to upper case
userids = userids.upper()
new_args = (args[:check_index] + (userids,) +
args[check_index + 1:])
userids = [userids]
self._vmops.check_guests_exist_in_db(userids)
return f(self, *new_args, **kw)
return inner
return outer | Check guest exist in database.
:param check_index: The parameter index of userid(s), default as 0 | entailment |
def guest_start(self, userid):
"""Power on a virtual machine.
:param str userid: the id of the virtual machine to be power on
:returns: None
"""
action = "start guest '%s'" % userid
with zvmutils.log_and_reraise_sdkbase_error(action):
self._vmops.guest_start(userid) | Power on a virtual machine.
:param str userid: the id of the virtual machine to be power on
:returns: None | entailment |
def guest_stop(self, userid, **kwargs):
"""Power off a virtual machine.
:param str userid: the id of the virtual machine to be power off
:param dict kwargs:
- timeout=<value>:
Integer, time to wait for vm to be deactivate, the
recommended value is 300
- poll_interval=<value>
Integer, how often to signal guest while waiting for it
to be deactivate, the recommended value is 20
:returns: None
"""
action = "stop guest '%s'" % userid
with zvmutils.log_and_reraise_sdkbase_error(action):
self._vmops.guest_stop(userid, **kwargs) | Power off a virtual machine.
:param str userid: the id of the virtual machine to be power off
:param dict kwargs:
- timeout=<value>:
Integer, time to wait for vm to be deactivate, the
recommended value is 300
- poll_interval=<value>
Integer, how often to signal guest while waiting for it
to be deactivate, the recommended value is 20
:returns: None | entailment |
def guest_softstop(self, userid, **kwargs):
"""Issue a shutdown command to shutdown the OS in a virtual
machine and then log the virtual machine off z/VM..
:param str userid: the id of the virtual machine to be power off
:param dict kwargs:
- timeout=<value>:
Integer, time to wait for vm to be deactivate, the
recommended value is 300
- poll_interval=<value>
Integer, how often to signal guest while waiting for it
to be deactivate, the recommended value is 20
:returns: None
"""
action = "soft stop guest '%s'" % userid
with zvmutils.log_and_reraise_sdkbase_error(action):
self._vmops.guest_softstop(userid, **kwargs) | Issue a shutdown command to shutdown the OS in a virtual
machine and then log the virtual machine off z/VM..
:param str userid: the id of the virtual machine to be power off
:param dict kwargs:
- timeout=<value>:
Integer, time to wait for vm to be deactivate, the
recommended value is 300
- poll_interval=<value>
Integer, how often to signal guest while waiting for it
to be deactivate, the recommended value is 20
:returns: None | entailment |
def guest_reboot(self, userid):
"""Reboot a virtual machine
:param str userid: the id of the virtual machine to be reboot
:returns: None
"""
action = "reboot guest '%s'" % userid
with zvmutils.log_and_reraise_sdkbase_error(action):
self._vmops.guest_reboot(userid) | Reboot a virtual machine
:param str userid: the id of the virtual machine to be reboot
:returns: None | entailment |
def guest_reset(self, userid):
"""reset a virtual machine
:param str userid: the id of the virtual machine to be reset
:returns: None
"""
action = "reset guest '%s'" % userid
with zvmutils.log_and_reraise_sdkbase_error(action):
self._vmops.guest_reset(userid) | reset a virtual machine
:param str userid: the id of the virtual machine to be reset
:returns: None | entailment |
def guest_pause(self, userid):
"""Pause a virtual machine.
:param str userid: the id of the virtual machine to be paused
:returns: None
"""
action = "pause guest '%s'" % userid
with zvmutils.log_and_reraise_sdkbase_error(action):
self._vmops.guest_pause(userid) | Pause a virtual machine.
:param str userid: the id of the virtual machine to be paused
:returns: None | entailment |
def guest_unpause(self, userid):
"""Unpause a virtual machine.
:param str userid: the id of the virtual machine to be unpaused
:returns: None
"""
action = "unpause guest '%s'" % userid
with zvmutils.log_and_reraise_sdkbase_error(action):
self._vmops.guest_unpause(userid) | Unpause a virtual machine.
:param str userid: the id of the virtual machine to be unpaused
:returns: None | entailment |
def guest_get_power_state(self, userid):
"""Returns power state."""
action = "get power state of guest '%s'" % userid
with zvmutils.log_and_reraise_sdkbase_error(action):
return self._vmops.get_power_state(userid) | Returns power state. | entailment |
def guest_get_info(self, userid):
"""Get the status of a virtual machine.
:param str userid: the id of the virtual machine
:returns: Dictionary contains:
power_state: (str) the running state, one of on | off
max_mem_kb: (int) the maximum memory in KBytes allowed
mem_kb: (int) the memory in KBytes used by the instance
num_cpu: (int) the number of virtual CPUs for the instance
cpu_time_us: (int) the CPU time used in microseconds
"""
action = "get info of guest '%s'" % userid
with zvmutils.log_and_reraise_sdkbase_error(action):
return self._vmops.get_info(userid) | Get the status of a virtual machine.
:param str userid: the id of the virtual machine
:returns: Dictionary contains:
power_state: (str) the running state, one of on | off
max_mem_kb: (int) the maximum memory in KBytes allowed
mem_kb: (int) the memory in KBytes used by the instance
num_cpu: (int) the number of virtual CPUs for the instance
cpu_time_us: (int) the CPU time used in microseconds | entailment |
def host_diskpool_get_info(self, disk_pool=None):
""" Retrieve diskpool information.
:param str disk_pool: the disk pool info. It use ':' to separate
disk pool type and pool name, eg "ECKD:eckdpool" or "FBA:fbapool"
:returns: Dictionary describing disk pool usage info
"""
# disk_pool must be assigned. disk_pool default to None because
# it is more convenient for users to just type function name when
# they want to get the disk pool info of CONF.zvm.disk_pool
if disk_pool is None:
disk_pool = CONF.zvm.disk_pool
if ':' not in disk_pool:
msg = ('Invalid input parameter disk_pool, expect ":" in'
'disk_pool, eg. ECKD:eckdpool')
LOG.error(msg)
raise exception.SDKInvalidInputFormat(msg)
diskpool_type = disk_pool.split(':')[0].upper()
diskpool_name = disk_pool.split(':')[1]
if diskpool_type not in ('ECKD', 'FBA'):
msg = ('Invalid disk pool type found in disk_pool, expect'
'disk_pool like ECKD:eckdpool or FBA:fbapool')
LOG.error(msg)
raise exception.SDKInvalidInputFormat(msg)
action = "get information of disk pool: '%s'" % disk_pool
with zvmutils.log_and_reraise_sdkbase_error(action):
return self._hostops.diskpool_get_info(diskpool_name) | Retrieve diskpool information.
:param str disk_pool: the disk pool info. It use ':' to separate
disk pool type and pool name, eg "ECKD:eckdpool" or "FBA:fbapool"
:returns: Dictionary describing disk pool usage info | entailment |
def image_delete(self, image_name):
"""Delete image from image repository
:param image_name: the name of the image to be deleted
"""
try:
self._imageops.image_delete(image_name)
except exception.SDKBaseException:
LOG.error("Failed to delete image '%s'" % image_name)
raise | Delete image from image repository
:param image_name: the name of the image to be deleted | entailment |
def image_get_root_disk_size(self, image_name):
"""Get the root disk size of the image
:param image_name: the image name in image Repository
:returns: the disk size in units CYL or BLK
"""
try:
return self._imageops.image_get_root_disk_size(image_name)
except exception.SDKBaseException:
LOG.error("Failed to get root disk size units of image '%s'" %
image_name)
raise | Get the root disk size of the image
:param image_name: the image name in image Repository
:returns: the disk size in units CYL or BLK | entailment |
def image_import(self, image_name, url, image_meta, remote_host=None):
"""Import image to zvmsdk image repository
:param image_name: image name that can be uniquely identify an image
:param str url: image url to specify the location of image such as
http://netloc/path/to/file.tar.gz.0
https://netloc/path/to/file.tar.gz.0
file:///path/to/file.tar.gz.0
:param dict image_meta:
a dictionary to describe the image info, such as md5sum,
os_version. For example:
{'os_version': 'rhel6.2',
'md5sum': ' 46f199c336eab1e35a72fa6b5f6f11f5'}
:param string remote_host:
if the image url schema is file, the remote_host is used to
indicate where the image comes from, the format is username@IP
eg. nova@192.168.99.1, the default value is None, it indicate
the image is from a local file system. If the image url schema
is http/https, this value will be useless
"""
try:
self._imageops.image_import(image_name, url, image_meta,
remote_host=remote_host)
except exception.SDKBaseException:
LOG.error("Failed to import image '%s'" % image_name)
raise | Import image to zvmsdk image repository
:param image_name: image name that can be uniquely identify an image
:param str url: image url to specify the location of image such as
http://netloc/path/to/file.tar.gz.0
https://netloc/path/to/file.tar.gz.0
file:///path/to/file.tar.gz.0
:param dict image_meta:
a dictionary to describe the image info, such as md5sum,
os_version. For example:
{'os_version': 'rhel6.2',
'md5sum': ' 46f199c336eab1e35a72fa6b5f6f11f5'}
:param string remote_host:
if the image url schema is file, the remote_host is used to
indicate where the image comes from, the format is username@IP
eg. nova@192.168.99.1, the default value is None, it indicate
the image is from a local file system. If the image url schema
is http/https, this value will be useless | entailment |
def image_query(self, imagename=None):
"""Get the list of image info in image repository
:param imagename: Used to retrieve the specified image info,
if not specified, all images info will be returned
:returns: A list that contains the specified or all images info
"""
try:
return self._imageops.image_query(imagename)
except exception.SDKBaseException:
LOG.error("Failed to query image")
raise | Get the list of image info in image repository
:param imagename: Used to retrieve the specified image info,
if not specified, all images info will be returned
:returns: A list that contains the specified or all images info | entailment |
def image_export(self, image_name, dest_url, remote_host=None):
"""Export the image to the specified location
:param image_name: image name that can be uniquely identify an image
:param dest_url: the location of exported image, eg.
file:///opt/images/export.img, now only support export to remote server
or local server's file system
:param remote_host: the server that the image will be export to, if
remote_host is None, the image will be stored in the dest_path in
local server, the format is username@IP eg. nova@9.x.x.x
:returns a dictionary that contains the exported image info
{
'image_name': the image_name that exported
'image_path': the image_path after exported
'os_version': the os version of the exported image
'md5sum': the md5sum of the original image
}
"""
try:
return self._imageops.image_export(image_name, dest_url,
remote_host)
except exception.SDKBaseException:
LOG.error("Failed to export image '%s'" % image_name)
raise | Export the image to the specified location
:param image_name: image name that can be uniquely identify an image
:param dest_url: the location of exported image, eg.
file:///opt/images/export.img, now only support export to remote server
or local server's file system
:param remote_host: the server that the image will be export to, if
remote_host is None, the image will be stored in the dest_path in
local server, the format is username@IP eg. nova@9.x.x.x
:returns a dictionary that contains the exported image info
{
'image_name': the image_name that exported
'image_path': the image_path after exported
'os_version': the os version of the exported image
'md5sum': the md5sum of the original image
} | entailment |
def guest_deploy(self, userid, image_name, transportfiles=None,
remotehost=None, vdev=None, hostname=None):
""" Deploy the image to vm.
:param userid: (str) the user id of the vm
:param image_name: (str) the name of image that used to deploy the vm
:param transportfiles: (str) the files that used to customize the vm
:param remotehost: the server where the transportfiles located, the
format is username@IP, eg nova@192.168.99.1
:param vdev: (str) the device that image will be deploy to
:param hostname: (str) the hostname of the vm. This parameter will be
ignored if transportfiles present.
"""
action = ("deploy image '%(img)s' to guest '%(vm)s'" %
{'img': image_name, 'vm': userid})
with zvmutils.log_and_reraise_sdkbase_error(action):
self._vmops.guest_deploy(userid, image_name, transportfiles,
remotehost, vdev, hostname) | Deploy the image to vm.
:param userid: (str) the user id of the vm
:param image_name: (str) the name of image that used to deploy the vm
:param transportfiles: (str) the files that used to customize the vm
:param remotehost: the server where the transportfiles located, the
format is username@IP, eg nova@192.168.99.1
:param vdev: (str) the device that image will be deploy to
:param hostname: (str) the hostname of the vm. This parameter will be
ignored if transportfiles present. | entailment |
def guest_capture(self, userid, image_name, capture_type='rootonly',
compress_level=6):
""" Capture the guest to generate a image
:param userid: (str) the user id of the vm
:param image_name: (str) the unique image name after capture
:param capture_type: (str) the type of capture, the value can be:
rootonly: indicate just root device will be captured
alldisks: indicate all the devices of the userid will be
captured
:param compress_level: the compression level of the image, default
is 6
"""
action = ("capture guest '%(vm)s' to generate image '%(img)s'" %
{'vm': userid, 'img': image_name})
with zvmutils.log_and_reraise_sdkbase_error(action):
self._vmops.guest_capture(userid, image_name,
capture_type=capture_type,
compress_level=compress_level) | Capture the guest to generate a image
:param userid: (str) the user id of the vm
:param image_name: (str) the unique image name after capture
:param capture_type: (str) the type of capture, the value can be:
rootonly: indicate just root device will be captured
alldisks: indicate all the devices of the userid will be
captured
:param compress_level: the compression level of the image, default
is 6 | entailment |
def guest_create_nic(self, userid, vdev=None, nic_id=None,
mac_addr=None, active=False):
""" Create the nic for the vm, add NICDEF record into the user direct.
:param str userid: the user id of the vm
:param str vdev: nic device number, 1- to 4- hexadecimal digits
:param str nic_id: nic identifier
:param str mac_addr: mac address, it is only be used when changing
the guest's user direct. Format should be xx:xx:xx:xx:xx:xx,
and x is a hexadecimal digit
:param bool active: whether add a nic on active guest system
:returns: nic device number, 1- to 4- hexadecimal digits
:rtype: str
"""
if mac_addr is not None:
if not zvmutils.valid_mac_addr(mac_addr):
raise exception.SDKInvalidInputFormat(
msg=("Invalid mac address, format should be "
"xx:xx:xx:xx:xx:xx, and x is a hexadecimal digit"))
return self._networkops.create_nic(userid, vdev=vdev, nic_id=nic_id,
mac_addr=mac_addr, active=active) | Create the nic for the vm, add NICDEF record into the user direct.
:param str userid: the user id of the vm
:param str vdev: nic device number, 1- to 4- hexadecimal digits
:param str nic_id: nic identifier
:param str mac_addr: mac address, it is only be used when changing
the guest's user direct. Format should be xx:xx:xx:xx:xx:xx,
and x is a hexadecimal digit
:param bool active: whether add a nic on active guest system
:returns: nic device number, 1- to 4- hexadecimal digits
:rtype: str | entailment |
def guest_delete_nic(self, userid, vdev, active=False):
""" delete the nic for the vm
:param str userid: the user id of the vm
:param str vdev: nic device number, 1- to 4- hexadecimal digits
:param bool active: whether delete a nic on active guest system
"""
self._networkops.delete_nic(userid, vdev, active=active) | delete the nic for the vm
:param str userid: the user id of the vm
:param str vdev: nic device number, 1- to 4- hexadecimal digits
:param bool active: whether delete a nic on active guest system | entailment |
def guest_get_definition_info(self, userid, **kwargs):
"""Get definition info for the specified guest vm, also could be used
to check specific info.
:param str userid: the user id of the guest vm
:param dict kwargs: Dictionary used to check specific info in user
direct. Valid keywords for kwargs:
nic_coupled=<vdev>, where <vdev> is the virtual
device number of the nic to be checked the couple
status.
:returns: Dictionary describing user direct and check info result
:rtype: dict
"""
action = "get the definition info of guest '%s'" % userid
with zvmutils.log_and_reraise_sdkbase_error(action):
return self._vmops.get_definition_info(userid, **kwargs) | Get definition info for the specified guest vm, also could be used
to check specific info.
:param str userid: the user id of the guest vm
:param dict kwargs: Dictionary used to check specific info in user
direct. Valid keywords for kwargs:
nic_coupled=<vdev>, where <vdev> is the virtual
device number of the nic to be checked the couple
status.
:returns: Dictionary describing user direct and check info result
:rtype: dict | entailment |
def guest_register(self, userid, meta, net_set):
"""DB operation for migrate vm from another z/VM host in same SSI
:param userid: (str) the userid of the vm to be relocated or tested
:param meta: (str) the metadata of the vm to be relocated or tested
:param net_set: (str) the net_set of the vm, default is 1.
"""
userid = userid.upper()
if not zvmutils.check_userid_exist(userid):
LOG.error("User directory '%s' does not exist." % userid)
raise exception.SDKObjectNotExistError(
obj_desc=("Guest '%s'" % userid), modID='guest')
else:
action = "list all guests in database which has been migrated."
with zvmutils.log_and_reraise_sdkbase_error(action):
guests = self._GuestDbOperator.get_migrated_guest_list()
if userid in str(guests):
"""change comments for vm"""
comments = self._GuestDbOperator.get_comments_by_userid(
userid)
comments['migrated'] = 0
action = "update guest '%s' in database" % userid
with zvmutils.log_and_reraise_sdkbase_error(action):
self._GuestDbOperator.update_guest_by_userid(userid,
comments=comments)
else:
"""add one record for new vm"""
action = "add guest '%s' to database" % userid
with zvmutils.log_and_reraise_sdkbase_error(action):
self._GuestDbOperator.add_guest_migrated(userid, meta,
net_set)
action = "add switches of guest '%s' to database" % userid
info = self._vmops.get_definition_info(userid)
user_direct = info['user_direct']
for nic_info in user_direct:
if nic_info.startswith('NICDEF'):
nic_list = nic_info.split()
interface = nic_list[1]
switch = nic_list[6]
with zvmutils.log_and_reraise_sdkbase_error(action):
self._NetworkDbOperator.switch_add_record_migrated(
userid, interface, switch)
LOG.info("Guest %s registered." % userid) | DB operation for migrate vm from another z/VM host in same SSI
:param userid: (str) the userid of the vm to be relocated or tested
:param meta: (str) the metadata of the vm to be relocated or tested
:param net_set: (str) the net_set of the vm, default is 1. | entailment |
def guest_live_migrate(self, userid, dest_zcc_userid, destination,
parms, lgr_action):
"""Move an eligible, running z/VM(R) virtual machine transparently
from one z/VM system to another within an SSI cluster.
:param userid: (str) the userid of the vm to be relocated or tested
:param dest_zcc_userid: (str) the userid of zcc on destination
:param destination: (str) the system ID of the z/VM system to which
the specified vm will be relocated or tested.
:param parms: (dict) a dictionary of options for relocation.
It has one dictionary that contains some of the below keys:
{'maxtotal': i,
'maxquiesce': i,
'immediate': str}
In which, 'maxtotal':indicates the maximum total time
(in seconds)
that the command issuer is willing to
wait for the entire relocation
to complete or -1 to indicate there is no limit for time.
'maxquiesce':indicates the maximum quiesce time
for this relocation.
This is the amount of time (in seconds)
a virtual machine may be stopped
during a relocation attempt or -1 to indicate
there is no limit for time.
'immediate':If present, immediate=YES is set,
which causes the VMRELOCATE command
to do one early pass through virtual machine storage
and then go directly to the quiesce stage.
:param lgr_action: (str) indicates the action is move or test for vm.
"""
if lgr_action.lower() == 'move':
if dest_zcc_userid == '':
errmsg = ("'dest_zcc_userid' is required if the value of "
"'lgr_action' equals 'move'.")
LOG.error(errmsg)
raise exception.SDKMissingRequiredInput(msg=errmsg)
# Add authorization for new zcc.
cmd = ('echo -n %s > /etc/iucv_authorized_userid\n' %
dest_zcc_userid)
rc = self._smtclient.execute_cmd(userid, cmd)
if rc != 0:
err_msg = ("Add authorization for new zcc failed")
LOG.error(err_msg)
# Live_migrate the guest
operation = "Move guest '%s' to SSI '%s'" % (userid, destination)
with zvmutils.log_and_reraise_sdkbase_error(operation):
self._vmops.live_migrate_vm(userid, destination,
parms, lgr_action)
comments = self._GuestDbOperator.get_comments_by_userid(userid)
comments['migrated'] = 1
action = "update guest '%s' in database" % userid
with zvmutils.log_and_reraise_sdkbase_error(action):
self._GuestDbOperator.update_guest_by_userid(userid,
comments=comments)
if lgr_action.lower() == 'test':
operation = "Test move guest '%s' to SSI '%s'" % (userid,
destination)
with zvmutils.log_and_reraise_sdkbase_error(operation):
self._vmops.live_migrate_vm(userid, destination,
parms, lgr_action) | Move an eligible, running z/VM(R) virtual machine transparently
from one z/VM system to another within an SSI cluster.
:param userid: (str) the userid of the vm to be relocated or tested
:param dest_zcc_userid: (str) the userid of zcc on destination
:param destination: (str) the system ID of the z/VM system to which
the specified vm will be relocated or tested.
:param parms: (dict) a dictionary of options for relocation.
It has one dictionary that contains some of the below keys:
{'maxtotal': i,
'maxquiesce': i,
'immediate': str}
In which, 'maxtotal':indicates the maximum total time
(in seconds)
that the command issuer is willing to
wait for the entire relocation
to complete or -1 to indicate there is no limit for time.
'maxquiesce':indicates the maximum quiesce time
for this relocation.
This is the amount of time (in seconds)
a virtual machine may be stopped
during a relocation attempt or -1 to indicate
there is no limit for time.
'immediate':If present, immediate=YES is set,
which causes the VMRELOCATE command
to do one early pass through virtual machine storage
and then go directly to the quiesce stage.
:param lgr_action: (str) indicates the action is move or test for vm. | entailment |
def guest_create(self, userid, vcpus, memory, disk_list=None,
user_profile=CONF.zvm.user_profile,
max_cpu=CONF.zvm.user_default_max_cpu,
max_mem=CONF.zvm.user_default_max_memory,
ipl_from='', ipl_param='', ipl_loadparam=''):
"""create a vm in z/VM
:param userid: (str) the userid of the vm to be created
:param vcpus: (int) amount of vcpus
:param memory: (int) size of memory in MB
:param disk_list: (dict) a list of disks info for the guest.
It has one dictionary that contain some of the below keys for
each disk, the root disk should be the first element in the
list, the format is:
{'size': str,
'format': str,
'is_boot_disk': bool,
'disk_pool': str}
In which, 'size': case insensitive, the unit can be in
Megabytes (M), Gigabytes (G), or number of cylinders/blocks, eg
512M, 1g or just 2000.
'format': can be ext2, ext3, ext4, xfs and none.
'is_boot_disk': For root disk, this key must be set to indicate
the image that will be deployed on this disk.
'disk_pool': optional, if not specified, the disk will be
created by using the value from configure file,the format is
ECKD:eckdpoolname or FBA:fbapoolname.
For example:
[{'size': '1g',
'is_boot_disk': True,
'disk_pool': 'ECKD:eckdpool1'},
{'size': '200000',
'disk_pool': 'FBA:fbapool1',
'format': 'ext3'}]
In this case it will create one disk 0100(in case the vdev
for root disk is 0100) with size 1g from ECKD disk pool
eckdpool1 for guest , then set IPL 0100 in guest's user
directory, and it will create 0101 with 200000 blocks from
FBA disk pool fbapool1, and formated with ext3.
:param user_profile: (str) the profile for the guest
:param max_cpu: (int) the maximum number of virtual cpu this user can
define. The value should be a decimal value between 1 and 64.
:param max_mem: (str) the maximum size of memory the user can define.
The value should be specified by 1-4 bits of number suffixed by
either M (Megabytes) or G (Gigabytes). And the number should be
an integer.
:param ipl_from: (str) where to ipl the guest from, it can be given
by guest input param, e.g CMS.
:param ipl_param: the param to use when IPL for as PARM
:param ipl_loadparam: the param to use when IPL for as LOADPARM
"""
userid = userid.upper()
if disk_list:
for disk in disk_list:
if not isinstance(disk, dict):
errmsg = ('Invalid "disk_list" input, it should be a '
'dictionary. Details could be found in doc.')
LOG.error(errmsg)
raise exception.SDKInvalidInputFormat(msg=errmsg)
# 'size' is required for each disk
if 'size' not in disk.keys():
errmsg = ('Invalid "disk_list" input, "size" is required '
'for each disk.')
LOG.error(errmsg)
raise exception.SDKInvalidInputFormat(msg=errmsg)
# 'disk_pool' format check
disk_pool = disk.get('disk_pool') or CONF.zvm.disk_pool
if ':' not in disk_pool or (disk_pool.split(':')[0].upper()
not in ['ECKD', 'FBA']):
errmsg = ("Invalid disk_pool input, it should be in format"
" ECKD:eckdpoolname or FBA:fbapoolname")
LOG.error(errmsg)
raise exception.SDKInvalidInputFormat(msg=errmsg)
# 'format' value check
if ('format' in disk.keys()) and (disk['format'].lower() not in
('ext2', 'ext3', 'ext4',
'xfs', 'none')):
errmsg = ("Invalid disk_pool input, supported 'format' "
"includes 'ext2', 'ext3', 'ext4', 'xfs', 'none'")
LOG.error(errmsg)
raise exception.SDKInvalidInputFormat(msg=errmsg)
action = "create guest '%s'" % userid
with zvmutils.log_and_reraise_sdkbase_error(action):
return self._vmops.create_vm(userid, vcpus, memory, disk_list,
user_profile, max_cpu, max_mem,
ipl_from, ipl_param, ipl_loadparam) | create a vm in z/VM
:param userid: (str) the userid of the vm to be created
:param vcpus: (int) amount of vcpus
:param memory: (int) size of memory in MB
:param disk_list: (dict) a list of disks info for the guest.
It has one dictionary that contain some of the below keys for
each disk, the root disk should be the first element in the
list, the format is:
{'size': str,
'format': str,
'is_boot_disk': bool,
'disk_pool': str}
In which, 'size': case insensitive, the unit can be in
Megabytes (M), Gigabytes (G), or number of cylinders/blocks, eg
512M, 1g or just 2000.
'format': can be ext2, ext3, ext4, xfs and none.
'is_boot_disk': For root disk, this key must be set to indicate
the image that will be deployed on this disk.
'disk_pool': optional, if not specified, the disk will be
created by using the value from configure file,the format is
ECKD:eckdpoolname or FBA:fbapoolname.
For example:
[{'size': '1g',
'is_boot_disk': True,
'disk_pool': 'ECKD:eckdpool1'},
{'size': '200000',
'disk_pool': 'FBA:fbapool1',
'format': 'ext3'}]
In this case it will create one disk 0100(in case the vdev
for root disk is 0100) with size 1g from ECKD disk pool
eckdpool1 for guest , then set IPL 0100 in guest's user
directory, and it will create 0101 with 200000 blocks from
FBA disk pool fbapool1, and formated with ext3.
:param user_profile: (str) the profile for the guest
:param max_cpu: (int) the maximum number of virtual cpu this user can
define. The value should be a decimal value between 1 and 64.
:param max_mem: (str) the maximum size of memory the user can define.
The value should be specified by 1-4 bits of number suffixed by
either M (Megabytes) or G (Gigabytes). And the number should be
an integer.
:param ipl_from: (str) where to ipl the guest from, it can be given
by guest input param, e.g CMS.
:param ipl_param: the param to use when IPL for as PARM
:param ipl_loadparam: the param to use when IPL for as LOADPARM | entailment |
def guest_live_resize_cpus(self, userid, cpu_cnt):
"""Live resize virtual cpus of guests.
:param userid: (str) the userid of the guest to be live resized
:param cpu_cnt: (int) The number of virtual cpus that the guest should
have in active state after live resize. The value should be an
integer between 1 and 64.
"""
action = "live resize guest '%s' to have '%i' virtual cpus" % (userid,
cpu_cnt)
LOG.info("Begin to %s" % action)
with zvmutils.log_and_reraise_sdkbase_error(action):
self._vmops.live_resize_cpus(userid, cpu_cnt)
LOG.info("%s successfully." % action) | Live resize virtual cpus of guests.
:param userid: (str) the userid of the guest to be live resized
:param cpu_cnt: (int) The number of virtual cpus that the guest should
have in active state after live resize. The value should be an
integer between 1 and 64. | entailment |
def guest_resize_cpus(self, userid, cpu_cnt):
"""Resize virtual cpus of guests.
:param userid: (str) the userid of the guest to be resized
:param cpu_cnt: (int) The number of virtual cpus that the guest should
have defined in user directory after resize. The value should
be an integer between 1 and 64.
"""
action = "resize guest '%s' to have '%i' virtual cpus" % (userid,
cpu_cnt)
LOG.info("Begin to %s" % action)
with zvmutils.log_and_reraise_sdkbase_error(action):
self._vmops.resize_cpus(userid, cpu_cnt)
LOG.info("%s successfully." % action) | Resize virtual cpus of guests.
:param userid: (str) the userid of the guest to be resized
:param cpu_cnt: (int) The number of virtual cpus that the guest should
have defined in user directory after resize. The value should
be an integer between 1 and 64. | entailment |
def guest_live_resize_mem(self, userid, size):
"""Live resize memory of guests.
:param userid: (str) the userid of the guest to be live resized
:param size: (str) The memory size that the guest should have
in available status after live resize.
The value should be specified by 1-4 bits of number suffixed by
either M (Megabytes) or G (Gigabytes). And the number should be
an integer.
"""
action = "live resize guest '%s' to have '%s' memory" % (userid,
size)
LOG.info("Begin to %s" % action)
with zvmutils.log_and_reraise_sdkbase_error(action):
self._vmops.live_resize_memory(userid, size)
LOG.info("%s successfully." % action) | Live resize memory of guests.
:param userid: (str) the userid of the guest to be live resized
:param size: (str) The memory size that the guest should have
in available status after live resize.
The value should be specified by 1-4 bits of number suffixed by
either M (Megabytes) or G (Gigabytes). And the number should be
an integer. | entailment |
def guest_resize_mem(self, userid, size):
"""Resize memory of guests.
:param userid: (str) the userid of the guest to be resized
:param size: (str) The memory size that the guest should have
defined in user directory after resize.
The value should be specified by 1-4 bits of number suffixed by
either M (Megabytes) or G (Gigabytes). And the number should be
an integer.
"""
action = "resize guest '%s' to have '%s' memory" % (userid, size)
LOG.info("Begin to %s" % action)
with zvmutils.log_and_reraise_sdkbase_error(action):
self._vmops.resize_memory(userid, size)
LOG.info("%s successfully." % action) | Resize memory of guests.
:param userid: (str) the userid of the guest to be resized
:param size: (str) The memory size that the guest should have
defined in user directory after resize.
The value should be specified by 1-4 bits of number suffixed by
either M (Megabytes) or G (Gigabytes). And the number should be
an integer. | entailment |
def guest_create_disks(self, userid, disk_list):
"""Add disks to an existing guest vm.
:param userid: (str) the userid of the vm to be created
:param disk_list: (list) a list of disks info for the guest.
It has one dictionary that contain some of the below keys for
each disk, the root disk should be the first element in the
list, the format is:
{'size': str,
'format': str,
'is_boot_disk': bool,
'disk_pool': str}
In which, 'size': case insensitive, the unit can be in
Megabytes (M), Gigabytes (G), or number of cylinders/blocks, eg
512M, 1g or just 2000.
'format': optional, can be ext2, ext3, ext4, xfs, if not
specified, the disk will not be formatted.
'is_boot_disk': For root disk, this key must be set to indicate
the image that will be deployed on this disk.
'disk_pool': optional, if not specified, the disk will be
created by using the value from configure file,the format is
ECKD:eckdpoolname or FBA:fbapoolname.
For example:
[{'size': '1g',
'is_boot_disk': True,
'disk_pool': 'ECKD:eckdpool1'},
{'size': '200000',
'disk_pool': 'FBA:fbapool1',
'format': 'ext3'}]
In this case it will create one disk 0100(in case the vdev
for root disk is 0100) with size 1g from ECKD disk pool
eckdpool1 for guest , then set IPL 0100 in guest's user
directory, and it will create 0101 with 200000 blocks from
FBA disk pool fbapool1, and formated with ext3.
"""
if disk_list == [] or disk_list is None:
# nothing to do
LOG.debug("No disk specified when calling guest_create_disks, "
"nothing happened")
return
action = "create disks '%s' for guest '%s'" % (str(disk_list), userid)
with zvmutils.log_and_reraise_sdkbase_error(action):
return self._vmops.create_disks(userid, disk_list) | Add disks to an existing guest vm.
:param userid: (str) the userid of the vm to be created
:param disk_list: (list) a list of disks info for the guest.
It has one dictionary that contain some of the below keys for
each disk, the root disk should be the first element in the
list, the format is:
{'size': str,
'format': str,
'is_boot_disk': bool,
'disk_pool': str}
In which, 'size': case insensitive, the unit can be in
Megabytes (M), Gigabytes (G), or number of cylinders/blocks, eg
512M, 1g or just 2000.
'format': optional, can be ext2, ext3, ext4, xfs, if not
specified, the disk will not be formatted.
'is_boot_disk': For root disk, this key must be set to indicate
the image that will be deployed on this disk.
'disk_pool': optional, if not specified, the disk will be
created by using the value from configure file,the format is
ECKD:eckdpoolname or FBA:fbapoolname.
For example:
[{'size': '1g',
'is_boot_disk': True,
'disk_pool': 'ECKD:eckdpool1'},
{'size': '200000',
'disk_pool': 'FBA:fbapool1',
'format': 'ext3'}]
In this case it will create one disk 0100(in case the vdev
for root disk is 0100) with size 1g from ECKD disk pool
eckdpool1 for guest , then set IPL 0100 in guest's user
directory, and it will create 0101 with 200000 blocks from
FBA disk pool fbapool1, and formated with ext3. | entailment |
def guest_delete_disks(self, userid, disk_vdev_list):
"""Delete disks from an existing guest vm.
:param userid: (str) the userid of the vm to be deleted
:param disk_vdev_list: (list) the vdev list of disks to be deleted,
for example: ['0101', '0102']
"""
action = "delete disks '%s' from guest '%s'" % (str(disk_vdev_list),
userid)
with zvmutils.log_and_reraise_sdkbase_error(action):
self._vmops.delete_disks(userid, disk_vdev_list) | Delete disks from an existing guest vm.
:param userid: (str) the userid of the vm to be deleted
:param disk_vdev_list: (list) the vdev list of disks to be deleted,
for example: ['0101', '0102'] | entailment |
def guest_nic_couple_to_vswitch(self, userid, nic_vdev,
vswitch_name, active=False):
""" Couple nic device to specified vswitch.
:param str userid: the user's name who owns the nic
:param str nic_vdev: nic device number, 1- to 4- hexadecimal digits
:param str vswitch_name: the name of the vswitch
:param bool active: whether make the change on active guest system
"""
self._networkops.couple_nic_to_vswitch(userid, nic_vdev,
vswitch_name, active=active) | Couple nic device to specified vswitch.
:param str userid: the user's name who owns the nic
:param str nic_vdev: nic device number, 1- to 4- hexadecimal digits
:param str vswitch_name: the name of the vswitch
:param bool active: whether make the change on active guest system | entailment |
def guest_nic_uncouple_from_vswitch(self, userid, nic_vdev,
active=False):
""" Disonnect nic device with network.
:param str userid: the user's name who owns the nic
:param str nic_vdev: nic device number, 1- to 4- hexadecimal digits
:param bool active: whether make the change on active guest system
"""
self._networkops.uncouple_nic_from_vswitch(userid, nic_vdev,
active=active) | Disonnect nic device with network.
:param str userid: the user's name who owns the nic
:param str nic_vdev: nic device number, 1- to 4- hexadecimal digits
:param bool active: whether make the change on active guest system | entailment |
def vswitch_create(self, name, rdev=None, controller='*',
connection='CONNECT', network_type='ETHERNET',
router="NONROUTER", vid='UNAWARE', port_type='ACCESS',
gvrp='GVRP', queue_mem=8, native_vid=1,
persist=True):
""" Create vswitch.
:param str name: the vswitch name
:param str rdev: the real device number, a maximum of three devices,
all 1-4 characters in length, delimited by blanks. 'NONE'
may also be specified
:param str controller: the vswitch's controller, it could be the userid
controlling the real device, or '*' to specifies that any
available controller may be used
:param str connection:
- CONnect:
Activate the real device connection.
- DISCONnect:
Do not activate the real device connection.
- NOUPLINK:
The vswitch will never have connectivity through
the UPLINK port
:param str network_type: Specifies the transport mechanism to be used
for the vswitch, as follows: IP, ETHERNET
:param str router:
- NONrouter:
The OSA-Express device identified in
real_device_address= will not act as a router to the
vswitch
- PRIrouter:
The OSA-Express device identified in
real_device_address= will act as a primary router to the
vswitch
- Note: If the network_type is ETHERNET, this value must be
unspecified, otherwise, if this value is unspecified, default
is NONROUTER
:param str/int vid: the VLAN ID. This can be any of the following
values: UNAWARE, AWARE or 1-4094
:param str port_type:
- ACCESS:
The default porttype attribute for
guests authorized for the virtual switch.
The guest is unaware of VLAN IDs and sends and
receives only untagged traffic
- TRUNK:
The default porttype attribute for
guests authorized for the virtual switch.
The guest is VLAN aware and sends and receives tagged
traffic for those VLANs to which the guest is authorized.
If the guest is also authorized to the natvid, untagged
traffic sent or received by the guest is associated with
the native VLAN ID (natvid) of the virtual switch.
:param str gvrp:
- GVRP:
Indicates that the VLAN IDs in use on the virtual
switch should be registered with GVRP-aware switches on the
LAN. This provides dynamic VLAN registration and VLAN
registration removal for networking switches. This
eliminates the need to manually configure the individual
port VLAN assignments.
- NOGVRP:
Do not register VLAN IDs with GVRP-aware switches on
the LAN. When NOGVRP is specified VLAN port assignments
must be configured manually
:param int queue_mem: A number between 1 and 8, specifying the QDIO
buffer size in megabytes.
:param int native_vid: the native vlan id, 1-4094 or None
:param bool persist: whether create the vswitch in the permanent
configuration for the system
"""
if ((queue_mem < 1) or (queue_mem > 8)):
errmsg = ('API vswitch_create: Invalid "queue_mem" input, '
'it should be 1-8')
raise exception.SDKInvalidInputFormat(msg=errmsg)
if isinstance(vid, int) or vid.upper() != 'UNAWARE':
if ((native_vid is not None) and
((native_vid < 1) or (native_vid > 4094))):
errmsg = ('API vswitch_create: Invalid "native_vid" input, '
'it should be 1-4094 or None')
raise exception.SDKInvalidInputFormat(msg=errmsg)
if network_type.upper() == 'ETHERNET':
router = None
self._networkops.add_vswitch(name, rdev=rdev, controller=controller,
connection=connection,
network_type=network_type,
router=router, vid=vid,
port_type=port_type, gvrp=gvrp,
queue_mem=queue_mem,
native_vid=native_vid,
persist=persist) | Create vswitch.
:param str name: the vswitch name
:param str rdev: the real device number, a maximum of three devices,
all 1-4 characters in length, delimited by blanks. 'NONE'
may also be specified
:param str controller: the vswitch's controller, it could be the userid
controlling the real device, or '*' to specifies that any
available controller may be used
:param str connection:
- CONnect:
Activate the real device connection.
- DISCONnect:
Do not activate the real device connection.
- NOUPLINK:
The vswitch will never have connectivity through
the UPLINK port
:param str network_type: Specifies the transport mechanism to be used
for the vswitch, as follows: IP, ETHERNET
:param str router:
- NONrouter:
The OSA-Express device identified in
real_device_address= will not act as a router to the
vswitch
- PRIrouter:
The OSA-Express device identified in
real_device_address= will act as a primary router to the
vswitch
- Note: If the network_type is ETHERNET, this value must be
unspecified, otherwise, if this value is unspecified, default
is NONROUTER
:param str/int vid: the VLAN ID. This can be any of the following
values: UNAWARE, AWARE or 1-4094
:param str port_type:
- ACCESS:
The default porttype attribute for
guests authorized for the virtual switch.
The guest is unaware of VLAN IDs and sends and
receives only untagged traffic
- TRUNK:
The default porttype attribute for
guests authorized for the virtual switch.
The guest is VLAN aware and sends and receives tagged
traffic for those VLANs to which the guest is authorized.
If the guest is also authorized to the natvid, untagged
traffic sent or received by the guest is associated with
the native VLAN ID (natvid) of the virtual switch.
:param str gvrp:
- GVRP:
Indicates that the VLAN IDs in use on the virtual
switch should be registered with GVRP-aware switches on the
LAN. This provides dynamic VLAN registration and VLAN
registration removal for networking switches. This
eliminates the need to manually configure the individual
port VLAN assignments.
- NOGVRP:
Do not register VLAN IDs with GVRP-aware switches on
the LAN. When NOGVRP is specified VLAN port assignments
must be configured manually
:param int queue_mem: A number between 1 and 8, specifying the QDIO
buffer size in megabytes.
:param int native_vid: the native vlan id, 1-4094 or None
:param bool persist: whether create the vswitch in the permanent
configuration for the system | entailment |
def guest_get_console_output(self, userid):
"""Get the console output of the guest virtual machine.
:param str userid: the user id of the vm
:returns: console log string
:rtype: str
"""
action = "get the console output of guest '%s'" % userid
with zvmutils.log_and_reraise_sdkbase_error(action):
output = self._vmops.get_console_output(userid)
return output | Get the console output of the guest virtual machine.
:param str userid: the user id of the vm
:returns: console log string
:rtype: str | entailment |
def guest_delete(self, userid):
"""Delete guest.
:param userid: the user id of the vm
"""
# check guest exist in database or not
userid = userid.upper()
if not self._vmops.check_guests_exist_in_db(userid, raise_exc=False):
if zvmutils.check_userid_exist(userid):
LOG.error("Guest '%s' does not exist in guests database" %
userid)
raise exception.SDKObjectNotExistError(
obj_desc=("Guest '%s'" % userid), modID='guest')
else:
LOG.debug("The guest %s does not exist." % userid)
return
action = "delete guest '%s'" % userid
with zvmutils.log_and_reraise_sdkbase_error(action):
return self._vmops.delete_vm(userid) | Delete guest.
:param userid: the user id of the vm | entailment |
def guest_inspect_stats(self, userid_list):
"""Get the statistics including cpu and mem of the guests
:param userid_list: a single userid string or a list of guest userids
:returns: dictionary describing the cpu statistics of the vm
in the form {'UID1':
{
'guest_cpus': xx,
'used_cpu_time_us': xx,
'elapsed_cpu_time_us': xx,
'min_cpu_count': xx,
'max_cpu_limit': xx,
'samples_cpu_in_use': xx,
'samples_cpu_delay': xx,
'used_mem_kb': xx,
'max_mem_kb': xx,
'min_mem_kb': xx,
'shared_mem_kb': xx
},
'UID2':
{
'guest_cpus': xx,
'used_cpu_time_us': xx,
'elapsed_cpu_time_us': xx,
'min_cpu_count': xx,
'max_cpu_limit': xx,
'samples_cpu_in_use': xx,
'samples_cpu_delay': xx,
'used_mem_kb': xx,
'max_mem_kb': xx,
'min_mem_kb': xx,
'shared_mem_kb': xx
}
}
for the guests that are shutdown or not exist, no data
returned in the dictionary
"""
if not isinstance(userid_list, list):
userid_list = [userid_list]
action = "get the statistics of guest '%s'" % str(userid_list)
with zvmutils.log_and_reraise_sdkbase_error(action):
return self._monitor.inspect_stats(userid_list) | Get the statistics including cpu and mem of the guests
:param userid_list: a single userid string or a list of guest userids
:returns: dictionary describing the cpu statistics of the vm
in the form {'UID1':
{
'guest_cpus': xx,
'used_cpu_time_us': xx,
'elapsed_cpu_time_us': xx,
'min_cpu_count': xx,
'max_cpu_limit': xx,
'samples_cpu_in_use': xx,
'samples_cpu_delay': xx,
'used_mem_kb': xx,
'max_mem_kb': xx,
'min_mem_kb': xx,
'shared_mem_kb': xx
},
'UID2':
{
'guest_cpus': xx,
'used_cpu_time_us': xx,
'elapsed_cpu_time_us': xx,
'min_cpu_count': xx,
'max_cpu_limit': xx,
'samples_cpu_in_use': xx,
'samples_cpu_delay': xx,
'used_mem_kb': xx,
'max_mem_kb': xx,
'min_mem_kb': xx,
'shared_mem_kb': xx
}
}
for the guests that are shutdown or not exist, no data
returned in the dictionary | entailment |
def guest_inspect_vnics(self, userid_list):
"""Get the vnics statistics of the guest virtual machines
:param userid_list: a single userid string or a list of guest userids
:returns: dictionary describing the vnics statistics of the vm
in the form
{'UID1':
[{
'vswitch_name': xx,
'nic_vdev': xx,
'nic_fr_rx': xx,
'nic_fr_tx': xx,
'nic_fr_rx_dsc': xx,
'nic_fr_tx_dsc': xx,
'nic_fr_rx_err': xx,
'nic_fr_tx_err': xx,
'nic_rx': xx,
'nic_tx': xx
},
],
'UID2':
[{
'vswitch_name': xx,
'nic_vdev': xx,
'nic_fr_rx': xx,
'nic_fr_tx': xx,
'nic_fr_rx_dsc': xx,
'nic_fr_tx_dsc': xx,
'nic_fr_rx_err': xx,
'nic_fr_tx_err': xx,
'nic_rx': xx,
'nic_tx': xx
},
]
}
for the guests that are shutdown or not exist, no data
returned in the dictionary
"""
if not isinstance(userid_list, list):
userid_list = [userid_list]
action = "get the vnics statistics of guest '%s'" % str(userid_list)
with zvmutils.log_and_reraise_sdkbase_error(action):
return self._monitor.inspect_vnics(userid_list) | Get the vnics statistics of the guest virtual machines
:param userid_list: a single userid string or a list of guest userids
:returns: dictionary describing the vnics statistics of the vm
in the form
{'UID1':
[{
'vswitch_name': xx,
'nic_vdev': xx,
'nic_fr_rx': xx,
'nic_fr_tx': xx,
'nic_fr_rx_dsc': xx,
'nic_fr_tx_dsc': xx,
'nic_fr_rx_err': xx,
'nic_fr_tx_err': xx,
'nic_rx': xx,
'nic_tx': xx
},
],
'UID2':
[{
'vswitch_name': xx,
'nic_vdev': xx,
'nic_fr_rx': xx,
'nic_fr_tx': xx,
'nic_fr_rx_dsc': xx,
'nic_fr_tx_dsc': xx,
'nic_fr_rx_err': xx,
'nic_fr_tx_err': xx,
'nic_rx': xx,
'nic_tx': xx
},
]
}
for the guests that are shutdown or not exist, no data
returned in the dictionary | entailment |
def vswitch_set_vlan_id_for_user(self, vswitch_name, userid, vlan_id):
"""Set vlan id for user when connecting to the vswitch
:param str vswitch_name: the name of the vswitch
:param str userid: the user id of the vm
:param int vlan_id: the VLAN id
"""
self._networkops.set_vswitch_port_vlan_id(vswitch_name,
userid, vlan_id) | Set vlan id for user when connecting to the vswitch
:param str vswitch_name: the name of the vswitch
:param str userid: the user id of the vm
:param int vlan_id: the VLAN id | entailment |
def guest_config_minidisks(self, userid, disk_info):
"""Punch the script that used to process additional disks to vm
:param str userid: the user id of the vm
:param disk_info: a list contains disks info for the guest. It
contains dictionaries that describes disk info for each disk.
Each dictionary has 3 keys, format is required, vdev and
mntdir are optional. For example, if vdev is not specified, it
will start from the next vdev of CONF.zvm.user_root_vdev, eg.
if CONF.zvm.user_root_vdev is 0100, zvmsdk will use 0101 as the
vdev for first additional disk in disk_info, and if mntdir is
not specified, zvmsdk will use /mnt/ephemeral0 as the mount
point of first additional disk
Here are some examples:
[{'vdev': '0101',
'format': 'ext3',
'mntdir': '/mnt/ephemeral0'}]
In this case, the zvmsdk will treat 0101 as additional disk's
vdev, and it's formatted with ext3, and will be mounted to
/mnt/ephemeral0
[{'format': 'ext3'},
{'format': 'ext4'}]
In this case, if CONF.zvm.user_root_vdev is 0100, zvmsdk will
configure the first additional disk as 0101, mount it to
/mnt/ephemeral0 with ext3, and configure the second additional
disk 0102, mount it to /mnt/ephemeral1 with ext4.
"""
action = "config disks for userid '%s'" % userid
with zvmutils.log_and_reraise_sdkbase_error(action):
self._vmops.guest_config_minidisks(userid, disk_info) | Punch the script that used to process additional disks to vm
:param str userid: the user id of the vm
:param disk_info: a list contains disks info for the guest. It
contains dictionaries that describes disk info for each disk.
Each dictionary has 3 keys, format is required, vdev and
mntdir are optional. For example, if vdev is not specified, it
will start from the next vdev of CONF.zvm.user_root_vdev, eg.
if CONF.zvm.user_root_vdev is 0100, zvmsdk will use 0101 as the
vdev for first additional disk in disk_info, and if mntdir is
not specified, zvmsdk will use /mnt/ephemeral0 as the mount
point of first additional disk
Here are some examples:
[{'vdev': '0101',
'format': 'ext3',
'mntdir': '/mnt/ephemeral0'}]
In this case, the zvmsdk will treat 0101 as additional disk's
vdev, and it's formatted with ext3, and will be mounted to
/mnt/ephemeral0
[{'format': 'ext3'},
{'format': 'ext4'}]
In this case, if CONF.zvm.user_root_vdev is 0100, zvmsdk will
configure the first additional disk as 0101, mount it to
/mnt/ephemeral0 with ext3, and configure the second additional
disk 0102, mount it to /mnt/ephemeral1 with ext4. | entailment |
def vswitch_set(self, vswitch_name, **kwargs):
"""Change the configuration of an existing virtual switch
:param str vswitch_name: the name of the virtual switch
:param dict kwargs:
- grant_userid=<value>:
A userid to be added to the access list
- user_vlan_id=<value>:
user VLAN ID. Support following ways:
1. As single values between 1 and 4094. A maximum of four
values may be specified, separated by blanks.
Example: 1010 2020 3030 4040
2. As a range of two numbers, separated by a dash (-).
A maximum of two ranges may be specified.
Example: 10-12 20-22
- revoke_userid=<value>:
A userid to be removed from the access list
- real_device_address=<value>:
The real device address or the real device address and
OSA Express port number of a QDIO OSA
Express device to be used to create the switch to the virtual
adapter. If using a real device and an OSA Express port number,
specify the real device number followed by a period(.),
the letter 'P' (or 'p'), followed by the port number as a
hexadecimal number. A maximum of three device addresses,
all 1-7 characters in length, may be specified, delimited by
blanks. 'None' may also be specified
- port_name=<value>:
The name used to identify the OSA Expanded
adapter. A maximum of three port names, all 1-8 characters in
length, may be specified, delimited by blanks.
- controller_name=<value>:
One of the following:
1. The userid controlling the real device. A maximum of eight
userids, all 1-8 characters in length, may be specified,
delimited by blanks.
2. '*': Specifies that any available controller may be used
- connection_value=<value>:
One of the following values:
CONnect: Activate the real device connection.
DISCONnect: Do not activate the real device connection.
- queue_memory_limit=<value>:
A number between 1 and 8
specifying the QDIO buffer size in megabytes.
- routing_value=<value>:
Specifies whether the OSA-Express QDIO
device will act as a router to the virtual switch, as follows:
NONrouter: The OSA-Express device identified in
real_device_address= will not act as a router to the vswitch
PRIrouter: The OSA-Express device identified in
real_device_address= will act as a primary router to the
vswitch
- port_type=<value>:
Specifies the port type, ACCESS or TRUNK
- persist=<value>:
one of the following values:
NO: The vswitch is updated on the active system, but is not
updated in the permanent configuration for the system.
YES: The vswitch is updated on the active system and also in
the permanent configuration for the system.
If not specified, the default is NO.
- gvrp_value=<value>:
GVRP or NOGVRP
- mac_id=<value>:
A unique identifier (up to six hexadecimal
digits) used as part of the vswitch MAC address
- uplink=<value>:
One of the following:
NO: The port being enabled is not the vswitch's UPLINK port.
YES: The port being enabled is the vswitch's UPLINK port.
- nic_userid=<value>:
One of the following:
1. The userid of the port to/from which the UPLINK port will
be connected or disconnected. If a userid is specified,
then nic_vdev= must also be specified
2. '*': Disconnect the currently connected guest port to/from
the special virtual switch UPLINK port. (This is equivalent
to specifying NIC NONE on CP SET VSWITCH).
- nic_vdev=<value>:
The virtual device to/from which the the
UPLINK port will be connected/disconnected. If this value is
specified, nic_userid= must also be specified, with a userid.
- lacp=<value>:
One of the following values:
ACTIVE: Indicates that the virtual switch will initiate
negotiations with the physical switch via the link aggregation
control protocol (LACP) and will respond to LACP packets sent
by the physical switch.
INACTIVE: Indicates that aggregation is to be performed,
but without LACP.
- Interval=<value>:
The interval to be used by the control
program (CP) when doing load balancing of conversations across
multiple links in the group. This can be any of the following
values:
1 - 9990: Indicates the number of seconds between load
balancing operations across the link aggregation group.
OFF: Indicates that no load balancing is done.
- group_rdev=<value>:
The real device address or the real device
address and OSA Express port number of a QDIO OSA Express
devcie to be affected within the link aggregation group
associated with this vswitch. If using a real device and an OSA
Express port number, specify the real device number followed
by a period (.), the letter 'P' (or 'p'), followed by the port
number as a hexadecimal number. A maximum of eight device
addresses all 1-7 characters in length, may be specified,
delimited by blanks.
Note: If a real device address is specified, this device will
be added to the link aggregation group associated with this
vswitch. (The link aggregation group will be created if it does
not already exist.)
- iptimeout=<value>:
A number between 1 and 240 specifying the
length of time in minutes that a remote IP address table entry
remains in the IP address table for the virtual switch.
- port_isolation=<value>:
ON or OFF
- promiscuous=<value>:
One of the following:
NO: The userid or port on the grant is not authorized to use
the vswitch in promiscuous mode
YES: The userid or port on the grant is authorized to use the
vswitch in promiscuous mode.
- MAC_protect=<value>:
ON, OFF or UNSPECified
- VLAN_counters=<value>:
ON or OFF
"""
for k in kwargs.keys():
if k not in constants.SET_VSWITCH_KEYWORDS:
errmsg = ('API vswitch_set: Invalid keyword %s' % k)
raise exception.SDKInvalidInputFormat(msg=errmsg)
self._networkops.set_vswitch(vswitch_name, **kwargs) | Change the configuration of an existing virtual switch
:param str vswitch_name: the name of the virtual switch
:param dict kwargs:
- grant_userid=<value>:
A userid to be added to the access list
- user_vlan_id=<value>:
user VLAN ID. Support following ways:
1. As single values between 1 and 4094. A maximum of four
values may be specified, separated by blanks.
Example: 1010 2020 3030 4040
2. As a range of two numbers, separated by a dash (-).
A maximum of two ranges may be specified.
Example: 10-12 20-22
- revoke_userid=<value>:
A userid to be removed from the access list
- real_device_address=<value>:
The real device address or the real device address and
OSA Express port number of a QDIO OSA
Express device to be used to create the switch to the virtual
adapter. If using a real device and an OSA Express port number,
specify the real device number followed by a period(.),
the letter 'P' (or 'p'), followed by the port number as a
hexadecimal number. A maximum of three device addresses,
all 1-7 characters in length, may be specified, delimited by
blanks. 'None' may also be specified
- port_name=<value>:
The name used to identify the OSA Expanded
adapter. A maximum of three port names, all 1-8 characters in
length, may be specified, delimited by blanks.
- controller_name=<value>:
One of the following:
1. The userid controlling the real device. A maximum of eight
userids, all 1-8 characters in length, may be specified,
delimited by blanks.
2. '*': Specifies that any available controller may be used
- connection_value=<value>:
One of the following values:
CONnect: Activate the real device connection.
DISCONnect: Do not activate the real device connection.
- queue_memory_limit=<value>:
A number between 1 and 8
specifying the QDIO buffer size in megabytes.
- routing_value=<value>:
Specifies whether the OSA-Express QDIO
device will act as a router to the virtual switch, as follows:
NONrouter: The OSA-Express device identified in
real_device_address= will not act as a router to the vswitch
PRIrouter: The OSA-Express device identified in
real_device_address= will act as a primary router to the
vswitch
- port_type=<value>:
Specifies the port type, ACCESS or TRUNK
- persist=<value>:
one of the following values:
NO: The vswitch is updated on the active system, but is not
updated in the permanent configuration for the system.
YES: The vswitch is updated on the active system and also in
the permanent configuration for the system.
If not specified, the default is NO.
- gvrp_value=<value>:
GVRP or NOGVRP
- mac_id=<value>:
A unique identifier (up to six hexadecimal
digits) used as part of the vswitch MAC address
- uplink=<value>:
One of the following:
NO: The port being enabled is not the vswitch's UPLINK port.
YES: The port being enabled is the vswitch's UPLINK port.
- nic_userid=<value>:
One of the following:
1. The userid of the port to/from which the UPLINK port will
be connected or disconnected. If a userid is specified,
then nic_vdev= must also be specified
2. '*': Disconnect the currently connected guest port to/from
the special virtual switch UPLINK port. (This is equivalent
to specifying NIC NONE on CP SET VSWITCH).
- nic_vdev=<value>:
The virtual device to/from which the the
UPLINK port will be connected/disconnected. If this value is
specified, nic_userid= must also be specified, with a userid.
- lacp=<value>:
One of the following values:
ACTIVE: Indicates that the virtual switch will initiate
negotiations with the physical switch via the link aggregation
control protocol (LACP) and will respond to LACP packets sent
by the physical switch.
INACTIVE: Indicates that aggregation is to be performed,
but without LACP.
- Interval=<value>:
The interval to be used by the control
program (CP) when doing load balancing of conversations across
multiple links in the group. This can be any of the following
values:
1 - 9990: Indicates the number of seconds between load
balancing operations across the link aggregation group.
OFF: Indicates that no load balancing is done.
- group_rdev=<value>:
The real device address or the real device
address and OSA Express port number of a QDIO OSA Express
devcie to be affected within the link aggregation group
associated with this vswitch. If using a real device and an OSA
Express port number, specify the real device number followed
by a period (.), the letter 'P' (or 'p'), followed by the port
number as a hexadecimal number. A maximum of eight device
addresses all 1-7 characters in length, may be specified,
delimited by blanks.
Note: If a real device address is specified, this device will
be added to the link aggregation group associated with this
vswitch. (The link aggregation group will be created if it does
not already exist.)
- iptimeout=<value>:
A number between 1 and 240 specifying the
length of time in minutes that a remote IP address table entry
remains in the IP address table for the virtual switch.
- port_isolation=<value>:
ON or OFF
- promiscuous=<value>:
One of the following:
NO: The userid or port on the grant is not authorized to use
the vswitch in promiscuous mode
YES: The userid or port on the grant is authorized to use the
vswitch in promiscuous mode.
- MAC_protect=<value>:
ON, OFF or UNSPECified
- VLAN_counters=<value>:
ON or OFF | entailment |
def vswitch_delete(self, vswitch_name, persist=True):
""" Delete vswitch.
:param str name: the vswitch name
:param bool persist: whether delete the vswitch from the permanent
configuration for the system
"""
self._networkops.delete_vswitch(vswitch_name, persist) | Delete vswitch.
:param str name: the vswitch name
:param bool persist: whether delete the vswitch from the permanent
configuration for the system | entailment |
def guest_create_network_interface(self, userid, os_version,
guest_networks, active=False):
""" Create network interface(s) for the guest inux system. It will
create the nic for the guest, add NICDEF record into the user
direct. It will also construct network interface configuration
files and punch the files to the guest. These files will take
effect when initializing and configure guest.
:param str userid: the user id of the guest
:param str os_version: operating system version of the guest
:param list guest_networks: a list of network info for the guest.
It has one dictionary that contain some of the below keys for
each network, the format is:
{'ip_addr': (str) IP address or None,
'dns_addr': (list) dns addresses or None,
'gateway_addr': (str) gateway address or None,
'cidr': (str) cidr format,
'nic_vdev': (str)nic VDEV, 1- to 4- hexadecimal digits or None,
'nic_id': (str) nic identifier or None,
'mac_addr': (str) mac address or None, it is only be used when
changing the guest's user direct. Format should be
xx:xx:xx:xx:xx:xx, and x is a hexadecimal digit
'osa_device': (str) OSA address or None}
Example for guest_networks:
[{'ip_addr': '192.168.95.10',
'dns_addr': ['9.0.2.1', '9.0.3.1'],
'gateway_addr': '192.168.95.1',
'cidr': "192.168.95.0/24",
'nic_vdev': '1000',
'mac_addr': '02:00:00:12:34:56'},
{'ip_addr': '192.168.96.10',
'dns_addr': ['9.0.2.1', '9.0.3.1'],
'gateway_addr': '192.168.96.1',
'cidr': "192.168.96.0/24",
'nic_vdev': '1003}]
:param bool active: whether add a nic on active guest system
:returns: guest_networks list, including nic_vdev for each network
:rtype: list
"""
if len(guest_networks) == 0:
errmsg = ("API guest_create_network_interface: "
"Network information is required but not provided")
raise exception.SDKInvalidInputFormat(msg=errmsg)
for network in guest_networks:
vdev = nic_id = mac_addr = ip_addr = OSA = None
if 'nic_vdev' in network.keys():
vdev = network['nic_vdev']
if 'osa_device' in network.keys():
OSA = network['osa_device']
if 'nic_id' in network.keys():
nic_id = network['nic_id']
if (('mac_addr' in network.keys()) and
(network['mac_addr'] is not None)):
mac_addr = network['mac_addr']
if not zvmutils.valid_mac_addr(mac_addr):
errmsg = ("API guest_create_network_interface: "
"Invalid mac address, format should be "
"xx:xx:xx:xx:xx:xx, and x is a hexadecimal "
"digit")
raise exception.SDKInvalidInputFormat(msg=errmsg)
if (('ip_addr' in network.keys()) and
(network['ip_addr'] is not None)):
ip_addr = network['ip_addr']
if not netaddr.valid_ipv4(ip_addr):
errmsg = ("API guest_create_network_interface: "
"Invalid management IP address, it should be "
"the value between 0.0.0.0 and 255.255.255.255")
raise exception.SDKInvalidInputFormat(msg=errmsg)
if (('dns_addr' in network.keys()) and
(network['dns_addr'] is not None)):
if not isinstance(network['dns_addr'], list):
raise exception.SDKInvalidInputTypes(
'guest_config_network',
str(list), str(type(network['dns_addr'])))
for dns in network['dns_addr']:
if not netaddr.valid_ipv4(dns):
errmsg = ("API guest_create_network_interface: "
"Invalid dns IP address, it should be the "
"value between 0.0.0.0 and 255.255.255.255")
raise exception.SDKInvalidInputFormat(msg=errmsg)
if (('gateway_addr' in network.keys()) and
(network['gateway_addr'] is not None)):
if not netaddr.valid_ipv4(
network['gateway_addr']):
errmsg = ("API guest_create_network_interface: "
"Invalid gateway IP address, it should be "
"the value between 0.0.0.0 and 255.255.255.255")
raise exception.SDKInvalidInputFormat(msg=errmsg)
if (('cidr' in network.keys()) and
(network['cidr'] is not None)):
if not zvmutils.valid_cidr(network['cidr']):
errmsg = ("API guest_create_network_interface: "
"Invalid CIDR, format should be a.b.c.d/n, and "
"a.b.c.d is IP address, n is the value "
"between 0-32")
raise exception.SDKInvalidInputFormat(msg=errmsg)
try:
if OSA is None:
used_vdev = self._networkops.create_nic(userid, vdev=vdev,
nic_id=nic_id,
mac_addr=mac_addr,
active=active)
else:
used_vdev = self._networkops.dedicate_OSA(userid, OSA,
vdev=vdev,
active=active)
network['nic_vdev'] = used_vdev
except exception.SDKBaseException:
LOG.error(('Failed to create nic on vm %s') % userid)
raise
try:
self._networkops.network_configuration(userid, os_version,
guest_networks,
active=active)
except exception.SDKBaseException:
LOG.error(('Failed to set network configuration file on vm %s') %
userid)
raise
return guest_networks | Create network interface(s) for the guest inux system. It will
create the nic for the guest, add NICDEF record into the user
direct. It will also construct network interface configuration
files and punch the files to the guest. These files will take
effect when initializing and configure guest.
:param str userid: the user id of the guest
:param str os_version: operating system version of the guest
:param list guest_networks: a list of network info for the guest.
It has one dictionary that contain some of the below keys for
each network, the format is:
{'ip_addr': (str) IP address or None,
'dns_addr': (list) dns addresses or None,
'gateway_addr': (str) gateway address or None,
'cidr': (str) cidr format,
'nic_vdev': (str)nic VDEV, 1- to 4- hexadecimal digits or None,
'nic_id': (str) nic identifier or None,
'mac_addr': (str) mac address or None, it is only be used when
changing the guest's user direct. Format should be
xx:xx:xx:xx:xx:xx, and x is a hexadecimal digit
'osa_device': (str) OSA address or None}
Example for guest_networks:
[{'ip_addr': '192.168.95.10',
'dns_addr': ['9.0.2.1', '9.0.3.1'],
'gateway_addr': '192.168.95.1',
'cidr': "192.168.95.0/24",
'nic_vdev': '1000',
'mac_addr': '02:00:00:12:34:56'},
{'ip_addr': '192.168.96.10',
'dns_addr': ['9.0.2.1', '9.0.3.1'],
'gateway_addr': '192.168.96.1',
'cidr': "192.168.96.0/24",
'nic_vdev': '1003}]
:param bool active: whether add a nic on active guest system
:returns: guest_networks list, including nic_vdev for each network
:rtype: list | entailment |
def guests_get_nic_info(self, userid=None, nic_id=None, vswitch=None):
""" Retrieve nic information in the network database according to
the requirements, the nic information will include the guest
name, nic device number, vswitch name that the nic is coupled
to, nic identifier and the comments.
:param str userid: the user id of the vm
:param str nic_id: nic identifier
:param str vswitch: the name of the vswitch
:returns: list describing nic information, format is
[
(userid, interface, vswitch, nic_id, comments),
(userid, interface, vswitch, nic_id, comments)
], such as
[
('VM01', '1000', 'xcatvsw2', '1111-2222', None),
('VM02', '2000', 'xcatvsw3', None, None)
]
:rtype: list
"""
action = "get nic information"
with zvmutils.log_and_reraise_sdkbase_error(action):
return self._networkops.get_nic_info(userid=userid, nic_id=nic_id,
vswitch=vswitch) | Retrieve nic information in the network database according to
the requirements, the nic information will include the guest
name, nic device number, vswitch name that the nic is coupled
to, nic identifier and the comments.
:param str userid: the user id of the vm
:param str nic_id: nic identifier
:param str vswitch: the name of the vswitch
:returns: list describing nic information, format is
[
(userid, interface, vswitch, nic_id, comments),
(userid, interface, vswitch, nic_id, comments)
], such as
[
('VM01', '1000', 'xcatvsw2', '1111-2222', None),
('VM02', '2000', 'xcatvsw3', None, None)
]
:rtype: list | entailment |
def vswitch_query(self, vswitch_name):
"""Check the virtual switch status
:param str vswitch_name: the name of the virtual switch
:returns: Dictionary describing virtual switch info
:rtype: dict
"""
action = "get virtual switch information"
with zvmutils.log_and_reraise_sdkbase_error(action):
return self._networkops.vswitch_query(vswitch_name) | Check the virtual switch status
:param str vswitch_name: the name of the virtual switch
:returns: Dictionary describing virtual switch info
:rtype: dict | entailment |
def guest_delete_network_interface(self, userid, os_version,
vdev, active=False):
""" delete the nic and network configuration for the vm
:param str userid: the user id of the guest
:param str os_version: operating system version of the guest
:param str vdev: nic device number, 1- to 4- hexadecimal digits
:param bool active: whether delete a nic on active guest system
"""
self._networkops.delete_nic(userid, vdev, active=active)
self._networkops.delete_network_configuration(userid, os_version,
vdev, active=active) | delete the nic and network configuration for the vm
:param str userid: the user id of the guest
:param str os_version: operating system version of the guest
:param str vdev: nic device number, 1- to 4- hexadecimal digits
:param bool active: whether delete a nic on active guest system | entailment |
def mock_session_with_fixtures(session, path, url):
"""
Context Manager
Mock the responses with a particular session
to any files found within a static path
:param session: The requests session object
:type session: :class:`requests.Session`
:param path: The path to the fixtures
:type path: ``str``
:param url: The base URL to mock, e.g. http://mock.com, http://
supports a single URL or a list
:type url: ``str`` or ``list``
"""
_orig_adapters = session.adapters
mock_adapter = adapter.Adapter()
session.adapters = OrderedDict()
if isinstance(url, (list, tuple)):
for u in url:
session.mount(u, mock_adapter)
else:
session.mount(url, mock_adapter)
mock_adapter.register_path(path)
yield
session.adapters = _orig_adapters | Context Manager
Mock the responses with a particular session
to any files found within a static path
:param session: The requests session object
:type session: :class:`requests.Session`
:param path: The path to the fixtures
:type path: ``str``
:param url: The base URL to mock, e.g. http://mock.com, http://
supports a single URL or a list
:type url: ``str`` or ``list`` | entailment |
def mock_session_with_class(session, cls, url):
"""
Context Manager
Mock the responses with a particular session
to any private methods for the URLs
:param session: The requests session object
:type session: :class:`requests.Session`
:param cls: The class instance with private methods for URLs
:type cls: ``object``
:param url: The base URL to mock, e.g. http://mock.com, http://
supports a single URL or a list
:type url: ``str`` or ``list``
"""
_orig_adapters = session.adapters
mock_adapter = adapter.ClassAdapter(cls)
session.adapters = OrderedDict()
if isinstance(url, (list, tuple)):
for u in url:
session.mount(u, mock_adapter)
else:
session.mount(url, mock_adapter)
yield
session.adapters = _orig_adapters | Context Manager
Mock the responses with a particular session
to any private methods for the URLs
:param session: The requests session object
:type session: :class:`requests.Session`
:param cls: The class instance with private methods for URLs
:type cls: ``object``
:param url: The base URL to mock, e.g. http://mock.com, http://
supports a single URL or a list
:type url: ``str`` or ``list`` | entailment |
def _fixpath(self, p):
"""Apply tilde expansion and absolutization to a path."""
return os.path.abspath(os.path.expanduser(p)) | Apply tilde expansion and absolutization to a path. | entailment |
def _get_config_dirs(self):
"""Return a list of directories where config files may be located.
following directories are returned::
./
../etc
~/
/etc/zvmsdk/
"""
_cwd = os.path.split(os.path.abspath(__file__))[0]
_pdir = os.path.split(_cwd)[0]
_etcdir = ''.join((_pdir, '/', 'etc/'))
cfg_dirs = [
self._fixpath(_cwd),
self._fixpath('/etc/zvmsdk/'),
self._fixpath('/etc/'),
self._fixpath('~'),
self._fixpath(_etcdir),
]
return [x for x in cfg_dirs if x] | Return a list of directories where config files may be located.
following directories are returned::
./
../etc
~/
/etc/zvmsdk/ | entailment |
def _search_dirs(self, dirs, basename, extension=""):
"""Search a list of directories for a given filename or directory name.
Iterator over the supplied directories, returning the first file
found with the supplied name and extension.
:param dirs: a list of directories
:param basename: the filename
:param extension: the file extension, for example '.conf'
:returns: the path to a matching file, or None
"""
for d in dirs:
path = os.path.join(d, '%s%s' % (basename, extension))
if os.path.exists(path):
return path
return None | Search a list of directories for a given filename or directory name.
Iterator over the supplied directories, returning the first file
found with the supplied name and extension.
:param dirs: a list of directories
:param basename: the filename
:param extension: the file extension, for example '.conf'
:returns: the path to a matching file, or None | entailment |
def find_config_file(self, project=None, extension='.conf'):
"""Return the config file.
:param project: "zvmsdk"
:param extension: the type of the config file
"""
cfg_dirs = self._get_config_dirs()
config_files = self._search_dirs(cfg_dirs, project, extension)
return config_files | Return the config file.
:param project: "zvmsdk"
:param extension: the type of the config file | entailment |
def scrypt_mcf(scrypt, password, salt=None, N=SCRYPT_N, r=SCRYPT_r, p=SCRYPT_p,
prefix=SCRYPT_MCF_PREFIX_DEFAULT):
"""Derives a Modular Crypt Format hash using the scrypt KDF given
Expects the signature:
scrypt(password, salt, N=SCRYPT_N, r=SCRYPT_r, p=SCRYPT_p, olen=64)
If no salt is given, a random salt of 128+ bits is used. (Recommended.)
"""
if isinstance(password, unicode):
password = password.encode('utf8')
elif not isinstance(password, bytes):
raise TypeError('password must be a unicode or byte string')
if salt is not None and not isinstance(salt, bytes):
raise TypeError('salt must be a byte string')
if salt is not None and not (1 <= len(salt) <= 16):
raise ValueError('salt must be 1-16 bytes')
if r > 255:
raise ValueError('scrypt_mcf r out of range [1,255]')
if p > 255:
raise ValueError('scrypt_mcf p out of range [1,255]')
if N > 2**31:
raise ValueError('scrypt_mcf N out of range [2,2**31]')
if b'\0' in password:
raise ValueError('scrypt_mcf password must not contain zero bytes')
if prefix == SCRYPT_MCF_PREFIX_s1:
if salt is None:
salt = os.urandom(16)
hash = scrypt(password, salt, N, r, p)
return _scrypt_mcf_encode_s1(N, r, p, salt, hash)
elif prefix == SCRYPT_MCF_PREFIX_7 or prefix == SCRYPT_MCF_PREFIX_ANY:
if salt is None:
salt = os.urandom(32)
salt = _cb64enc(salt)
hash = scrypt(password, salt, N, r, p, 32)
return _scrypt_mcf_encode_7(N, r, p, salt, hash)
else:
raise ValueError("Unrecognized MCF format") | Derives a Modular Crypt Format hash using the scrypt KDF given
Expects the signature:
scrypt(password, salt, N=SCRYPT_N, r=SCRYPT_r, p=SCRYPT_p, olen=64)
If no salt is given, a random salt of 128+ bits is used. (Recommended.) | entailment |
def scrypt_mcf_check(scrypt, mcf, password):
"""Returns True if the password matches the given MCF hash
Supports both the libscrypt $s1$ format and the $7$ format.
"""
if not isinstance(mcf, bytes):
raise TypeError('MCF must be a byte string')
if isinstance(password, unicode):
password = password.encode('utf8')
elif not isinstance(password, bytes):
raise TypeError('password must be a unicode or byte string')
N, r, p, salt, hash, hlen = _scrypt_mcf_decode(mcf)
h = scrypt(password, salt, N=N, r=r, p=p, olen=hlen)
cmp = 0
for i, j in zip(bytearray(h), bytearray(hash)):
cmp |= i ^ j
return cmp == 0 | Returns True if the password matches the given MCF hash
Supports both the libscrypt $s1$ format and the $7$ format. | entailment |
def new_plugin(odir, py_name=None, version='0.0.1.dev0',
description='New plugin'):
"""
Create a new plugin for the psyplot package
Parameters
----------
odir: str
The name of the directory where the data will be copied to. The
directory must not exist! The name of the directory also defines the
name of the package.
py_name: str
The name of the python package. If None, the basename of `odir` is used
(and ``'-'`` is replaced by ``'_'``)
version: str
The version of the package
description: str
The description of the plugin"""
name = osp.basename(odir)
if py_name is None:
py_name = name.replace('-', '_')
src = osp.join(osp.dirname(__file__), 'plugin-template-files')
# copy the source files
shutil.copytree(src, odir)
os.rename(osp.join(odir, 'plugin_template'), osp.join(odir, py_name))
replacements = {'PLUGIN_NAME': name,
'PLUGIN_PYNAME': py_name,
'PLUGIN_VERSION': version,
'PLUGIN_DESC': description,
}
files = [
'README.md',
'setup.py',
osp.join(py_name, 'plugin.py'),
osp.join(py_name, 'plotters.py'),
osp.join(py_name, '__init__.py'),
]
for fname in files:
with open(osp.join(odir, fname)) as f:
s = f.read()
for key, val in replacements.items():
s = s.replace(key, val)
with open(osp.join(odir, fname), 'w') as f:
f.write(s) | Create a new plugin for the psyplot package
Parameters
----------
odir: str
The name of the directory where the data will be copied to. The
directory must not exist! The name of the directory also defines the
name of the package.
py_name: str
The name of the python package. If None, the basename of `odir` is used
(and ``'-'`` is replaced by ``'_'``)
version: str
The version of the package
description: str
The description of the plugin | entailment |
def get_versions(requirements=True, key=None):
"""
Get the version information for psyplot, the plugins and its requirements
Parameters
----------
requirements: bool
If True, the requirements of the plugins and psyplot are investigated
key: func
A function that determines whether a plugin shall be considererd or
not. The function must take a single argument, that is the name of the
plugin as string, and must return True (import the plugin) or False
(skip the plugin). If None, all plugins are imported
Returns
-------
dict
A mapping from ``'psyplot'``/the plugin names to a dictionary with the
``'version'`` key and the corresponding version is returned. If
`requirements` is True, it also contains a mapping from
``'requirements'`` a dictionary with the versions
Examples
--------
Using the built-in JSON module, we get something like
.. code-block:: python
import json
print(json.dumps(psyplot.get_versions(), indent=4))
{
"psy_simple.plugin": {
"version": "1.0.0.dev0"
},
"psyplot": {
"version": "1.0.0.dev0",
"requirements": {
"matplotlib": "1.5.3",
"numpy": "1.11.3",
"pandas": "0.19.2",
"xarray": "0.9.1"
}
},
"psy_maps.plugin": {
"version": "1.0.0.dev0",
"requirements": {
"cartopy": "0.15.0"
}
}
}
"""
from pkg_resources import iter_entry_points
ret = {'psyplot': _get_versions(requirements)}
for ep in iter_entry_points(group='psyplot', name='plugin'):
if str(ep) in rcParams._plugins:
logger.debug('Loading entrypoint %s', ep)
if key is not None and not key(ep.module_name):
continue
mod = ep.load()
try:
ret[str(ep.module_name)] = mod.get_versions(requirements)
except AttributeError:
ret[str(ep.module_name)] = {
'version': getattr(mod, 'plugin_version',
getattr(mod, '__version__', ''))}
if key is None:
try:
import psyplot_gui
except ImportError:
pass
else:
ret['psyplot_gui'] = psyplot_gui.get_versions(requirements)
return ret | Get the version information for psyplot, the plugins and its requirements
Parameters
----------
requirements: bool
If True, the requirements of the plugins and psyplot are investigated
key: func
A function that determines whether a plugin shall be considererd or
not. The function must take a single argument, that is the name of the
plugin as string, and must return True (import the plugin) or False
(skip the plugin). If None, all plugins are imported
Returns
-------
dict
A mapping from ``'psyplot'``/the plugin names to a dictionary with the
``'version'`` key and the corresponding version is returned. If
`requirements` is True, it also contains a mapping from
``'requirements'`` a dictionary with the versions
Examples
--------
Using the built-in JSON module, we get something like
.. code-block:: python
import json
print(json.dumps(psyplot.get_versions(), indent=4))
{
"psy_simple.plugin": {
"version": "1.0.0.dev0"
},
"psyplot": {
"version": "1.0.0.dev0",
"requirements": {
"matplotlib": "1.5.3",
"numpy": "1.11.3",
"pandas": "0.19.2",
"xarray": "0.9.1"
}
},
"psy_maps.plugin": {
"version": "1.0.0.dev0",
"requirements": {
"cartopy": "0.15.0"
}
}
} | entailment |
def switch_delete_record_for_userid(self, userid):
"""Remove userid switch record from switch table."""
with get_network_conn() as conn:
conn.execute("DELETE FROM switch WHERE userid=?",
(userid,))
LOG.debug("Switch record for user %s is removed from "
"switch table" % userid) | Remove userid switch record from switch table. | entailment |
def switch_delete_record_for_nic(self, userid, interface):
"""Remove userid switch record from switch table."""
with get_network_conn() as conn:
conn.execute("DELETE FROM switch WHERE userid=? and interface=?",
(userid, interface))
LOG.debug("Switch record for user %s with nic %s is removed from "
"switch table" % (userid, interface)) | Remove userid switch record from switch table. | entailment |
def switch_add_record(self, userid, interface, port=None,
switch=None, comments=None):
"""Add userid and nic name address into switch table."""
with get_network_conn() as conn:
conn.execute("INSERT INTO switch VALUES (?, ?, ?, ?, ?)",
(userid, interface, switch, port, comments))
LOG.debug("New record in the switch table: user %s, "
"nic %s, port %s" %
(userid, interface, port)) | Add userid and nic name address into switch table. | entailment |
def switch_update_record_with_switch(self, userid, interface,
switch=None):
"""Update information in switch table."""
if not self._get_switch_by_user_interface(userid, interface):
msg = "User %s with nic %s does not exist in DB" % (userid,
interface)
LOG.error(msg)
obj_desc = ('User %s with nic %s' % (userid, interface))
raise exception.SDKObjectNotExistError(obj_desc,
modID=self._module_id)
if switch is not None:
with get_network_conn() as conn:
conn.execute("UPDATE switch SET switch=? "
"WHERE userid=? and interface=?",
(switch, userid, interface))
LOG.debug("Set switch to %s for user %s with nic %s "
"in switch table" %
(switch, userid, interface))
else:
with get_network_conn() as conn:
conn.execute("UPDATE switch SET switch=NULL "
"WHERE userid=? and interface=?",
(userid, interface))
LOG.debug("Set switch to None for user %s with nic %s "
"in switch table" %
(userid, interface)) | Update information in switch table. | entailment |
def image_query_record(self, imagename=None):
"""Query the image record from database, if imagename is None, all
of the image records will be returned, otherwise only the specified
image record will be returned."""
if imagename:
with get_image_conn() as conn:
result = conn.execute("SELECT * FROM image WHERE "
"imagename=?", (imagename,))
image_list = result.fetchall()
if not image_list:
obj_desc = "Image with name: %s" % imagename
raise exception.SDKObjectNotExistError(obj_desc=obj_desc,
modID=self._module_id)
else:
with get_image_conn() as conn:
result = conn.execute("SELECT * FROM image")
image_list = result.fetchall()
# Map each image record to be a dict, with the key is the field name in
# image DB
image_keys_list = ['imagename', 'imageosdistro', 'md5sum',
'disk_size_units', 'image_size_in_bytes', 'type',
'comments']
image_result = []
for item in image_list:
image_item = dict(zip(image_keys_list, item))
image_result.append(image_item)
return image_result | Query the image record from database, if imagename is None, all
of the image records will be returned, otherwise only the specified
image record will be returned. | entailment |
def get_comments_by_userid(self, userid):
""" Get comments record.
output should be like: {'k1': 'v1', 'k2': 'v2'}'
"""
userid = userid
with get_guest_conn() as conn:
res = conn.execute("SELECT comments FROM guests "
"WHERE userid=?", (userid,))
result = res.fetchall()
comments = {}
if result[0][0]:
comments = json.loads(result[0][0])
return comments | Get comments record.
output should be like: {'k1': 'v1', 'k2': 'v2'}' | entailment |
def get_metadata_by_userid(self, userid):
"""get metadata record.
output should be like: "a=1,b=2,c=3"
"""
userid = userid
with get_guest_conn() as conn:
res = conn.execute("SELECT * FROM guests "
"WHERE userid=?", (userid,))
guest = res.fetchall()
if len(guest) == 1:
return guest[0][2]
elif len(guest) == 0:
LOG.debug("Guest with userid: %s not found from DB!" % userid)
return ''
else:
msg = "Guest with userid: %s have multiple records!" % userid
LOG.error(msg)
raise exception.SDKInternalError(msg=msg, modID=self._module_id) | get metadata record.
output should be like: "a=1,b=2,c=3" | entailment |
def transfer_metadata_to_dict(self, meta):
"""transfer str to dict.
output should be like: {'a':1, 'b':2, 'c':3}
"""
dic = {}
arr = meta.strip(' ,').split(',')
for i in arr:
temp = i.split('=')
key = temp[0].strip()
value = temp[1].strip()
dic[key] = value
return dic | transfer str to dict.
output should be like: {'a':1, 'b':2, 'c':3} | entailment |
def face_index(vertices):
"""Takes an MxNx3 array and returns a 2D vertices and MxN face_indices arrays"""
new_verts = []
face_indices = []
for wall in vertices:
face_wall = []
for vert in wall:
if new_verts:
if not np.isclose(vert, new_verts).all(axis=1).any():
new_verts.append(vert)
else:
new_verts.append(vert)
face_index = np.where(np.isclose(vert, new_verts).all(axis=1))[0][0]
face_wall.append(face_index)
face_indices.append(face_wall)
return np.array(new_verts), np.array(face_indices) | Takes an MxNx3 array and returns a 2D vertices and MxN face_indices arrays | entailment |
def fan_triangulate(indices):
"""Return an array of vertices in triangular order using a fan triangulation algorithm."""
if len(indices[0]) != 4:
raise ValueError("Assumes working with a sequence of quad indices")
new_indices = []
for face in indices:
new_indices.extend([face[:-1], face[1:]])
return np.array(new_indices) | Return an array of vertices in triangular order using a fan triangulation algorithm. | entailment |
def from_dicts(cls, mesh_name, vert_dict, normal_dict):
"""Returns a wavefront .obj string using pre-triangulated vertex dict and normal dict as reference."""
# Put header in string
wavefront_str = "o {name}\n".format(name=mesh_name)
# Write Vertex data from vert_dict
for wall in vert_dict:
for vert in vert_dict[wall]:
wavefront_str += "v {0} {1} {2}\n".format(*vert)
# Write (false) UV Texture data
wavefront_str += "vt 1.0 1.0\n"
# Write Normal data from normal_dict
for wall, norm in normal_dict.items():
wavefront_str += "vn {0} {1} {2}\n".format(*norm)
# Write Face Indices (1-indexed)
vert_idx = 0
for wall in vert_dict:
for _ in range(0, len(vert_dict[wall]), 3):
wavefront_str += 'f '
for vert in range(3): # 3 vertices in each face
vert_idx += 1
wavefront_str += "{v}/1/{n} ".format(v=vert_idx, n=wall+1)
wavefront_str = wavefront_str[:-1] + '\n' # Cutoff trailing space and add a newline.
# Return Wavefront string
return WavefrontWriter(string=wavefront_str) | Returns a wavefront .obj string using pre-triangulated vertex dict and normal dict as reference. | entailment |
def from_arrays(cls, name, verts, normals, n_verts=3):
"""Returns a wavefront .obj string using pre-triangulated vertex dict and normal dict as reference."""
# Put header in string
wavefront_str = "o {name}\n".format(name=name)
# Write Vertex data from vert_dict
for vert in verts:
wavefront_str += "v {0} {1} {2}\n".format(*vert)
# Write (false) UV Texture data
wavefront_str += "vt 1.0 1.0\n"
for norm in normals:
wavefront_str += "vn {0} {1} {2}\n".format(*norm)
# Write Face Indices (1-indexed)
for wall_idx, vert_indices in enumerate(grouper(n_verts, range(1, len(verts) + 1))):
face_str = 'f '
for idx in vert_indices:
face_str += "{v}/1/{n} ".format(v=idx, n=wall_idx + 1)
wavefront_str += face_str + '\n'
return WavefrontWriter(string=wavefront_str) | Returns a wavefront .obj string using pre-triangulated vertex dict and normal dict as reference. | entailment |
def from_indexed_arrays(cls, name, verts, normals):
"""Takes MxNx3 verts, Mx3 normals to build obj file"""
# Put header in string
wavefront_str = "o {name}\n".format(name=name)
new_verts, face_indices = face_index(verts)
assert new_verts.shape[1] == 3, "verts should be Nx3 array"
assert face_indices.ndim == 2
face_indices = fan_triangulate(face_indices)
# Write Vertex data from vert_dict
for vert in new_verts:
wavefront_str += "v {0} {1} {2}\n".format(*vert)
# Write (false) UV Texture data
wavefront_str += "vt 1.0 1.0\n"
for norm in normals:
wavefront_str += "vn {0} {1} {2}\n".format(*norm)
assert len(face_indices) == len(normals) * 2
for norm_idx, vert_idx, in enumerate(face_indices):
wavefront_str += "f"
for vv in vert_idx:
wavefront_str += " {}/{}/{}".format(vv + 1, 1, (norm_idx // 2) + 1 )
wavefront_str += "\n"
return cls(string=wavefront_str) | Takes MxNx3 verts, Mx3 normals to build obj file | entailment |
def dump(self, f):
"""Write Wavefront data to file. Takes File object or filename."""
try:
f.write(self._data)
except AttributeError:
with open(f, 'w') as wf:
wf.write(self._data) | Write Wavefront data to file. Takes File object or filename. | entailment |
def scrypt(password, salt, N=SCRYPT_N, r=SCRYPT_r, p=SCRYPT_p, olen=64):
"""Returns a key derived using the scrypt key-derivarion function
N must be a power of two larger than 1 but no larger than 2 ** 63 (insane)
r and p must be positive numbers such that r * p < 2 ** 30
The default values are:
N -- 2**14 (~16k)
r -- 8
p -- 1
Memory usage is proportional to N*r. Defaults require about 16 MiB.
Time taken is proportional to N*p. Defaults take <100ms of a recent x86.
The last one differs from libscrypt defaults, but matches the 'interactive'
work factor from the original paper. For long term storage where runtime of
key derivation is not a problem, you could use 16 as in libscrypt or better
yet increase N if memory is plentiful.
"""
check_args(password, salt, N, r, p, olen)
try:
return _scrypt(password=password, salt=salt, N=N, r=r, p=p, buflen=olen)
except:
raise ValueError | Returns a key derived using the scrypt key-derivarion function
N must be a power of two larger than 1 but no larger than 2 ** 63 (insane)
r and p must be positive numbers such that r * p < 2 ** 30
The default values are:
N -- 2**14 (~16k)
r -- 8
p -- 1
Memory usage is proportional to N*r. Defaults require about 16 MiB.
Time taken is proportional to N*p. Defaults take <100ms of a recent x86.
The last one differs from libscrypt defaults, but matches the 'interactive'
work factor from the original paper. For long term storage where runtime of
key derivation is not a problem, you could use 16 as in libscrypt or better
yet increase N if memory is plentiful. | entailment |
def doIt(rh):
"""
Perform the requested function by invoking the subfunction handler.
Input:
Request Handle
Output:
Request Handle updated with parsed input.
Return code - 0: ok, non-zero: error
"""
rh.printSysLog("Enter cmdVM.doIt")
# Show the invocation parameters, if requested.
if 'showParms' in rh.parms and rh.parms['showParms'] is True:
rh.printLn("N", "Invocation parameters: ")
rh.printLn("N", " Routine: cmdVM." +
str(subfuncHandler[rh.subfunction][0]) + "(reqHandle)")
rh.printLn("N", " function: " + rh.function)
rh.printLn("N", " userid: " + rh.userid)
rh.printLn("N", " subfunction: " + rh.subfunction)
rh.printLn("N", " parms{}: ")
for key in rh.parms:
if key != 'showParms':
rh.printLn("N", " " + key + ": " + str(rh.parms[key]))
rh.printLn("N", " ")
# Call the subfunction handler
subfuncHandler[rh.subfunction][1](rh)
rh.printSysLog("Exit cmdVM.doIt, rc: " + str(rh.results['overallRC']))
return rh.results['overallRC'] | Perform the requested function by invoking the subfunction handler.
Input:
Request Handle
Output:
Request Handle updated with parsed input.
Return code - 0: ok, non-zero: error | entailment |
def invokeCmd(rh):
"""
Invoke the command in the virtual machine's operating system.
Input:
Request Handle with the following properties:
function - 'CMDVM'
subfunction - 'CMD'
userid - userid of the virtual machine
parms['cmd'] - Command to send
Output:
Request Handle updated with the results.
Return code - 0: ok, non-zero: error
"""
rh.printSysLog("Enter cmdVM.invokeCmd, userid: " + rh.userid)
results = execCmdThruIUCV(rh, rh.userid, rh.parms['cmd'])
if results['overallRC'] == 0:
rh.printLn("N", results['response'])
else:
rh.printLn("ES", results['response'])
rh.updateResults(results)
rh.printSysLog("Exit cmdVM.invokeCmd, rc: " + str(results['overallRC']))
return results['overallRC'] | Invoke the command in the virtual machine's operating system.
Input:
Request Handle with the following properties:
function - 'CMDVM'
subfunction - 'CMD'
userid - userid of the virtual machine
parms['cmd'] - Command to send
Output:
Request Handle updated with the results.
Return code - 0: ok, non-zero: error | entailment |
def parseCmdline(rh):
"""
Parse the request command input.
Input:
Request Handle
Output:
Request Handle updated with parsed input.
Return code - 0: ok, non-zero: error
"""
rh.printSysLog("Enter cmdVM.parseCmdline")
if rh.totalParms >= 2:
rh.userid = rh.request[1].upper()
else:
# Userid is missing.
msg = msgs.msg['0010'][1] % modId
rh.printLn("ES", msg)
rh.updateResults(msgs.msg['0010'][0])
rh.printSysLog("Exit cmdVM.parseCmdLine, rc: " +
rh.results['overallRC'])
return rh.results['overallRC']
if rh.totalParms == 2:
rh.subfunction = rh.userid
rh.userid = ''
if rh.totalParms >= 3:
rh.subfunction = rh.request[2].upper()
# Verify the subfunction is valid.
if rh.subfunction not in subfuncHandler:
# Subfunction is missing.
subList = ', '.join(sorted(subfuncHandler.keys()))
msg = msgs.msg['0011'][1] % (modId, subList)
rh.printLn("ES", msg)
rh.updateResults(msgs.msg['0011'][0])
# Parse the rest of the command line.
if rh.results['overallRC'] == 0:
rh.argPos = 3 # Begin Parsing at 4th operand
generalUtils.parseCmdline(rh, posOpsList, keyOpsList)
rh.printSysLog("Exit cmdVM.parseCmdLine, rc: " +
str(rh.results['overallRC']))
return rh.results['overallRC'] | Parse the request command input.
Input:
Request Handle
Output:
Request Handle updated with parsed input.
Return code - 0: ok, non-zero: error | entailment |
def _generate_vdev(self, base, offset):
"""Generate virtual device number based on base vdev
:param base: base virtual device number, string of 4 bit hex.
:param offset: offset to base, integer.
"""
vdev = hex(int(base, 16) + offset)[2:]
return vdev.rjust(4, '0') | Generate virtual device number based on base vdev
:param base: base virtual device number, string of 4 bit hex.
:param offset: offset to base, integer. | entailment |
def generate_disk_vdev(self, start_vdev=None, offset=0):
"""Generate virtual device number for disks
:param offset: offset of user_root_vdev.
:return: virtual device number, string of 4 bit hex.
"""
if not start_vdev:
start_vdev = CONF.zvm.user_root_vdev
vdev = self._generate_vdev(start_vdev, offset)
if offset >= 0 and offset < 254:
return vdev
else:
msg = ("Failed to generate disk vdev, invalid virtual device"
"number for disk:%s" % vdev)
LOG.error(msg)
raise exception.SDKGuestOperationError(rs=2, msg=msg) | Generate virtual device number for disks
:param offset: offset of user_root_vdev.
:return: virtual device number, string of 4 bit hex. | entailment |
def add_mdisks(self, userid, disk_list, start_vdev=None):
"""Add disks for the userid
:disks: A list dictionary to describe disk info, for example:
disk: [{'size': '1g',
'format': 'ext3',
'disk_pool': 'ECKD:eckdpool1'}]
"""
for idx, disk in enumerate(disk_list):
if 'vdev' in disk:
# this means user want to create their own device number
vdev = disk['vdev']
else:
vdev = self.generate_disk_vdev(start_vdev=start_vdev,
offset=idx)
self._add_mdisk(userid, disk, vdev)
disk['vdev'] = vdev
if disk.get('disk_pool') is None:
disk['disk_pool'] = CONF.zvm.disk_pool
sizeUpper = disk.get('size').strip().upper()
sizeUnit = sizeUpper[-1]
if sizeUnit != 'G' and sizeUnit != 'M':
sizeValue = sizeUpper
disk_pool = disk.get('disk_pool')
[diskpool_type, diskpool_name] = disk_pool.split(':')
if (diskpool_type.upper() == 'ECKD'):
# Convert the cylinders to bytes
convert = 737280
else:
# Convert the blocks to bytes
convert = 512
byteSize = float(float(int(sizeValue) * convert / 1024) / 1024)
unit = "M"
if (byteSize > 1024):
byteSize = float(byteSize / 1024)
unit = "G"
byteSize = "%.1f" % byteSize
disk['size'] = byteSize + unit
return disk_list | Add disks for the userid
:disks: A list dictionary to describe disk info, for example:
disk: [{'size': '1g',
'format': 'ext3',
'disk_pool': 'ECKD:eckdpool1'}] | entailment |
def dedicate_device(self, userid, vaddr, raddr, mode):
"""dedicate device
:userid: The name of the image obtaining a dedicated device
:vaddr: The virtual device number of the device
:raddr: A real device number to be dedicated or attached
to the specified image
:mode: Specify a 1 if the virtual device is to be in read-only mode.
Otherwise, specify a 0.
"""
# dedicate device to directory entry
self._dedicate_device(userid, vaddr, raddr, mode) | dedicate device
:userid: The name of the image obtaining a dedicated device
:vaddr: The virtual device number of the device
:raddr: A real device number to be dedicated or attached
to the specified image
:mode: Specify a 1 if the virtual device is to be in read-only mode.
Otherwise, specify a 0. | entailment |
def _dedicate_device(self, userid, vaddr, raddr, mode):
"""dedicate device."""
action = 'dedicate'
rd = ('changevm %(uid)s %(act)s %(va)s %(ra)s %(mod)i' %
{'uid': userid, 'act': action,
'va': vaddr, 'ra': raddr, 'mod': mode})
action = "dedicate device to userid '%s'" % userid
with zvmutils.log_and_reraise_smt_request_failed(action):
self._request(rd) | dedicate device. | entailment |
def get_fcp_info_by_status(self, userid, status):
"""get fcp information by the status.
:userid: The name of the image to query fcp info
:status: The status of target fcps. eg:'active', 'free' or 'offline'.
"""
results = self._get_fcp_info_by_status(userid, status)
return results | get fcp information by the status.
:userid: The name of the image to query fcp info
:status: The status of target fcps. eg:'active', 'free' or 'offline'. | entailment |
def _undedicate_device(self, userid, vaddr):
"""undedicate device."""
action = 'undedicate'
rd = ('changevm %(uid)s %(act)s %(va)s' %
{'uid': userid, 'act': action,
'va': vaddr})
action = "undedicate device from userid '%s'" % userid
with zvmutils.log_and_reraise_smt_request_failed(action):
self._request(rd) | undedicate device. | entailment |
def get_image_performance_info(self, userid):
"""Get CPU and memory usage information.
:userid: the zvm userid to be queried
"""
pi_dict = self.image_performance_query([userid])
return pi_dict.get(userid, None) | Get CPU and memory usage information.
:userid: the zvm userid to be queried | entailment |
def _parse_vswitch_inspect_data(self, rd_list):
""" Parse the Virtual_Network_Vswitch_Query_Byte_Stats data to get
inspect data.
"""
def _parse_value(data_list, idx, keyword, offset):
return idx + offset, data_list[idx].rpartition(keyword)[2].strip()
vsw_dict = {}
with zvmutils.expect_invalid_resp_data():
# vswitch count
idx = 0
idx, vsw_count = _parse_value(rd_list, idx, 'vswitch count:', 2)
vsw_dict['vswitch_count'] = int(vsw_count)
# deal with each vswitch data
vsw_dict['vswitches'] = []
for i in range(vsw_dict['vswitch_count']):
vsw_data = {}
# skip vswitch number
idx += 1
# vswitch name
idx, vsw_name = _parse_value(rd_list, idx, 'vswitch name:', 1)
vsw_data['vswitch_name'] = vsw_name
# uplink count
idx, up_count = _parse_value(rd_list, idx, 'uplink count:', 1)
# skip uplink data
idx += int(up_count) * 9
# skip bridge data
idx += 8
# nic count
vsw_data['nics'] = []
idx, nic_count = _parse_value(rd_list, idx, 'nic count:', 1)
nic_count = int(nic_count)
for j in range(nic_count):
nic_data = {}
idx, nic_id = _parse_value(rd_list, idx, 'nic_id:', 1)
userid, toss, vdev = nic_id.partition(' ')
nic_data['userid'] = userid
nic_data['vdev'] = vdev
idx, nic_data['nic_fr_rx'] = _parse_value(rd_list, idx,
'nic_fr_rx:', 1
)
idx, nic_data['nic_fr_rx_dsc'] = _parse_value(rd_list, idx,
'nic_fr_rx_dsc:', 1
)
idx, nic_data['nic_fr_rx_err'] = _parse_value(rd_list, idx,
'nic_fr_rx_err:', 1
)
idx, nic_data['nic_fr_tx'] = _parse_value(rd_list, idx,
'nic_fr_tx:', 1
)
idx, nic_data['nic_fr_tx_dsc'] = _parse_value(rd_list, idx,
'nic_fr_tx_dsc:', 1
)
idx, nic_data['nic_fr_tx_err'] = _parse_value(rd_list, idx,
'nic_fr_tx_err:', 1
)
idx, nic_data['nic_rx'] = _parse_value(rd_list, idx,
'nic_rx:', 1
)
idx, nic_data['nic_tx'] = _parse_value(rd_list, idx,
'nic_tx:', 1
)
vsw_data['nics'].append(nic_data)
# vlan count
idx, vlan_count = _parse_value(rd_list, idx, 'vlan count:', 1)
# skip vlan data
idx += int(vlan_count) * 3
# skip the blank line
idx += 1
vsw_dict['vswitches'].append(vsw_data)
return vsw_dict | Parse the Virtual_Network_Vswitch_Query_Byte_Stats data to get
inspect data. | entailment |
def get_power_state(self, userid):
"""Get power status of a z/VM instance."""
LOG.debug('Querying power stat of %s' % userid)
requestData = "PowerVM " + userid + " status"
action = "query power state of '%s'" % userid
with zvmutils.log_and_reraise_smt_request_failed(action):
results = self._request(requestData)
with zvmutils.expect_invalid_resp_data(results):
status = results['response'][0].partition(': ')[2]
return status | Get power status of a z/VM instance. | entailment |
def guest_start(self, userid):
"""Power on VM."""
requestData = "PowerVM " + userid + " on"
with zvmutils.log_and_reraise_smt_request_failed():
self._request(requestData) | Power on VM. | entailment |
def guest_stop(self, userid, **kwargs):
"""Power off VM."""
requestData = "PowerVM " + userid + " off"
if 'timeout' in kwargs.keys() and kwargs['timeout']:
requestData += ' --maxwait ' + str(kwargs['timeout'])
if 'poll_interval' in kwargs.keys() and kwargs['poll_interval']:
requestData += ' --poll ' + str(kwargs['poll_interval'])
with zvmutils.log_and_reraise_smt_request_failed():
self._request(requestData) | Power off VM. | entailment |
def live_migrate_move(self, userid, destination, parms):
""" moves the specified virtual machine, while it continues to run,
to the specified system within the SSI cluster. """
rd = ('migratevm %(uid)s move --destination %(dest)s ' %
{'uid': userid, 'dest': destination})
if 'maxtotal' in parms:
rd += ('--maxtotal ' + str(parms['maxTotal']))
if 'maxquiesce' in parms:
rd += ('--maxquiesce ' + str(parms['maxquiesce']))
if 'immediate' in parms:
rd += " --immediate"
if 'forcearch' in parms:
rd += " --forcearch"
if 'forcedomain' in parms:
rd += " --forcedomain"
if 'forcestorage' in parms:
rd += " --forcestorage"
action = "move userid '%s' to SSI '%s'" % (userid, destination)
try:
self._request(rd)
except exception.SDKSMTRequestFailed as err:
msg = ''
if action is not None:
msg = "Failed to %s. " % action
msg += "SMT error: %s" % err.format_message()
LOG.error(msg)
raise exception.SDKSMTRequestFailed(err.results, msg) | moves the specified virtual machine, while it continues to run,
to the specified system within the SSI cluster. | entailment |
def create_vm(self, userid, cpu, memory, disk_list, profile,
max_cpu, max_mem, ipl_from, ipl_param, ipl_loadparam):
""" Create VM and add disks if specified. """
rd = ('makevm %(uid)s directory LBYONLY %(mem)im %(pri)s '
'--cpus %(cpu)i --profile %(prof)s --maxCPU %(max_cpu)i '
'--maxMemSize %(max_mem)s --setReservedMem' %
{'uid': userid, 'mem': memory,
'pri': const.ZVM_USER_DEFAULT_PRIVILEGE,
'cpu': cpu, 'prof': profile,
'max_cpu': max_cpu, 'max_mem': max_mem})
if CONF.zvm.default_admin_userid:
rd += (' --logonby "%s"' % CONF.zvm.default_admin_userid)
if (disk_list and 'is_boot_disk' in disk_list[0] and
disk_list[0]['is_boot_disk']):
# we assume at least one disk exist, which means, is_boot_disk
# is true for exactly one disk.
rd += (' --ipl %s' % self._get_ipl_param(ipl_from))
# load param for ipl
if ipl_param:
rd += ' --iplParam %s' % ipl_param
if ipl_loadparam:
rd += ' --iplLoadparam %s' % ipl_loadparam
action = "create userid '%s'" % userid
try:
self._request(rd)
except exception.SDKSMTRequestFailed as err:
if ((err.results['rc'] == 436) and (err.results['rs'] == 4)):
result = "Profile '%s'" % profile
raise exception.SDKObjectNotExistError(obj_desc=result,
modID='guest')
else:
msg = ''
if action is not None:
msg = "Failed to %s. " % action
msg += "SMT error: %s" % err.format_message()
LOG.error(msg)
raise exception.SDKSMTRequestFailed(err.results, msg)
# Add the guest to db immediately after user created
action = "add guest '%s' to database" % userid
with zvmutils.log_and_reraise_sdkbase_error(action):
self._GuestDbOperator.add_guest(userid)
# Continue to add disk
if disk_list:
# Add disks for vm
return self.add_mdisks(userid, disk_list) | Create VM and add disks if specified. | entailment |
def _add_mdisk(self, userid, disk, vdev):
"""Create one disk for userid
NOTE: No read, write and multi password specified, and
access mode default as 'MR'.
"""
size = disk['size']
fmt = disk.get('format', 'ext4')
disk_pool = disk.get('disk_pool') or CONF.zvm.disk_pool
[diskpool_type, diskpool_name] = disk_pool.split(':')
if (diskpool_type.upper() == 'ECKD'):
action = 'add3390'
else:
action = 'add9336'
rd = ' '.join(['changevm', userid, action, diskpool_name,
vdev, size, '--mode MR'])
if fmt and fmt != 'none':
rd += (' --filesystem %s' % fmt.lower())
action = "add mdisk to userid '%s'" % userid
with zvmutils.log_and_reraise_smt_request_failed(action):
self._request(rd) | Create one disk for userid
NOTE: No read, write and multi password specified, and
access mode default as 'MR'. | entailment |
def get_vm_list(self):
"""Get the list of guests that are created by SDK
return userid list"""
action = "list all guests in database"
with zvmutils.log_and_reraise_sdkbase_error(action):
guests_in_db = self._GuestDbOperator.get_guest_list()
guests_migrated = self._GuestDbOperator.get_migrated_guest_list()
# db query return value in tuple (uuid, userid, metadata, comments)
userids_in_db = [g[1].upper() for g in guests_in_db]
userids_migrated = [g[1].upper() for g in guests_migrated]
userid_list = list(set(userids_in_db) - set(userids_migrated))
return userid_list | Get the list of guests that are created by SDK
return userid list | entailment |
def guest_authorize_iucv_client(self, userid, client=None):
"""Punch a script that used to set the authorized client userid in vm
If the guest is in log off status, the change will take effect when
the guest start up at first time.
If the guest is in active status, power off and power on are needed
for the change to take effect.
:param str guest: the user id of the vm
:param str client: the user id of the client that can communicate to
guest using IUCV"""
client = client or zvmutils.get_smt_userid()
iucv_path = "/tmp/" + userid
if not os.path.exists(iucv_path):
os.makedirs(iucv_path)
iucv_auth_file = iucv_path + "/iucvauth.sh"
zvmutils.generate_iucv_authfile(iucv_auth_file, client)
try:
requestData = "ChangeVM " + userid + " punchfile " + \
iucv_auth_file + " --class x"
self._request(requestData)
except exception.SDKSMTRequestFailed as err:
msg = ("Failed to punch IUCV auth file to userid '%s'. SMT error:"
" %s" % (userid, err.format_message()))
LOG.error(msg)
raise exception.SDKSMTRequestFailed(err.results, msg)
finally:
self._pathutils.clean_temp_folder(iucv_path) | Punch a script that used to set the authorized client userid in vm
If the guest is in log off status, the change will take effect when
the guest start up at first time.
If the guest is in active status, power off and power on are needed
for the change to take effect.
:param str guest: the user id of the vm
:param str client: the user id of the client that can communicate to
guest using IUCV | entailment |
def guest_deploy(self, userid, image_name, transportfiles=None,
remotehost=None, vdev=None):
""" Deploy image and punch config driver to target """
# (TODO: add the support of multiple disks deploy)
msg = ('Start to deploy image %(img)s to guest %(vm)s'
% {'img': image_name, 'vm': userid})
LOG.info(msg)
image_file = '/'.join([self._get_image_path_by_name(image_name),
CONF.zvm.user_root_vdev])
# Unpack image file to root disk
vdev = vdev or CONF.zvm.user_root_vdev
cmd = ['sudo', '/opt/zthin/bin/unpackdiskimage', userid, vdev,
image_file]
with zvmutils.expect_and_reraise_internal_error(modID='guest'):
(rc, output) = zvmutils.execute(cmd)
if rc != 0:
err_msg = ("unpackdiskimage failed with return code: %d." % rc)
err_output = ""
output_lines = output.split('\n')
for line in output_lines:
if line.__contains__("ERROR:"):
err_output += ("\\n" + line.strip())
LOG.error(err_msg + err_output)
raise exception.SDKGuestOperationError(rs=3, userid=userid,
unpack_rc=rc,
err=err_output)
# Purge guest reader to clean dirty data
rd = ("changevm %s purgerdr" % userid)
action = "purge reader of '%s'" % userid
with zvmutils.log_and_reraise_smt_request_failed(action):
self._request(rd)
# Punch transport files if specified
if transportfiles:
# Copy transport file to local
msg = ('Start to send customized file to vm %s' % userid)
LOG.info(msg)
try:
tmp_trans_dir = tempfile.mkdtemp()
local_trans = '/'.join([tmp_trans_dir,
os.path.basename(transportfiles)])
if remotehost:
cmd = ["/usr/bin/scp", "-B",
"-P", CONF.zvm.remotehost_sshd_port,
"-o StrictHostKeyChecking=no",
("%s:%s" % (remotehost, transportfiles)),
local_trans]
else:
cmd = ["/usr/bin/cp", transportfiles, local_trans]
with zvmutils.expect_and_reraise_internal_error(modID='guest'):
(rc, output) = zvmutils.execute(cmd)
if rc != 0:
err_msg = ('copy config drive with command %(cmd)s '
'failed with output: %(res)s' %
{'cmd': str(cmd), 'res': output})
LOG.error(err_msg)
raise exception.SDKGuestOperationError(rs=4, userid=userid,
err_info=err_msg)
# Punch config drive to guest userid
rd = ("changevm %(uid)s punchfile %(file)s --class X" %
{'uid': userid, 'file': local_trans})
action = "punch config drive to userid '%s'" % userid
with zvmutils.log_and_reraise_smt_request_failed(action):
self._request(rd)
finally:
# remove the local temp config drive folder
self._pathutils.clean_temp_folder(tmp_trans_dir)
# Authorize iucv client
self.guest_authorize_iucv_client(userid)
# Update os version in guest metadata
# TODO: may should append to old metadata, not replace
image_info = self._ImageDbOperator.image_query_record(image_name)
metadata = 'os_version=%s' % image_info[0]['imageosdistro']
self._GuestDbOperator.update_guest_by_userid(userid, meta=metadata)
msg = ('Deploy image %(img)s to guest %(vm)s disk %(vdev)s'
' successfully' % {'img': image_name, 'vm': userid,
'vdev': vdev})
LOG.info(msg) | Deploy image and punch config driver to target | entailment |
def grant_user_to_vswitch(self, vswitch_name, userid):
"""Set vswitch to grant user."""
smt_userid = zvmutils.get_smt_userid()
requestData = ' '.join((
'SMAPI %s API Virtual_Network_Vswitch_Set_Extended' % smt_userid,
"--operands",
"-k switch_name=%s" % vswitch_name,
"-k grant_userid=%s" % userid,
"-k persist=YES"))
try:
self._request(requestData)
except exception.SDKSMTRequestFailed as err:
LOG.error("Failed to grant user %s to vswitch %s, error: %s"
% (userid, vswitch_name, err.format_message()))
self._set_vswitch_exception(err, vswitch_name) | Set vswitch to grant user. | entailment |
def image_performance_query(self, uid_list):
"""Call Image_Performance_Query to get guest current status.
:uid_list: A list of zvm userids to be queried
"""
if uid_list == []:
return {}
if not isinstance(uid_list, list):
uid_list = [uid_list]
smt_userid = zvmutils.get_smt_userid()
rd = ' '.join((
"SMAPI %s API Image_Performance_Query" % smt_userid,
"--operands",
'-T "%s"' % (' '.join(uid_list)),
"-c %d" % len(uid_list)))
action = "get performance info of userid '%s'" % str(uid_list)
with zvmutils.log_and_reraise_smt_request_failed(action):
results = self._request(rd)
ipq_kws = {
'userid': "Guest name:",
'guest_cpus': "Guest CPUs:",
'used_cpu_time': "Used CPU time:",
'elapsed_cpu_time': "Elapsed time:",
'min_cpu_count': "Minimum CPU count:",
'max_cpu_limit': "Max CPU limit:",
'samples_cpu_in_use': "Samples CPU in use:",
'samples_cpu_delay': "Samples CPU delay:",
'used_memory': "Used memory:",
'max_memory': "Max memory:",
'min_memory': "Minimum memory:",
'shared_memory': "Shared memory:",
}
pi_dict = {}
pi = {}
rpi_list = ('\n'.join(results['response'])).split("\n\n")
for rpi in rpi_list:
try:
pi = zvmutils.translate_response_to_dict(rpi, ipq_kws)
except exception.SDKInternalError as err:
emsg = err.format_message()
# when there is only one userid queried and this userid is
# in 'off'state, the smcli will only returns the queried
# userid number, no valid performance info returned.
if(emsg.__contains__("No value matched with keywords.")):
continue
else:
raise err
for k, v in pi.items():
pi[k] = v.strip('" ')
if pi.get('userid') is not None:
pi_dict[pi['userid']] = pi
return pi_dict | Call Image_Performance_Query to get guest current status.
:uid_list: A list of zvm userids to be queried | entailment |
def system_image_performance_query(self, namelist):
"""Call System_Image_Performance_Query to get guest current status.
:namelist: A namelist that defined in smapi namelist file.
"""
smt_userid = zvmutils.get_smt_userid()
rd = ' '.join((
"SMAPI %s API System_Image_Performance_Query" % smt_userid,
"--operands -T %s" % namelist))
action = "get performance info of namelist '%s'" % namelist
with zvmutils.log_and_reraise_smt_request_failed(action):
results = self._request(rd)
ipq_kws = {
'userid': "Guest name:",
'guest_cpus': "Guest CPUs:",
'used_cpu_time': "Used CPU time:",
'elapsed_cpu_time': "Elapsed time:",
'min_cpu_count': "Minimum CPU count:",
'max_cpu_limit': "Max CPU limit:",
'samples_cpu_in_use': "Samples CPU in use:",
'samples_cpu_delay': "Samples CPU delay:",
'used_memory': "Used memory:",
'max_memory': "Max memory:",
'min_memory': "Minimum memory:",
'shared_memory': "Shared memory:",
}
pi_dict = {}
pi = {}
rpi_list = ('\n'.join(results['response'])).split("\n\n")
for rpi in rpi_list:
try:
pi = zvmutils.translate_response_to_dict(rpi, ipq_kws)
except exception.SDKInternalError as err:
emsg = err.format_message()
# when there is only one userid queried and this userid is
# in 'off'state, the smcli will only returns the queried
# userid number, no valid performance info returned.
if(emsg.__contains__("No value matched with keywords.")):
continue
else:
raise err
for k, v in pi.items():
pi[k] = v.strip('" ')
if pi.get('userid') is not None:
pi_dict[pi['userid']] = pi
return pi_dict | Call System_Image_Performance_Query to get guest current status.
:namelist: A namelist that defined in smapi namelist file. | entailment |
def set_vswitch(self, switch_name, **kwargs):
"""Set vswitch"""
smt_userid = zvmutils.get_smt_userid()
rd = ' '.join((
"SMAPI %s API Virtual_Network_Vswitch_Set_Extended" %
smt_userid,
"--operands",
"-k switch_name=%s" % switch_name))
for k, v in kwargs.items():
rd = ' '.join((rd,
"-k %(key)s=\'%(value)s\'" %
{'key': k, 'value': v}))
try:
self._request(rd)
except exception.SDKSMTRequestFailed as err:
LOG.error("Failed to set vswitch %s, error: %s" %
(switch_name, err.format_message()))
self._set_vswitch_exception(err, switch_name) | Set vswitch | entailment |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.