sentence1 stringlengths 52 3.87M | sentence2 stringlengths 1 47.2k | label stringclasses 1 value |
|---|---|---|
def _couple_nic(self, userid, vdev, vswitch_name,
active=False):
"""Couple NIC to vswitch by adding vswitch into user direct."""
if active:
self._is_active(userid)
msg = ('Start to couple nic device %(vdev)s of guest %(vm)s '
'with vswitch %(vsw)s'
% {'vdev': vdev, 'vm': userid, 'vsw': vswitch_name})
LOG.info(msg)
requestData = ' '.join((
'SMAPI %s' % userid,
"API Virtual_Network_Adapter_Connect_Vswitch_DM",
"--operands",
"-v %s" % vdev,
"-n %s" % vswitch_name))
try:
self._request(requestData)
except exception.SDKSMTRequestFailed as err:
LOG.error("Failed to couple nic %s to vswitch %s for user %s "
"in the guest's user direct, error: %s" %
(vdev, vswitch_name, userid, err.format_message()))
self._couple_inactive_exception(err, userid, vdev, vswitch_name)
# the inst must be active, or this call will failed
if active:
requestData = ' '.join((
'SMAPI %s' % userid,
'API Virtual_Network_Adapter_Connect_Vswitch',
"--operands",
"-v %s" % vdev,
"-n %s" % vswitch_name))
try:
self._request(requestData)
except (exception.SDKSMTRequestFailed,
exception.SDKInternalError) as err1:
results1 = err1.results
msg1 = err1.format_message()
if ((results1 is not None) and
(results1['rc'] == 204) and
(results1['rs'] == 20)):
LOG.warning("Virtual device %s already connected "
"on the active guest system", vdev)
else:
persist_OK = True
requestData = ' '.join((
'SMAPI %s' % userid,
'API Virtual_Network_Adapter_Disconnect_DM',
"--operands",
'-v %s' % vdev))
try:
self._request(requestData)
except (exception.SDKSMTRequestFailed,
exception.SDKInternalError) as err2:
results2 = err2.results
msg2 = err2.format_message()
if ((results2 is not None) and
(results2['rc'] == 212) and
(results2['rs'] == 32)):
persist_OK = True
else:
persist_OK = False
if persist_OK:
self._couple_active_exception(err1, userid, vdev,
vswitch_name)
else:
raise exception.SDKNetworkOperationError(rs=3,
nic=vdev, vswitch=vswitch_name,
couple_err=msg1, revoke_err=msg2)
"""Update information in switch table."""
self._NetDbOperator.switch_update_record_with_switch(userid, vdev,
vswitch_name)
msg = ('Couple nic device %(vdev)s of guest %(vm)s '
'with vswitch %(vsw)s successfully'
% {'vdev': vdev, 'vm': userid, 'vsw': vswitch_name})
LOG.info(msg) | Couple NIC to vswitch by adding vswitch into user direct. | entailment |
def couple_nic_to_vswitch(self, userid, nic_vdev,
vswitch_name, active=False):
"""Couple nic to vswitch."""
if active:
msg = ("both in the user direct of guest %s and on "
"the active guest system" % userid)
else:
msg = "in the user direct of guest %s" % userid
LOG.debug("Connect nic %s to switch %s %s",
nic_vdev, vswitch_name, msg)
self._couple_nic(userid, nic_vdev, vswitch_name, active=active) | Couple nic to vswitch. | entailment |
def _uncouple_nic(self, userid, vdev, active=False):
"""Uncouple NIC from vswitch"""
if active:
self._is_active(userid)
msg = ('Start to uncouple nic device %(vdev)s of guest %(vm)s'
% {'vdev': vdev, 'vm': userid})
LOG.info(msg)
requestData = ' '.join((
'SMAPI %s' % userid,
"API Virtual_Network_Adapter_Disconnect_DM",
"--operands",
"-v %s" % vdev))
try:
self._request(requestData)
except (exception.SDKSMTRequestFailed,
exception.SDKInternalError) as err:
results = err.results
emsg = err.format_message()
if ((results is not None) and
(results['rc'] == 212) and
(results['rs'] == 32)):
LOG.warning("Virtual device %s is already disconnected "
"in the guest's user direct", vdev)
else:
LOG.error("Failed to uncouple nic %s in the guest's user "
"direct, error: %s" % (vdev, emsg))
self._uncouple_inactive_exception(err, userid, vdev)
"""Update information in switch table."""
self._NetDbOperator.switch_update_record_with_switch(userid, vdev,
None)
# the inst must be active, or this call will failed
if active:
requestData = ' '.join((
'SMAPI %s' % userid,
'API Virtual_Network_Adapter_Disconnect',
"--operands",
"-v %s" % vdev))
try:
self._request(requestData)
except (exception.SDKSMTRequestFailed,
exception.SDKInternalError) as err:
results = err.results
emsg = err.format_message()
if ((results is not None) and
(results['rc'] == 204) and
(results['rs'] == 48)):
LOG.warning("Virtual device %s is already "
"disconnected on the active "
"guest system", vdev)
else:
LOG.error("Failed to uncouple nic %s on the active "
"guest system, error: %s" % (vdev, emsg))
self._uncouple_active_exception(err, userid, vdev)
msg = ('Uncouple nic device %(vdev)s of guest %(vm)s successfully'
% {'vdev': vdev, 'vm': userid})
LOG.info(msg) | Uncouple NIC from vswitch | entailment |
def execute_cmd(self, userid, cmdStr):
""""cmdVM."""
requestData = 'cmdVM ' + userid + ' CMD \'' + cmdStr + '\''
with zvmutils.log_and_reraise_smt_request_failed(action='execute '
'command on vm via iucv channel'):
results = self._request(requestData)
ret = results['response']
return ret | cmdVM. | entailment |
def execute_cmd_direct(self, userid, cmdStr):
""""cmdVM."""
requestData = 'cmdVM ' + userid + ' CMD \'' + cmdStr + '\''
results = self._smt.request(requestData)
return results | cmdVM. | entailment |
def image_import(self, image_name, url, image_meta, remote_host=None):
"""Import the image specified in url to SDK image repository, and
create a record in image db, the imported images are located in
image_repository/prov_method/os_version/image_name/, for example,
/opt/sdk/images/netboot/rhel7.2/90685d2b-167bimage/0100"""
image_info = []
try:
image_info = self._ImageDbOperator.image_query_record(image_name)
except exception.SDKObjectNotExistError:
msg = ("The image record %s doens't exist in SDK image datebase,"
" will import the image and create record now" % image_name)
LOG.info(msg)
# Ensure the specified image is not exist in image DB
if image_info:
msg = ("The image name %s has already exist in SDK image "
"database, please check if they are same image or consider"
" to use a different image name for import" % image_name)
LOG.error(msg)
raise exception.SDKImageOperationError(rs=13, img=image_name)
try:
image_os_version = image_meta['os_version'].lower()
target_folder = self._pathutils.create_import_image_repository(
image_os_version, const.IMAGE_TYPE['DEPLOY'],
image_name)
except Exception as err:
msg = ('Failed to create repository to store image %(img)s with '
'error: %(err)s, please make sure there are enough space '
'on zvmsdk server and proper permission to create the '
'repository' % {'img': image_name,
'err': six.text_type(err)})
LOG.error(msg)
raise exception.SDKImageOperationError(rs=14, msg=msg)
try:
import_image_fn = urlparse.urlparse(url).path.split('/')[-1]
import_image_fpath = '/'.join([target_folder, import_image_fn])
self._scheme2backend(urlparse.urlparse(url).scheme).image_import(
image_name, url,
import_image_fpath,
remote_host=remote_host)
# Check md5 after import to ensure import a correct image
# TODO change to use query image name in DB
expect_md5sum = image_meta.get('md5sum')
real_md5sum = self._get_md5sum(import_image_fpath)
if expect_md5sum and expect_md5sum != real_md5sum:
msg = ("The md5sum after import is not same as source image,"
" the image has been broken")
LOG.error(msg)
raise exception.SDKImageOperationError(rs=4)
# After import to image repository, figure out the image type is
# single disk image or multiple-disk image,if multiple disks image,
# extract it, if it's single image, rename its name to be same as
# specific vdev
# TODO: (nafei) use sub-function to check the image type
image_type = 'rootonly'
if image_type == 'rootonly':
final_image_fpath = '/'.join([target_folder,
CONF.zvm.user_root_vdev])
os.rename(import_image_fpath, final_image_fpath)
elif image_type == 'alldisks':
# For multiple disks image, extract it, after extract, the
# content under image folder is like: 0100, 0101, 0102
# and remove the image file 0100-0101-0102.tgz
pass
# TODO: put multiple disk image into consideration, update the
# disk_size_units and image_size db field
disk_size_units = self._get_disk_size_units(final_image_fpath)
image_size = self._get_image_size(final_image_fpath)
# TODO: update the real_md5sum field to include each disk image
self._ImageDbOperator.image_add_record(image_name,
image_os_version,
real_md5sum,
disk_size_units,
image_size,
image_type)
LOG.info("Image %s is import successfully" % image_name)
except Exception:
# Cleanup the image from image repository
self._pathutils.clean_temp_folder(target_folder)
raise | Import the image specified in url to SDK image repository, and
create a record in image db, the imported images are located in
image_repository/prov_method/os_version/image_name/, for example,
/opt/sdk/images/netboot/rhel7.2/90685d2b-167bimage/0100 | entailment |
def image_export(self, image_name, dest_url, remote_host=None):
"""Export the specific image to remote host or local file system
:param image_name: image name that can be uniquely identify an image
:param dest_path: the location to store exported image, eg.
/opt/images, the image will be stored in folder
/opt/images/
:param remote_host: the server that export image to, the format is
username@IP eg. nova@192.168.99.1, if remote_host is
None, it means the image will be stored in local server
: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
}
"""
image_info = self._ImageDbOperator.image_query_record(image_name)
if not image_info:
msg = ("The image %s does not exist in image repository"
% image_name)
LOG.error(msg)
raise exception.SDKImageOperationError(rs=20, img=image_name)
image_type = image_info[0]['type']
# TODO: (nafei) according to image_type, detect image exported path
# For multiple disk image, make the tgz firstly, the specify the
# source_path to be something like: 0100-0101-0102.tgz
if image_type == 'rootonly':
source_path = '/'.join([CONF.image.sdk_image_repository,
const.IMAGE_TYPE['DEPLOY'],
image_info[0]['imageosdistro'],
image_name,
CONF.zvm.user_root_vdev])
else:
pass
self._scheme2backend(urlparse.urlparse(dest_url).scheme).image_export(
source_path, dest_url,
remote_host=remote_host)
# TODO: (nafei) for multiple disks image, update the expect_dict
# to be the tgz's md5sum
export_dict = {'image_name': image_name,
'image_path': dest_url,
'os_version': image_info[0]['imageosdistro'],
'md5sum': image_info[0]['md5sum']}
LOG.info("Image %s export successfully" % image_name)
return export_dict | Export the specific image to remote host or local file system
:param image_name: image name that can be uniquely identify an image
:param dest_path: the location to store exported image, eg.
/opt/images, the image will be stored in folder
/opt/images/
:param remote_host: the server that export image to, the format is
username@IP eg. nova@192.168.99.1, if remote_host is
None, it means the image will be stored in local server
: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 _get_image_size(self, image_path):
"""Return disk size in bytes"""
command = 'du -b %s' % image_path
(rc, output) = zvmutils.execute(command)
if rc:
msg = ("Error happened when executing command du -b with"
"reason: %s" % output)
LOG.error(msg)
raise exception.SDKImageOperationError(rs=8)
size = output.split()[0]
return size | Return disk size in bytes | entailment |
def _get_md5sum(self, fpath):
"""Calculate the md5sum of the specific image file"""
try:
current_md5 = hashlib.md5()
if isinstance(fpath, six.string_types) and os.path.exists(fpath):
with open(fpath, "rb") as fh:
for chunk in self._read_chunks(fh):
current_md5.update(chunk)
elif (fpath.__class__.__name__ in ["StringIO", "StringO"] or
isinstance(fpath, IOBase)):
for chunk in self._read_chunks(fpath):
current_md5.update(chunk)
else:
return ""
return current_md5.hexdigest()
except Exception:
msg = ("Failed to calculate the image's md5sum")
LOG.error(msg)
raise exception.SDKImageOperationError(rs=3) | Calculate the md5sum of the specific image file | entailment |
def image_get_root_disk_size(self, image_name):
"""Return the root disk units of the specified image
image_name: the unique image name in db
Return the disk units in format like 3339:CYL or 467200:BLK
"""
image_info = self.image_query(image_name)
if not image_info:
raise exception.SDKImageOperationError(rs=20, img=image_name)
disk_size_units = image_info[0]['disk_size_units'].split(':')[0]
return disk_size_units | Return the root disk units of the specified image
image_name: the unique image name in db
Return the disk units in format like 3339:CYL or 467200:BLK | entailment |
def get_guest_connection_status(self, userid):
'''Get guest vm connection status.'''
rd = ' '.join(('getvm', userid, 'isreachable'))
results = self._request(rd)
if results['rs'] == 1:
return True
else:
return False | Get guest vm connection status. | entailment |
def process_additional_minidisks(self, userid, disk_info):
'''Generate and punch the scripts used to process additional disk into
target vm's reader.
'''
for idx, disk in enumerate(disk_info):
vdev = disk.get('vdev') or self.generate_disk_vdev(
offset = (idx + 1))
fmt = disk.get('format')
mount_dir = disk.get('mntdir') or ''.join(['/mnt/ephemeral',
str(vdev)])
disk_parms = self._generate_disk_parmline(vdev, fmt, mount_dir)
func_name = '/var/lib/zvmsdk/setupDisk'
self.aemod_handler(userid, func_name, disk_parms)
# trigger do-script
if self.get_power_state(userid) == 'on':
self.execute_cmd(userid, "/usr/bin/zvmguestconfigure start") | Generate and punch the scripts used to process additional disk into
target vm's reader. | entailment |
def _request_with_error_ignored(self, rd):
"""Send smt request, log and ignore any errors."""
try:
return self._request(rd)
except Exception as err:
# log as warning and ignore namelist operation failures
LOG.warning(six.text_type(err)) | Send smt request, log and ignore any errors. | entailment |
def image_import(cls, image_name, url, target, **kwargs):
"""Import image from remote host to local image repository using scp.
If remote_host not specified, it means the source file exist in local
file system, just copy the image to image repository
"""
source = urlparse.urlparse(url).path
if kwargs['remote_host']:
if '@' in kwargs['remote_host']:
source_path = ':'.join([kwargs['remote_host'], source])
command = ' '.join(['/usr/bin/scp',
"-P", CONF.zvm.remotehost_sshd_port,
"-o StrictHostKeyChecking=no",
'-r ', source_path, target])
(rc, output) = zvmutils.execute(command)
if rc:
msg = ("Copying image file from remote filesystem failed"
" with reason: %s" % output)
LOG.error(msg)
raise exception.SDKImageOperationError(rs=10, err=output)
else:
msg = ("The specified remote_host %s format invalid" %
kwargs['remote_host'])
LOG.error(msg)
raise exception.SDKImageOperationError(rs=11,
rh=kwargs['remote_host'])
else:
LOG.debug("Remote_host not specified, will copy from local")
try:
shutil.copyfile(source, target)
except Exception as err:
msg = ("Import image from local file system failed"
" with reason %s" % six.text_type(err))
LOG.error(msg)
raise exception.SDKImageOperationError(rs=12,
err=six.text_type(err)) | Import image from remote host to local image repository using scp.
If remote_host not specified, it means the source file exist in local
file system, just copy the image to image repository | entailment |
def image_export(cls, source_path, dest_url, **kwargs):
"""Export the specific image to remote host or local file system """
dest_path = urlparse.urlparse(dest_url).path
if kwargs['remote_host']:
target_path = ':'.join([kwargs['remote_host'], dest_path])
command = ' '.join(['/usr/bin/scp',
"-P", CONF.zvm.remotehost_sshd_port,
"-o StrictHostKeyChecking=no",
'-r ', source_path, target_path])
(rc, output) = zvmutils.execute(command)
if rc:
msg = ("Error happened when copying image file to remote "
"host with reason: %s" % output)
LOG.error(msg)
raise exception.SDKImageOperationError(rs=21, msg=output)
else:
# Copy to local file system
LOG.debug("Remote_host not specified, will copy to local server")
try:
shutil.copyfile(source_path, dest_path)
except Exception as err:
msg = ("Export image from %(src)s to local file system"
" %(dest)s failed: %(err)s" %
{'src': source_path,
'dest': dest_path,
'err': six.text_type(err)})
LOG.error(msg)
raise exception.SDKImageOperationError(rs=22,
err=six.text_type(err)) | Export the specific image to remote host or local file system | entailment |
def dedent(func):
"""
Dedent the docstring of a function and substitute with :attr:`params`
Parameters
----------
func: function
function with the documentation to dedent"""
if isinstance(func, types.MethodType) and not six.PY3:
func = func.im_func
func.__doc__ = func.__doc__ and dedents(func.__doc__)
return func | Dedent the docstring of a function and substitute with :attr:`params`
Parameters
----------
func: function
function with the documentation to dedent | entailment |
def indent(text, num=4):
"""Indet the given string"""
str_indent = ' ' * num
return str_indent + ('\n' + str_indent).join(text.splitlines()) | Indet the given string | entailment |
def append_original_doc(parent, num=0):
"""Return an iterator that append the docstring of the given `parent`
function to the applied function"""
def func(func):
func.__doc__ = func.__doc__ and func.__doc__ + indent(
parent.__doc__, num)
return func
return func | Return an iterator that append the docstring of the given `parent`
function to the applied function | entailment |
def get_sections(self, s, base, sections=[
'Parameters', 'Other Parameters', 'Possible types']):
"""
Extract the specified sections out of the given string
The same as the :meth:`docrep.DocstringProcessor.get_sections` method
but uses the ``'Possible types'`` section by default, too
Parameters
----------
%(DocstringProcessor.get_sections.parameters)s
Returns
-------
str
The replaced string
"""
return super(PsyplotDocstringProcessor, self).get_sections(s, base,
sections) | Extract the specified sections out of the given string
The same as the :meth:`docrep.DocstringProcessor.get_sections` method
but uses the ``'Possible types'`` section by default, too
Parameters
----------
%(DocstringProcessor.get_sections.parameters)s
Returns
-------
str
The replaced string | entailment |
def create_config_drive(network_interface_info, os_version):
"""Generate config driver for zVM guest vm.
:param dict network_interface_info: Required keys:
ip_addr - (str) IP address
nic_vdev - (str) VDEV of the nic
gateway_v4 - IPV4 gateway
broadcast_v4 - IPV4 broadcast address
netmask_v4 - IPV4 netmask
:param str os_version: operating system version of the guest
"""
temp_path = CONF.guest.temp_path
if not os.path.exists(temp_path):
os.mkdir(temp_path)
cfg_dir = os.path.join(temp_path, 'openstack')
if os.path.exists(cfg_dir):
shutil.rmtree(cfg_dir)
content_dir = os.path.join(cfg_dir, 'content')
latest_dir = os.path.join(cfg_dir, 'latest')
os.mkdir(cfg_dir)
os.mkdir(content_dir)
os.mkdir(latest_dir)
net_file = os.path.join(content_dir, '0000')
generate_net_file(network_interface_info, net_file, os_version)
znetconfig_file = os.path.join(content_dir, '0001')
generate_znetconfig_file(znetconfig_file, os_version)
meta_data_path = os.path.join(latest_dir, 'meta_data.json')
generate_meta_data(meta_data_path)
network_data_path = os.path.join(latest_dir, 'network_data.json')
generate_file('{}', network_data_path)
vendor_data_path = os.path.join(latest_dir, 'vendor_data.json')
generate_file('{}', vendor_data_path)
tar_path = os.path.join(temp_path, 'cfgdrive.tgz')
tar = tarfile.open(tar_path, "w:gz")
os.chdir(temp_path)
tar.add('openstack')
tar.close()
return tar_path | Generate config driver for zVM guest vm.
:param dict network_interface_info: Required keys:
ip_addr - (str) IP address
nic_vdev - (str) VDEV of the nic
gateway_v4 - IPV4 gateway
broadcast_v4 - IPV4 broadcast address
netmask_v4 - IPV4 netmask
:param str os_version: operating system version of the guest | 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)
# Set the memory required based on parameter values
m = 128 * r * (N + p + 2)
try:
return _scrypt(
password=password, salt=salt, n=N, r=r, p=p, maxmem=m, dklen=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 set(self, ctype, key, data):
"""Set or update cache content.
:param ctype: cache type
:param key: the key to be set value
:param data: cache data
"""
with zvmutils.acquire_lock(self._lock):
target_cache = self._get_ctype_cache(ctype)
target_cache['data'][key] = data | Set or update cache content.
:param ctype: cache type
:param key: the key to be set value
:param data: cache data | entailment |
def GoodResponse(body, request, status_code=None,
headers=None):
"""
Construct a Good HTTP response (defined in DEFAULT_GOOD_RESPONSE_CODE)
:param body: The body of the response
:type body: ``str``
:param request: The HTTP request
:type request: :class:`requests.Request`
:param status_code: The return status code, defaults
to DEFAULT_GOOD_STATUS_CODE if not specified
:type status_code: ``int``
:param headers: Response headers, defaults to
DEFAULT_RESPONSE_HEADERS if not specified
:type headers: ``dict``
:rtype: :class:`requests.Response`
:returns: a Response object
"""
response = Response()
response.url = request.url
response.raw = BytesIO(body)
if status_code:
response.status_code = status_code
else:
response.status_code = DEFAULT_GOOD_STATUS_CODE
if headers:
response.headers = headers
else:
response.headers = DEFAULT_RESPONSE_HEADERS
response.request = request
response._content = body
return response | Construct a Good HTTP response (defined in DEFAULT_GOOD_RESPONSE_CODE)
:param body: The body of the response
:type body: ``str``
:param request: The HTTP request
:type request: :class:`requests.Request`
:param status_code: The return status code, defaults
to DEFAULT_GOOD_STATUS_CODE if not specified
:type status_code: ``int``
:param headers: Response headers, defaults to
DEFAULT_RESPONSE_HEADERS if not specified
:type headers: ``dict``
:rtype: :class:`requests.Response`
:returns: a Response object | entailment |
def BadResponse(body, request, status_code=None,
headers=None):
"""
Construct a Bad HTTP response (defined in DEFAULT_BAD_RESPONSE_CODE)
:param body: The body of the response
:type body: ``str``
:param request: The HTTP request
:type request: :class:`requests.Request`
:param status_code: The return status code, defaults
to DEFAULT_GOOD_STATUS_CODE if not specified
:type status_code: ``int``
:param headers: Response headers, defaults to
DEFAULT_RESPONSE_HEADERS if not specified
:type headers: ``dict``
:rtype: :class:`requests.Response`
:returns: a Response object
"""
response = Response()
response.url = request.url
response.raw = BytesIO(body)
if status_code:
response.status_code = status_code
else:
response.status_code = DEFAULT_BAD_STATUS_CODE
if headers:
response.headers = headers
else:
response.headers = DEFAULT_RESPONSE_HEADERS
response.request = request
response._content = body
return response | Construct a Bad HTTP response (defined in DEFAULT_BAD_RESPONSE_CODE)
:param body: The body of the response
:type body: ``str``
:param request: The HTTP request
:type request: :class:`requests.Request`
:param status_code: The return status code, defaults
to DEFAULT_GOOD_STATUS_CODE if not specified
:type status_code: ``int``
:param headers: Response headers, defaults to
DEFAULT_RESPONSE_HEADERS if not specified
:type headers: ``dict``
:rtype: :class:`requests.Response`
:returns: a Response object | entailment |
def disable_warnings(critical=False):
"""Function that disables all warnings and all critical warnings (if
critical evaluates to True) related to the psyplot Module.
Please note that you can also configure the warnings via the
psyplot.warning logger (logging.getLogger(psyplot.warning))."""
warnings.filterwarnings('ignore', '\w', PsyPlotWarning, 'psyplot', 0)
if critical:
warnings.filterwarnings('ignore', '\w', PsyPlotCritical, 'psyplot', 0) | Function that disables all warnings and all critical warnings (if
critical evaluates to True) related to the psyplot Module.
Please note that you can also configure the warnings via the
psyplot.warning logger (logging.getLogger(psyplot.warning)). | entailment |
def warn(message, category=PsyPlotWarning, logger=None):
"""wrapper around the warnings.warn function for non-critical warnings.
logger may be a logging.Logger instance"""
if logger is not None:
message = "[Warning by %s]\n%s" % (logger.name, message)
warnings.warn(message, category, stacklevel=3) | wrapper around the warnings.warn function for non-critical warnings.
logger may be a logging.Logger instance | entailment |
def critical(message, category=PsyPlotCritical, logger=None):
"""wrapper around the warnings.warn function for critical warnings.
logger may be a logging.Logger instance"""
if logger is not None:
message = "[Critical warning by %s]\n%s" % (logger.name, message)
warnings.warn(message, category, stacklevel=2) | wrapper around the warnings.warn function for critical warnings.
logger may be a logging.Logger instance | entailment |
def customwarn(message, category, filename, lineno, *args, **kwargs):
"""Use the psyplot.warning logger for categories being out of
PsyPlotWarning and PsyPlotCritical and the default warnings.showwarning
function for all the others."""
if category is PsyPlotWarning:
logger.warning(warnings.formatwarning(
"\n%s" % message, category, filename, lineno))
elif category is PsyPlotCritical:
logger.critical(warnings.formatwarning(
"\n%s" % message, category, filename, lineno),
exc_info=True)
else:
old_showwarning(message, category, filename, lineno, *args, **kwargs) | Use the psyplot.warning logger for categories being out of
PsyPlotWarning and PsyPlotCritical and the default warnings.showwarning
function for all the others. | entailment |
def _get_home():
"""Find user's home directory if possible.
Otherwise, returns None.
:see: http://mail.python.org/pipermail/python-list/2005-February/325395.html
This function is copied from matplotlib version 1.4.3, Jan 2016
"""
try:
if six.PY2 and sys.platform == 'win32':
path = os.path.expanduser(b"~").decode(sys.getfilesystemencoding())
else:
path = os.path.expanduser("~")
except ImportError:
# This happens on Google App Engine (pwd module is not present).
pass
else:
if os.path.isdir(path):
return path
for evar in ('HOME', 'USERPROFILE', 'TMP'):
path = os.environ.get(evar)
if path is not None and os.path.isdir(path):
return path
return None | Find user's home directory if possible.
Otherwise, returns None.
:see: http://mail.python.org/pipermail/python-list/2005-February/325395.html
This function is copied from matplotlib version 1.4.3, Jan 2016 | entailment |
def match_url(self, request):
"""
Match the request against a file in the adapter directory
:param request: The request
:type request: :class:`requests.Request`
:return: Path to the file
:rtype: ``str``
"""
parsed_url = urlparse(request.path_url)
path_url = parsed_url.path
query_params = parsed_url.query
match = None
for path in self.paths:
for item in self.index:
target_path = os.path.join(BASE_PATH, path, path_url[1:])
query_path = target_path.lower() + quote(
'?' + query_params).lower()
if target_path.lower() == item[0]:
match = item[1]
break
elif query_path == item[0]:
match = item[1]
break
return match | Match the request against a file in the adapter directory
:param request: The request
:type request: :class:`requests.Request`
:return: Path to the file
:rtype: ``str`` | entailment |
def _reindex(self):
"""
Create a case-insensitive index of the paths
"""
self.index = []
for path in self.paths:
target_path = os.path.normpath(os.path.join(BASE_PATH,
path))
for root, subdirs, files in os.walk(target_path):
for f in files:
self.index.append(
(os.path.join(root, f).lower(),
os.path.join(root, f))) | Create a case-insensitive index of the paths | entailment |
def add3390(rh):
"""
Adds a 3390 (ECKD) disk to a virtual machine's directory entry.
Input:
Request Handle with the following properties:
function - 'CHANGEVM'
subfunction - 'ADD3390'
userid - userid of the virtual machine
parms['diskPool'] - Disk pool
parms['diskSize'] - size of the disk in cylinders or bytes.
parms['fileSystem'] - Linux filesystem to install on the disk.
parms['mode'] - Disk access mode
parms['multiPW'] - Multi-write password
parms['readPW'] - Read password
parms['vaddr'] - Virtual address
parms['writePW'] - Write password
Output:
Request Handle updated with the results.
Return code - 0: ok, non-zero: error
"""
rh.printSysLog("Enter changeVM.add3390")
results, cyl = generalUtils.cvtToCyl(rh, rh.parms['diskSize'])
if results['overallRC'] != 0:
# message already sent. Only need to update the final results.
rh.updateResults(results)
if results['overallRC'] == 0:
parms = [
"-T", rh.userid,
"-v", rh.parms['vaddr'],
"-t", "3390",
"-a", "AUTOG",
"-r", rh.parms['diskPool'],
"-u", "1",
"-z", cyl,
"-f", "1"]
hideList = []
if 'mode' in rh.parms:
parms.extend(["-m", rh.parms['mode']])
else:
parms.extend(["-m", 'W'])
if 'readPW' in rh.parms:
parms.extend(["-R", rh.parms['readPW']])
hideList.append(len(parms) - 1)
if 'writePW' in rh.parms:
parms.extend(["-W", rh.parms['writePW']])
hideList.append(len(parms) - 1)
if 'multiPW' in rh.parms:
parms.extend(["-M", rh.parms['multiPW']])
hideList.append(len(parms) - 1)
results = invokeSMCLI(rh,
"Image_Disk_Create_DM",
parms,
hideInLog=hideList)
if results['overallRC'] != 0:
# SMAPI API failed.
rh.printLn("ES", results['response'])
rh.updateResults(results) # Use results returned by invokeSMCLI
if (results['overallRC'] == 0 and 'fileSystem' in rh.parms):
results = installFS(
rh,
rh.parms['vaddr'],
rh.parms['mode'],
rh.parms['fileSystem'],
"3390")
if results['overallRC'] == 0:
results = isLoggedOn(rh, rh.userid)
if results['overallRC'] != 0:
# Cannot determine if VM is logged on or off.
# We have partially failed. Pass back the results.
rh.updateResults(results)
elif results['rs'] == 0:
# Add the disk to the active configuration.
parms = [
"-T", rh.userid,
"-v", rh.parms['vaddr'],
"-m", rh.parms['mode']]
results = invokeSMCLI(rh, "Image_Disk_Create", parms)
if results['overallRC'] == 0:
rh.printLn("N", "Added dasd " + rh.parms['vaddr'] +
" to the active configuration.")
else:
# SMAPI API failed.
rh.printLn("ES", results['response'])
rh.updateResults(results) # Use results from invokeSMCLI
rh.printSysLog("Exit changeVM.add3390, rc: " +
str(rh.results['overallRC']))
return rh.results['overallRC'] | Adds a 3390 (ECKD) disk to a virtual machine's directory entry.
Input:
Request Handle with the following properties:
function - 'CHANGEVM'
subfunction - 'ADD3390'
userid - userid of the virtual machine
parms['diskPool'] - Disk pool
parms['diskSize'] - size of the disk in cylinders or bytes.
parms['fileSystem'] - Linux filesystem to install on the disk.
parms['mode'] - Disk access mode
parms['multiPW'] - Multi-write password
parms['readPW'] - Read password
parms['vaddr'] - Virtual address
parms['writePW'] - Write password
Output:
Request Handle updated with the results.
Return code - 0: ok, non-zero: error | entailment |
def add9336(rh):
"""
Adds a 9336 (FBA) disk to virtual machine's directory entry.
Input:
Request Handle with the following properties:
function - 'CHANGEVM'
subfunction - 'ADD9336'
userid - userid of the virtual machine
parms['diskPool'] - Disk pool
parms['diskSize'] - size of the disk in blocks or bytes.
parms['fileSystem'] - Linux filesystem to install on the disk.
parms['mode'] - Disk access mode
parms['multiPW'] - Multi-write password
parms['readPW'] - Read password
parms['vaddr'] - Virtual address
parms['writePW'] - Write password
Output:
Request Handle updated with the results.
Return code - 0: ok, non-zero: error
"""
rh.printSysLog("Enter changeVM.add9336")
results, blocks = generalUtils.cvtToBlocks(rh, rh.parms['diskSize'])
if results['overallRC'] != 0:
# message already sent. Only need to update the final results.
rh.updateResults(results)
if results['overallRC'] == 0:
parms = [
"-T", rh.userid,
"-v", rh.parms['vaddr'],
"-t", "9336",
"-a", "AUTOG",
"-r", rh.parms['diskPool'],
"-u", "1",
"-z", blocks,
"-f", "1"]
hideList = []
if 'mode' in rh.parms:
parms.extend(["-m", rh.parms['mode']])
else:
parms.extend(["-m", 'W'])
if 'readPW' in rh.parms:
parms.extend(["-R", rh.parms['readPW']])
hideList.append(len(parms) - 1)
if 'writePW' in rh.parms:
parms.extend(["-W", rh.parms['writePW']])
hideList.append(len(parms) - 1)
if 'multiPW' in rh.parms:
parms.extend(["-M", rh.parms['multiPW']])
hideList.append(len(parms) - 1)
results = invokeSMCLI(rh,
"Image_Disk_Create_DM",
parms,
hideInLog=hideList)
if results['overallRC'] != 0:
# SMAPI API failed.
rh.printLn("ES", results['response'])
rh.updateResults(results) # Use results from invokeSMCLI
if (results['overallRC'] == 0 and 'fileSystem' in rh.parms):
# Install the file system
results = installFS(
rh,
rh.parms['vaddr'],
rh.parms['mode'],
rh.parms['fileSystem'],
"9336")
if results['overallRC'] == 0:
results = isLoggedOn(rh, rh.userid)
if (results['overallRC'] == 0 and results['rs'] == 0):
# Add the disk to the active configuration.
parms = [
"-T", rh.userid,
"-v", rh.parms['vaddr'],
"-m", rh.parms['mode']]
results = invokeSMCLI(rh, "Image_Disk_Create", parms)
if results['overallRC'] == 0:
rh.printLn("N", "Added dasd " + rh.parms['vaddr'] +
" to the active configuration.")
else:
# SMAPI API failed.
rh.printLn("ES", results['response'])
rh.updateResults(results) # Use results from invokeSMCLI
rh.printSysLog("Exit changeVM.add9336, rc: " +
str(rh.results['overallRC']))
return rh.results['overallRC'] | Adds a 9336 (FBA) disk to virtual machine's directory entry.
Input:
Request Handle with the following properties:
function - 'CHANGEVM'
subfunction - 'ADD9336'
userid - userid of the virtual machine
parms['diskPool'] - Disk pool
parms['diskSize'] - size of the disk in blocks or bytes.
parms['fileSystem'] - Linux filesystem to install on the disk.
parms['mode'] - Disk access mode
parms['multiPW'] - Multi-write password
parms['readPW'] - Read password
parms['vaddr'] - Virtual address
parms['writePW'] - Write password
Output:
Request Handle updated with the results.
Return code - 0: ok, non-zero: error | entailment |
def dedicate(rh):
"""
Dedicate device.
Input:
Request Handle with the following properties:
function - 'CHANGEVM'
subfunction - 'DEDICATEDM'
userid - userid of the virtual machine
parms['vaddr'] - Virtual address
parms['raddr'] - Real address
parms['mode'] - Read only mode or not.
Output:
Request Handle updated with the results.
Return code - 0: ok, non-zero: error
"""
rh.printSysLog("Enter changeVM.dedicate")
parms = [
"-T", rh.userid,
"-v", rh.parms['vaddr'],
"-r", rh.parms['raddr'],
"-R", rh.parms['mode']]
hideList = []
results = invokeSMCLI(rh,
"Image_Device_Dedicate_DM",
parms,
hideInLog=hideList)
if results['overallRC'] != 0:
# SMAPI API failed.
rh.printLn("ES", results['response'])
rh.updateResults(results) # Use results from invokeSMCLI
if results['overallRC'] == 0:
results = isLoggedOn(rh, rh.userid)
if (results['overallRC'] == 0 and results['rs'] == 0):
# Dedicate device to active configuration.
parms = [
"-T", rh.userid,
"-v", rh.parms['vaddr'],
"-r", rh.parms['raddr'],
"-R", rh.parms['mode']]
results = invokeSMCLI(rh, "Image_Device_Dedicate", parms)
if results['overallRC'] == 0:
rh.printLn("N", "Dedicated device " + rh.parms['vaddr'] +
" to the active configuration.")
else:
# SMAPI API failed.
rh.printLn("ES", results['response'])
rh.updateResults(results) # Use results from invokeSMCLI
rh.printSysLog("Exit changeVM.dedicate, rc: " +
str(rh.results['overallRC']))
return rh.results['overallRC'] | Dedicate device.
Input:
Request Handle with the following properties:
function - 'CHANGEVM'
subfunction - 'DEDICATEDM'
userid - userid of the virtual machine
parms['vaddr'] - Virtual address
parms['raddr'] - Real address
parms['mode'] - Read only mode or not.
Output:
Request Handle updated with the results.
Return code - 0: ok, non-zero: error | entailment |
def addAEMOD(rh):
"""
Send an Activation Modification Script to the virtual machine.
Input:
Request Handle with the following properties:
function - 'CHANGEVM'
subfunction - 'AEMOD'
userid - userid of the virtual machine
parms['aeScript'] - File specification of the AE script
parms['invparms'] - invparms operand
Output:
Request Handle updated with the results.
Return code - 0: ok
Return code - 4: input error, rs - 11 AE script not found
"""
rh.printSysLog("Enter changeVM.addAEMOD")
invokeScript = "invokeScript.sh"
trunkFile = "aemod.doscript"
fileClass = "X"
tempDir = tempfile.mkdtemp()
if os.path.isfile(rh.parms['aeScript']):
# Get the short name of our activation engine modifier script
if rh.parms['aeScript'].startswith("/"):
s = rh.parms['aeScript']
tmpAEScript = s[s.rindex("/") + 1:]
else:
tmpAEScript = rh.parms['aeScript']
# Copy the mod script to our temp directory
shutil.copyfile(rh.parms['aeScript'], tempDir + "/" + tmpAEScript)
# Create the invocation script.
conf = "#!/bin/bash \n"
baseName = os.path.basename(rh.parms['aeScript'])
parm = "/bin/bash %s %s \n" % (baseName, rh.parms['invParms'])
fh = open(tempDir + "/" + invokeScript, "w")
fh.write(conf)
fh.write(parm)
fh.close()
# Generate the tar package for punch
tar = tarfile.open(tempDir + "/" + trunkFile, "w")
for file in os.listdir(tempDir):
tar.add(tempDir + "/" + file, arcname=file)
tar.close()
# Punch file to reader
punch2reader(rh, rh.userid, tempDir + "/" + trunkFile, fileClass)
shutil.rmtree(tempDir)
else:
# Worker script does not exist.
shutil.rmtree(tempDir)
msg = msgs.msg['0400'][1] % (modId, rh.parms['aeScript'])
rh.printLn("ES", msg)
rh.updateResults(msgs.msg['0400'][0])
rh.printSysLog("Exit changeVM.addAEMOD, rc: " +
str(rh.results['overallRC']))
return rh.results['overallRC'] | Send an Activation Modification Script to the virtual machine.
Input:
Request Handle with the following properties:
function - 'CHANGEVM'
subfunction - 'AEMOD'
userid - userid of the virtual machine
parms['aeScript'] - File specification of the AE script
parms['invparms'] - invparms operand
Output:
Request Handle updated with the results.
Return code - 0: ok
Return code - 4: input error, rs - 11 AE script not found | entailment |
def addLOADDEV(rh):
"""
Sets the LOADDEV statement in the virtual machine's directory entry.
Input:
Request Handle with the following properties:
function - 'CHANGEVM'
subfunction - 'ADDLOADDEV'
userid - userid of the virtual machine
parms['boot'] - Boot program number
parms['addr'] - Logical block address of the boot record
parms['lun'] - One to eight-byte logical unit number
of the FCP-I/O device.
parms['wwpn'] - World-Wide Port Number
parms['scpDataType'] - SCP data type
parms['scpData'] - Designates information to be passed to the
program is loaded during guest IPL.
Note that any of the parms may be left blank, in which case
we will not update them.
Output:
Request Handle updated with the results.
Return code - 0: ok, non-zero: error
"""
rh.printSysLog("Enter changeVM.addLOADDEV")
# scpDataType and scpData must appear or disappear concurrently
if ('scpData' in rh.parms and 'scpDataType' not in rh.parms):
msg = msgs.msg['0014'][1] % (modId, "scpData", "scpDataType")
rh.printLn("ES", msg)
rh.updateResults(msgs.msg['0014'][0])
return
if ('scpDataType' in rh.parms and 'scpData' not in rh.parms):
if rh.parms['scpDataType'].lower() == "delete":
scpDataType = 1
else:
# scpDataType and scpData must appear or disappear
# concurrently unless we're deleting data
msg = msgs.msg['0014'][1] % (modId, "scpDataType", "scpData")
rh.printLn("ES", msg)
rh.updateResults(msgs.msg['0014'][0])
return
scpData = ""
if 'scpDataType' in rh.parms:
if rh.parms['scpDataType'].lower() == "hex":
scpData = rh.parms['scpData']
scpDataType = 3
elif rh.parms['scpDataType'].lower() == "ebcdic":
scpData = rh.parms['scpData']
scpDataType = 2
# scpDataType not hex, ebcdic or delete
elif rh.parms['scpDataType'].lower() != "delete":
msg = msgs.msg['0016'][1] % (modId, rh.parms['scpDataType'])
rh.printLn("ES", msg)
rh.updateResults(msgs.msg['0016'][0])
return
else:
# Not specified, 0 for do nothing
scpDataType = 0
scpData = ""
if 'boot' not in rh.parms:
boot = ""
else:
boot = rh.parms['boot']
if 'addr' not in rh.parms:
block = ""
else:
block = rh.parms['addr']
if 'lun' not in rh.parms:
lun = ""
else:
lun = rh.parms['lun']
# Make sure it doesn't have the 0x prefix
lun.replace("0x", "")
if 'wwpn' not in rh.parms:
wwpn = ""
else:
wwpn = rh.parms['wwpn']
# Make sure it doesn't have the 0x prefix
wwpn.replace("0x", "")
parms = [
"-T", rh.userid,
"-b", boot,
"-k", block,
"-l", lun,
"-p", wwpn,
"-s", str(scpDataType)]
if scpData != "":
parms.extend(["-d", scpData])
results = invokeSMCLI(rh, "Image_SCSI_Characteristics_Define_DM", parms)
# SMAPI API failed.
if results['overallRC'] != 0:
rh.printLn("ES", results['response'])
rh.updateResults(results)
rh.printSysLog("Exit changeVM.addLOADDEV, rc: " +
str(rh.results['overallRC']))
return rh.results['overallRC'] | Sets the LOADDEV statement in the virtual machine's directory entry.
Input:
Request Handle with the following properties:
function - 'CHANGEVM'
subfunction - 'ADDLOADDEV'
userid - userid of the virtual machine
parms['boot'] - Boot program number
parms['addr'] - Logical block address of the boot record
parms['lun'] - One to eight-byte logical unit number
of the FCP-I/O device.
parms['wwpn'] - World-Wide Port Number
parms['scpDataType'] - SCP data type
parms['scpData'] - Designates information to be passed to the
program is loaded during guest IPL.
Note that any of the parms may be left blank, in which case
we will not update them.
Output:
Request Handle updated with the results.
Return code - 0: ok, non-zero: error | entailment |
def punchFile(rh):
"""
Punch a file to a virtual reader of the specified virtual machine.
Input:
Request Handle with the following properties:
function - 'CHANGEVM'
subfunction - 'PUNCHFILE'
userid - userid of the virtual machine
parms['class'] - Spool class (optional)
parms['file'] - Filespec of the file to punch.
Output:
Request Handle updated with the results.
Return code - 0: ok, non-zero: error
"""
rh.printSysLog("Enter changeVM.punchFile")
# Default spool class in "A" , if specified change to specified class
spoolClass = "A"
if 'class' in rh.parms:
spoolClass = str(rh.parms['class'])
punch2reader(rh, rh.userid, rh.parms['file'], spoolClass)
rh.printSysLog("Exit changeVM.punchFile, rc: " +
str(rh.results['overallRC']))
return rh.results['overallRC'] | Punch a file to a virtual reader of the specified virtual machine.
Input:
Request Handle with the following properties:
function - 'CHANGEVM'
subfunction - 'PUNCHFILE'
userid - userid of the virtual machine
parms['class'] - Spool class (optional)
parms['file'] - Filespec of the file to punch.
Output:
Request Handle updated with the results.
Return code - 0: ok, non-zero: error | entailment |
def purgeRDR(rh):
"""
Purge the reader belonging to the virtual machine.
Input:
Request Handle with the following properties:
function - 'CHANGEVM'
subfunction - 'PURGERDR'
userid - userid of the virtual machine
Output:
Request Handle updated with the results.
Return code - 0: ok, non-zero: error
"""
rh.printSysLog("Enter changeVM.purgeRDR")
results = purgeReader(rh)
rh.updateResults(results)
rh.printSysLog("Exit changeVM.purgeRDR, rc: " +
str(rh.results['overallRC']))
return rh.results['overallRC'] | Purge the reader belonging to the virtual machine.
Input:
Request Handle with the following properties:
function - 'CHANGEVM'
subfunction - 'PURGERDR'
userid - userid of the virtual machine
Output:
Request Handle updated with the results.
Return code - 0: ok, non-zero: error | entailment |
def removeDisk(rh):
"""
Remove a disk from a virtual machine.
Input:
Request Handle with the following properties:
function - 'CHANGEVM'
subfunction - 'REMOVEDISK'
userid - userid of the virtual machine
parms['vaddr'] - Virtual address
Output:
Request Handle updated with the results.
Return code - 0: ok, non-zero: error
"""
rh.printSysLog("Enter changeVM.removeDisk")
results = {'overallRC': 0, 'rc': 0, 'rs': 0}
# Is image logged on
loggedOn = False
results = isLoggedOn(rh, rh.userid)
if results['overallRC'] == 0:
if results['rs'] == 0:
loggedOn = True
results = disableEnableDisk(
rh,
rh.userid,
rh.parms['vaddr'],
'-d')
if results['overallRC'] != 0:
rh.printLn("ES", results['response'])
rh.updateResults(results)
if results['overallRC'] == 0 and loggedOn:
strCmd = "/sbin/vmcp detach " + rh.parms['vaddr']
results = execCmdThruIUCV(rh, rh.userid, strCmd)
if results['overallRC'] != 0:
if re.search('(^HCP\w\w\w040E)', results['response']):
# Device does not exist, ignore the error
results = {'overallRC': 0, 'rc': 0, 'rs': 0, 'response': ''}
else:
rh.printLn("ES", results['response'])
rh.updateResults(results)
if results['overallRC'] == 0:
# Remove the disk from the user entry.
parms = [
"-T", rh.userid,
"-v", rh.parms['vaddr'],
"-e", "0"]
results = invokeSMCLI(rh, "Image_Disk_Delete_DM", parms)
if results['overallRC'] != 0:
if (results['overallRC'] == 8 and results['rc'] == 208 and
results['rs'] == 36):
# Disk does not exist, ignore the error
results = {'overallRC': 0, 'rc': 0, 'rs': 0, 'response': ''}
else:
# SMAPI API failed.
rh.printLn("ES", results['response'])
rh.updateResults(results) # Use results from invokeSMCLI
else:
# Unexpected error. Message already sent.
rh.updateResults(results)
rh.printSysLog("Exit changeVM.removeDisk, rc: " +
str(rh.results['overallRC']))
return rh.results['overallRC'] | Remove a disk from a virtual machine.
Input:
Request Handle with the following properties:
function - 'CHANGEVM'
subfunction - 'REMOVEDISK'
userid - userid of the virtual machine
parms['vaddr'] - Virtual address
Output:
Request Handle updated with the results.
Return code - 0: ok, non-zero: error | entailment |
def showInvLines(rh):
"""
Produce help output related to command synopsis
Input:
Request Handle
"""
if rh.subfunction != '':
rh.printLn("N", "Usage:")
rh.printLn("N", " python " + rh.cmdName +
" ChangeVM <userid> add3390 <diskPool> <vAddr>")
rh.printLn("N", " <diskSize3390> --mode " +
"<mode> --readpw <read_pw>")
rh.printLn("N", " --writepw <write_pw> " +
"--multipw <multi_pw> --filesystem <fsType>")
rh.printLn("N", " python " + rh.cmdName +
" ChangeVM <userid> add9336 <diskPool> <vAddr>")
rh.printLn("N", " <diskSize9336> --mode " +
"<mode> --readpw <read_pw>")
rh.printLn("N", " --writepw <write_pw> " +
"--multipw <multi_pw> --filesystem <fsType>")
rh.printLn("N", " python " + rh.cmdName +
" ChangeVM <userid> aemod <aeScript> --invparms <invParms>")
rh.printLn("N", " python " + rh.cmdName +
" ChangeVM <userid> IPL <addrOrNSS> --loadparms <loadParms>")
rh.printLn("N", " --parms <parmString>")
rh.printLn("N", " python " + rh.cmdName +
" ChangeVM <userid> loaddev --boot <boot> --addr <addr>")
rh.printLn("N", " --wwpn <wwpn> --lun <lun> " +
"--scpdatatype <scpDatatype> --scpdata <scp_data>")
rh.printLn("N", " python " + rh.cmdName +
" ChangeVM <userid> punchFile <file> --class <class>")
rh.printLn("N", " python " + rh.cmdName +
" ChangeVM <userid> purgeRDR")
rh.printLn("N", " python " + rh.cmdName +
" ChangeVM <userid> removedisk <vAddr>")
rh.printLn("N", " python " + rh.cmdName +
" ChangeVM <userid> removeIPL <vAddr>")
rh.printLn("N", " python " + rh.cmdName + " ChangeVM help")
rh.printLn("N", " python " + rh.cmdName +
" ChangeVM version")
return | Produce help output related to command synopsis
Input:
Request Handle | entailment |
def showOperandLines(rh):
"""
Produce help output related to operands.
Input:
Request Handle
"""
if rh.function == 'HELP':
rh.printLn("N", " For the ChangeVM function:")
else:
rh.printLn("N", "Sub-Functions(s):")
rh.printLn("N", " add3390 - Add a 3390 (ECKD) disk " +
"to a virtual machine's directory")
rh.printLn("N", " entry.")
rh.printLn("N", " add9336 - Add a 9336 (FBA) disk " +
"to virtual machine's directory")
rh.printLn("N", " entry.")
rh.printLn("N", " aemod - Sends an activation " +
"engine script to the managed virtual")
rh.printLn("N", " machine.")
rh.printLn("N", " help - Displays this help " +
"information.")
rh.printLn("N", " ipl - Sets the IPL statement in " +
"the virtual machine's")
rh.printLn("N", " directory entry.")
rh.printLn("N", " loaddev - Sets the LOADDEV statement " +
"in the virtual machine's")
rh.printLn("N", " directory entry.")
rh.printLn("N", " punchfile - Punch a file to a virtual " +
"reader of the specified")
rh.printLn("N", " virtual machine.")
rh.printLn("N", " purgerdr - Purges the reader " +
"belonging to the virtual machine.")
rh.printLn("N", " removedisk - " +
"Remove an mdisk from a virtual machine.")
rh.printLn("N", " removeIPL - " +
"Remove an IPL from a virtual machine's directory entry.")
rh.printLn("N", " version - " +
"show the version of the power function")
if rh.subfunction != '':
rh.printLn("N", "Operand(s):")
rh.printLn("N", " -addr <addr> - " +
"Specifies the logical block address of the")
rh.printLn("N", " " +
"boot record.")
rh.printLn("N", " <addrOrNSS> - " +
"Specifies the virtual address or NSS name")
rh.printLn("N", " to IPL.")
rh.printLn("N", " <aeScript> - " +
"aeScript is the fully qualified file")
rh.printLn("N", " " +
"specification of the script to be sent")
rh.printLn("N", " --boot <boot> - " +
"Boot program number")
rh.printLn("N", " --class <class> - " +
"The class is optional and specifies the spool")
rh.printLn("N", " " +
"class for the reader file.")
rh.printLn("N", " <diskPool> - " +
"Specifies the directory manager disk pool to")
rh.printLn("N", " " +
"use to obtain the disk.")
rh.printLn("N", " <diskSize3390> - " +
"Specifies the size of the ECKD minidisk. ")
rh.printLn("N", " <diskSize9336> - " +
"Specifies the size of the FBA type minidisk.")
rh.printLn("N", " <file> - " +
"File to punch to the target system.")
rh.printLn("N", " --filesystem <fsType> - " +
"Specifies type of filesystem to be created on")
rh.printLn("N", " the minidisk.")
rh.printLn("N", " --invparms <invParms> - " +
"Specifies the parameters to be specified in the")
rh.printLn("N", " " +
"invocation script to call the aeScript.")
rh.printLn("N", " --loadparms <loadParms> - " +
"Specifies a 1 to 8-character load parameter that")
rh.printLn("N", " " +
"is used by the IPL'd system.")
rh.printLn("N", " --lun <lun> - " +
"One to eight-byte logical unit number of the")
rh.printLn("N", " FCP-I/O device.")
rh.printLn("N", " --mode <mode> - " +
"Specifies the access mode for the minidisk.")
rh.printLn("N", " --multipw <multi_pw> - " +
"Specifies the password that allows sharing the")
rh.printLn("N", " " +
"minidisk in multiple-write mode.")
rh.printLn("N", " --parms <parmString> - " +
"Specifies a parameter string to pass to the")
rh.printLn("N", " " +
"virtual machine in general-purpose registers at")
rh.printLn("N", " " +
"user's the completion of the IPL.")
rh.printLn("N", " --readpw <read_pw> - " +
"Specifies the password that allows sharing the")
rh.printLn("N", " " +
"minidisk in read mode.")
rh.printLn("N", " --scpdata <scpdata> - " +
"Provides the SCP data information.")
rh.printLn("N", " --scpdatatype <scpdatatype> - " +
"Specifies whether the scp data is in hex,")
rh.printLn("N", " " +
"EBCDIC, or should be deleted.")
rh.printLn("N", " <userid> - " +
"Userid of the target virtual machine.")
rh.printLn("N", " <vAddr> - " +
"Virtual address of the device.")
rh.printLn("N", " --writepw <write_pw> - " +
"Specifies is the password that allows sharing")
rh.printLn("N", " " +
"the minidisk in write mode.")
rh.printLn("N", " --wwpn <wwpn> - " +
"The world-wide port number.")
return | Produce help output related to operands.
Input:
Request Handle | entailment |
def send_request(self, api_name, *api_args, **api_kwargs):
"""Refer to SDK API documentation.
:param api_name: SDK API name
:param *api_args: SDK API sequence parameters
:param **api_kwargs: SDK API keyword parameters
"""
return self.conn.request(api_name, *api_args, **api_kwargs) | Refer to SDK API documentation.
:param api_name: SDK API name
:param *api_args: SDK API sequence parameters
:param **api_kwargs: SDK API keyword parameters | entailment |
def getDiskPoolNames(rh):
"""
Obtain the list of disk pools known to the directory manager.
Input:
Request Handle with the following properties:
function - 'GETHOST'
subfunction - 'DISKPOOLNAMES'
Output:
Request Handle updated with the results.
Return code - 0: ok, non-zero: error
"""
rh.printSysLog("Enter getHost.getDiskPoolNames")
parms = ["-q", "1", "-e", "3", "-T", "dummy"]
results = invokeSMCLI(rh, "Image_Volume_Space_Query_DM", parms)
if results['overallRC'] == 0:
for line in results['response'].splitlines():
poolName = line.partition(' ')[0]
rh.printLn("N", poolName)
else:
# SMAPI API failed.
rh.printLn("ES", results['response'])
rh.updateResults(results) # Use results from invokeSMCLI
rh.printSysLog("Exit getHost.getDiskPoolNames, rc: " +
str(rh.results['overallRC']))
return rh.results['overallRC'] | Obtain the list of disk pools known to the directory manager.
Input:
Request Handle with the following properties:
function - 'GETHOST'
subfunction - 'DISKPOOLNAMES'
Output:
Request Handle updated with the results.
Return code - 0: ok, non-zero: error | entailment |
def getDiskPoolSpace(rh):
"""
Obtain disk pool space information for all or a specific disk pool.
Input:
Request Handle with the following properties:
function - 'GETHOST'
subfunction - 'DISKPOOLSPACE'
parms['poolName'] - Name of the disk pool. Optional,
if not present then information for all
disk pools is obtained.
Output:
Request Handle updated with the results.
Return code - 0: ok, non-zero: error
"""
rh.printSysLog("Enter getHost.getDiskPoolSpace")
results = {'overallRC': 0}
if 'poolName' not in rh.parms:
poolNames = ["*"]
else:
if isinstance(rh.parms['poolName'], list):
poolNames = rh.parms['poolName']
else:
poolNames = [rh.parms['poolName']]
if results['overallRC'] == 0:
# Loop thru each pool getting total. Do it for query 2 & 3
totals = {}
for qType in ["2", "3"]:
parms = [
"-q", qType,
"-e", "3",
"-T", "DUMMY",
"-n", " ".join(poolNames)]
results = invokeSMCLI(rh, "Image_Volume_Space_Query_DM", parms)
if results['overallRC'] == 0:
for line in results['response'].splitlines():
parts = line.split()
if len(parts) == 9:
poolName = parts[7]
else:
poolName = parts[4]
if poolName not in totals:
totals[poolName] = {"2": 0., "3": 0.}
if parts[1][:4] == "3390":
totals[poolName][qType] += int(parts[3]) * 737280
elif parts[1][:4] == "9336":
totals[poolName][qType] += int(parts[3]) * 512
else:
# SMAPI API failed.
rh.printLn("ES", results['response'])
rh.updateResults(results) # Use results from invokeSMCLI
break
if results['overallRC'] == 0:
if len(totals) == 0:
# No pool information found.
msg = msgs.msg['0402'][1] % (modId, " ".join(poolNames))
rh.printLn("ES", msg)
rh.updateResults(msgs.msg['0402'][0])
else:
# Produce a summary for each pool
for poolName in sorted(totals):
total = totals[poolName]["2"] + totals[poolName]["3"]
rh.printLn("N", poolName + " Total: " +
generalUtils.cvtToMag(rh, total))
rh.printLn("N", poolName + " Used: " +
generalUtils.cvtToMag(rh, totals[poolName]["3"]))
rh.printLn("N", poolName + " Free: " +
generalUtils.cvtToMag(rh, totals[poolName]["2"]))
rh.printSysLog("Exit getHost.getDiskPoolSpace, rc: " +
str(rh.results['overallRC']))
return rh.results['overallRC'] | Obtain disk pool space information for all or a specific disk pool.
Input:
Request Handle with the following properties:
function - 'GETHOST'
subfunction - 'DISKPOOLSPACE'
parms['poolName'] - Name of the disk pool. Optional,
if not present then information for all
disk pools is obtained.
Output:
Request Handle updated with the results.
Return code - 0: ok, non-zero: error | entailment |
def getFcpDevices(rh):
"""
Lists the FCP device channels that are active, free, or offline.
Input:
Request Handle with the following properties:
function - 'GETHOST'
subfunction - 'FCPDEVICES'
Output:
Request Handle updated with the results.
Return code - 0: ok, non-zero: error
"""
rh.printSysLog("Enter getHost.getFcpDevices")
parms = ["-T", "dummy"]
results = invokeSMCLI(rh, "System_WWPN_Query", parms)
if results['overallRC'] == 0:
rh.printLn("N", results['response'])
else:
# SMAPI API failed.
rh.printLn("ES", results['response'])
rh.updateResults(results) # Use results from invokeSMCLI
rh.printSysLog("Exit getHost.getFcpDevices, rc: " +
str(rh.results['overallRC']))
return rh.results['overallRC'] | Lists the FCP device channels that are active, free, or offline.
Input:
Request Handle with the following properties:
function - 'GETHOST'
subfunction - 'FCPDEVICES'
Output:
Request Handle updated with the results.
Return code - 0: ok, non-zero: error | entailment |
def getGeneralInfo(rh):
"""
Obtain general information about the host.
Input:
Request Handle with the following properties:
function - 'GETHOST'
subfunction - 'GENERAL'
Output:
Request Handle updated with the results.
Return code - 0: ok
Return code - 4: problem getting some info
"""
rh.printSysLog("Enter getHost.getGeneralInfo")
# Get host using VMCP
rh.results['overallRC'] = 0
cmd = ["sudo", "/sbin/vmcp", "query userid"]
strCmd = ' '.join(cmd)
rh.printSysLog("Invoking: " + strCmd)
try:
host = subprocess.check_output(
cmd,
close_fds=True,
stderr=subprocess.STDOUT)
host = bytes.decode(host)
userid = host.split()[0]
host = host.split()[2]
except subprocess.CalledProcessError as e:
msg = msgs.msg['0405'][1] % (modId, "Hypervisor Name",
strCmd, e.output)
rh.printLn("ES", msg)
rh.updateResults(msgs.msg['0405'][0])
host = "no info"
except Exception as e:
# All other exceptions.
rh.printLn("ES", msgs.msg['0421'][1] % (modId, strCmd,
type(e).__name__, str(e)))
rh.updateResults(msgs.msg['0421'][0])
host = "no info"
# Get a bunch of info from /proc/sysinfo
lparCpuTotal = "no info"
lparCpuUsed = "no info"
cecModel = "no info"
cecVendor = "no info"
hvInfo = "no info"
with open('/proc/sysinfo', 'r') as myFile:
for num, line in enumerate(myFile, 1):
# Get total physical CPU in this LPAR
if "LPAR CPUs Total" in line:
lparCpuTotal = line.split()[3]
# Get used physical CPU in this LPAR
if "LPAR CPUs Configured" in line:
lparCpuUsed = line.split()[3]
# Get CEC model
if "Type:" in line:
cecModel = line.split()[1]
# Get vendor of CEC
if "Manufacturer:" in line:
cecVendor = line.split()[1]
# Get hypervisor type and version
if "VM00 Control Program" in line:
hvInfo = line.split()[3] + " " + line.split()[4]
if lparCpuTotal == "no info":
msg = msgs.msg['0405'][1] % (modId, "LPAR CPUs Total",
"cat /proc/sysinfo", "not found")
rh.printLn("ES", msg)
rh.updateResults(msgs.msg['0405'][0])
if lparCpuUsed == "no info":
msg = msgs.msg['0405'][1] % (modId, "LPAR CPUs Configured",
"cat /proc/sysinfo", "not found")
rh.printLn("ES", msg)
rh.updateResults(msgs.msg['0405'][0])
if cecModel == "no info":
msg = msgs.msg['0405'][1] % (modId, "Type:",
"cat /proc/sysinfo", "not found")
rh.printLn("ES", msg)
rh.updateResults(msgs.msg['0405'][0])
if cecVendor == "no info":
msg = msgs.msg['0405'][1] % (modId, "Manufacturer:",
"cat /proc/sysinfo", "not found")
rh.printLn("ES", msg)
rh.updateResults(msgs.msg['0405'][0])
if hvInfo == "no info":
msg = msgs.msg['0405'][1] % (modId, "VM00 Control Program",
"cat /proc/sysinfo", "not found")
rh.printLn("ES", msg)
rh.updateResults(msgs.msg['0405'][0])
# Get processor architecture
arch = str(os.uname()[4])
# Get LPAR memory total & offline
parm = ["-T", "dummy", "-k", "STORAGE="]
lparMemTotal = "no info"
lparMemStandby = "no info"
results = invokeSMCLI(rh, "System_Information_Query", parm)
if results['overallRC'] == 0:
for line in results['response'].splitlines():
if "STORAGE=" in line:
lparMemOnline = line.split()[0]
lparMemStandby = line.split()[4]
lparMemTotal = lparMemOnline.split("=")[2]
lparMemStandby = lparMemStandby.split("=")[1]
else:
# SMAPI API failed, so we put out messages
# 300 and 405 for consistency
rh.printLn("ES", results['response'])
rh.updateResults(results) # Use results from invokeSMCLI
msg = msgs.msg['0405'][1] % (modId, "LPAR memory",
"(see message 300)", results['response'])
rh.printLn("ES", msg)
# Get LPAR memory in use
parm = ["-T", "dummy", "-k", "detailed_cpu=show=no"]
lparMemUsed = "no info"
results = invokeSMCLI(rh, "System_Performance_Information_Query",
parm)
if results['overallRC'] == 0:
for line in results['response'].splitlines():
if "MEMORY_IN_USE=" in line:
lparMemUsed = line.split("=")[1]
lparMemUsed = generalUtils.getSizeFromPage(rh, lparMemUsed)
else:
# SMAPI API failed, so we put out messages
# 300 and 405 for consistency
rh.printLn("ES", results['response'])
rh.updateResults(results) # Use results from invokeSMCLI
msg = msgs.msg['0405'][1] % (modId, "LPAR memory in use",
"(see message 300)", results['response'])
rh.printLn("ES", msg)
# Get IPL Time
ipl = ""
cmd = ["sudo", "/sbin/vmcp", "query cplevel"]
strCmd = ' '.join(cmd)
rh.printSysLog("Invoking: " + strCmd)
try:
ipl = subprocess.check_output(
cmd,
close_fds=True,
stderr=subprocess.STDOUT)
ipl = bytes.decode(ipl).split("\n")[2]
except subprocess.CalledProcessError as e:
msg = msgs.msg['0405'][1] % (modId, "IPL Time",
strCmd, e.output)
rh.printLn("ES", msg)
rh.updateResults(msgs.msg['0405'][0])
except Exception as e:
# All other exceptions.
rh.printLn("ES", msgs.msg['0421'][1] % (modId, strCmd,
type(e).__name__, str(e)))
rh.updateResults(msgs.msg['0421'][0])
# Create output string
outstr = "ZCC USERID: " + userid
outstr += "\nz/VM Host: " + host
outstr += "\nArchitecture: " + arch
outstr += "\nCEC Vendor: " + cecVendor
outstr += "\nCEC Model: " + cecModel
outstr += "\nHypervisor OS: " + hvInfo
outstr += "\nHypervisor Name: " + host
outstr += "\nLPAR CPU Total: " + lparCpuTotal
outstr += "\nLPAR CPU Used: " + lparCpuUsed
outstr += "\nLPAR Memory Total: " + lparMemTotal
outstr += "\nLPAR Memory Offline: " + lparMemStandby
outstr += "\nLPAR Memory Used: " + lparMemUsed
outstr += "\nIPL Time: " + ipl
rh.printLn("N", outstr)
rh.printSysLog("Exit getHost.getGeneralInfo, rc: " +
str(rh.results['overallRC']))
return rh.results['overallRC'] | Obtain general information about the host.
Input:
Request Handle with the following properties:
function - 'GETHOST'
subfunction - 'GENERAL'
Output:
Request Handle updated with the results.
Return code - 0: ok
Return code - 4: problem getting some info | 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 getHost.parseCmdline")
rh.userid = ''
if rh.totalParms >= 2:
rh.subfunction = rh.request[1].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 = 2 # Begin Parsing at 3rd operand
generalUtils.parseCmdline(rh, posOpsList, keyOpsList)
rh.printSysLog("Exit getHost.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 showInvLines(rh):
"""
Produce help output related to command synopsis
Input:
Request Handle
"""
if rh.subfunction != '':
rh.printLn("N", "Usage:")
rh.printLn("N", " python " + rh.cmdName + " GetHost " +
"diskpoolnames")
rh.printLn("N", " python " + rh.cmdName + " GetHost " +
"diskpoolspace <poolName>")
rh.printLn("N", " python " + rh.cmdName + " GetHost fcpdevices")
rh.printLn("N", " python " + rh.cmdName + " GetHost general")
rh.printLn("N", " python " + rh.cmdName + " GetHost help")
rh.printLn("N", " python " + rh.cmdName + " GetHost version")
return | Produce help output related to command synopsis
Input:
Request Handle | entailment |
def showOperandLines(rh):
"""
Produce help output related to operands.
Input:
Request Handle
"""
if rh.function == 'HELP':
rh.printLn("N", " For the GetHost function:")
else:
rh.printLn("N", "Sub-Functions(s):")
rh.printLn("N", " diskpoolnames - " +
"Returns the names of the directory manager disk pools.")
rh.printLn("N", " diskpoolspace - " +
"Returns disk pool size information.")
rh.printLn("N", " fcpdevices - " +
"Lists the FCP device channels that are active, free, or")
rh.printLn("N", " offline.")
rh.printLn("N", " general - " +
"Returns the general information related to the z/VM")
rh.printLn("N", " hypervisor environment.")
rh.printLn("N", " help - Returns this help information.")
rh.printLn("N", " version - Show the version of this function")
if rh.subfunction != '':
rh.printLn("N", "Operand(s):")
rh.printLn("N", " <poolName> - Name of the disk pool.")
return | Produce help output related to operands.
Input:
Request Handle | entailment |
def deleteMachine(rh):
"""
Delete a virtual machine from the user directory.
Input:
Request Handle with the following properties:
function - 'DELETEVM'
subfunction - 'DIRECTORY'
userid - userid of the virtual machine to be deleted.
Output:
Request Handle updated with the results.
Return code - 0: ok, non-zero: error
"""
rh.printSysLog("Enter deleteVM.deleteMachine")
results = {'overallRC': 0, 'rc': 0, 'rs': 0}
# Is image logged on ?
state = 'on' # Assume 'on'.
results = isLoggedOn(rh, rh.userid)
if results['overallRC'] != 0:
# Cannot determine the log on/off state.
# Message already included. Act as if it is 'on'.
pass
elif results['rs'] == 0:
# State is powered on.
pass
else:
state = 'off'
# Reset values for rest of subfunction
results['overallRC'] = 0
results['rc'] = 0
results['rs'] = 0
if state == 'on':
parms = ["-T", rh.userid, "-f IMMED"]
results = invokeSMCLI(rh, "Image_Deactivate", parms)
if results['overallRC'] == 0:
pass
elif (results['overallRC'] == 8 and results['rc'] == 200 and
(results['rs'] == 12 or results['rs'] == 16)):
# Tolerable error. Machine is already in or going into the state
# that we want it to enter.
rh.updateResults({}, reset=1)
else:
# SMAPI API failed.
rh.printLn("ES", results['response'])
rh.updateResults(results) # Use results returned by invokeSMCLI
# Clean up the reader before delete
if results['overallRC'] == 0:
result = purgeReader(rh)
if result['overallRC'] != 0:
# Tolerable the purge failure error
rh.updateResults({}, reset=1)
if results['overallRC'] == 0:
parms = ["-T", rh.userid, "-e", "0"]
results = invokeSMCLI(rh, "Image_Delete_DM", parms)
if results['overallRC'] != 0:
# SMAPI API failed.
rh.printLn("ES", results['response'])
rh.updateResults(results) # Use results returned by invokeSMCLI
rh.printSysLog("Exit deleteVM.deleteMachine, rc: " +
str(rh.results['overallRC']))
return rh.results['overallRC'] | Delete a virtual machine from the user directory.
Input:
Request Handle with the following properties:
function - 'DELETEVM'
subfunction - 'DIRECTORY'
userid - userid of the virtual machine to be deleted.
Output:
Request Handle updated with the results.
Return code - 0: ok, non-zero: error | entailment |
def activate(rh):
"""
Activate a virtual machine.
Input:
Request Handle with the following properties:
function - 'POWERVM'
subfunction - 'ON'
userid - userid of the virtual machine
parms['desiredState'] - Desired state. Optional,
unless 'maxQueries' is specified.
parms['maxQueries'] - Maximum number of queries to issue.
Optional.
parms['maxWait'] - Maximum time to wait in seconds. Optional,
unless 'maxQueries' is specified.
parms['poll'] - Polling interval in seconds. Optional,
unless 'maxQueries' is specified.
Output:
Request Handle updated with the results.
Return code - 0: ok, non-zero: error
"""
rh.printSysLog("Enter powerVM.activate, userid: " + rh.userid)
parms = ["-T", rh.userid]
smcliResults = invokeSMCLI(rh, "Image_Activate", parms)
if smcliResults['overallRC'] == 0:
pass
elif (smcliResults['overallRC'] == 8 and
smcliResults['rc'] == 200 and smcliResults['rs'] == 8):
pass # All good. No need to change the ReqHandle results.
else:
# SMAPI API failed.
rh.printLn("ES", smcliResults['response'])
rh.updateResults(smcliResults) # Use results from invokeSMCLI
if rh.results['overallRC'] == 0 and 'maxQueries' in rh.parms:
# Wait for the system to be in the desired state of:
# OS is 'up' and reachable or VM is 'on'.
if rh.parms['desiredState'] == 'up':
results = waitForOSState(
rh,
rh.userid,
rh.parms['desiredState'],
maxQueries=rh.parms['maxQueries'],
sleepSecs=rh.parms['poll'])
else:
results = waitForVMState(
rh,
rh.userid,
rh.parms['desiredState'],
maxQueries=rh.parms['maxQueries'],
sleepSecs=rh.parms['poll'])
if results['overallRC'] == 0:
rh.printLn("N", "%s: %s" %
(rh.userid, rh.parms['desiredState']))
else:
rh.updateResults(results)
rh.printSysLog("Exit powerVM.activate, rc: " +
str(rh.results['overallRC']))
return rh.results['overallRC'] | Activate a virtual machine.
Input:
Request Handle with the following properties:
function - 'POWERVM'
subfunction - 'ON'
userid - userid of the virtual machine
parms['desiredState'] - Desired state. Optional,
unless 'maxQueries' is specified.
parms['maxQueries'] - Maximum number of queries to issue.
Optional.
parms['maxWait'] - Maximum time to wait in seconds. Optional,
unless 'maxQueries' is specified.
parms['poll'] - Polling interval in seconds. Optional,
unless 'maxQueries' is specified.
Output:
Request Handle updated with the results.
Return code - 0: ok, non-zero: error | entailment |
def checkIsReachable(rh):
"""
Check if a virtual machine is reachable.
Input:
Request Handle with the following properties:
function - 'POWERVM'
subfunction - 'ISREACHABLE'
userid - userid of the virtual machine
Output:
Request Handle updated with the results.
overallRC - 0: determined the status, non-zero: some weird failure
while trying to execute a command
on the guest via IUCV
rc - RC returned from execCmdThruIUCV
rs - 0: not reachable, 1: reachable
"""
rh.printSysLog("Enter powerVM.checkIsReachable, userid: " +
rh.userid)
strCmd = "echo 'ping'"
results = execCmdThruIUCV(rh, rh.userid, strCmd)
if results['overallRC'] == 0:
rh.printLn("N", rh.userid + ": reachable")
reachable = 1
else:
# A failure from execCmdThruIUCV is acceptable way of determining
# that the system is unreachable. We won't pass along the
# error message.
rh.printLn("N", rh.userid + ": unreachable")
reachable = 0
rh.updateResults({"rs": reachable})
rh.printSysLog("Exit powerVM.checkIsReachable, rc: 0")
return 0 | Check if a virtual machine is reachable.
Input:
Request Handle with the following properties:
function - 'POWERVM'
subfunction - 'ISREACHABLE'
userid - userid of the virtual machine
Output:
Request Handle updated with the results.
overallRC - 0: determined the status, non-zero: some weird failure
while trying to execute a command
on the guest via IUCV
rc - RC returned from execCmdThruIUCV
rs - 0: not reachable, 1: reachable | entailment |
def deactivate(rh):
"""
Deactivate a virtual machine.
Input:
Request Handle with the following properties:
function - 'POWERVM'
subfunction - 'OFF'
userid - userid of the virtual machine
parms['maxQueries'] - Maximum number of queries to issue.
Optional.
parms['maxWait'] - Maximum time to wait in seconds. Optional,
unless 'maxQueries' is specified.
parms['poll'] - Polling interval in seconds. Optional,
unless 'maxQueries' is specified.
Output:
Request Handle updated with the results.
Return code - 0: ok, non-zero: error
"""
rh.printSysLog("Enter powerVM.deactivate, userid: " +
rh.userid)
parms = ["-T", rh.userid, "-f", "IMMED"]
results = invokeSMCLI(rh, "Image_Deactivate", parms)
if results['overallRC'] == 0:
pass
elif (results['overallRC'] == 8 and results['rc'] == 200 and
(results['rs'] == 12 or results['rs'] == 16)):
# Tolerable error. Machine is already in or going into the state
# we want it to enter.
rh.printLn("N", rh.userid + ": off")
rh.updateResults({}, reset=1)
else:
# SMAPI API failed.
rh.printLn("ES", results['response'])
rh.updateResults(results) # Use results from invokeSMCLI
if results['overallRC'] == 0 and 'maxQueries' in rh.parms:
results = waitForVMState(
rh,
rh.userid,
'off',
maxQueries=rh.parms['maxQueries'],
sleepSecs=rh.parms['poll'])
if results['overallRC'] == 0:
rh.printLn("N", rh.userid + ": off")
else:
rh.updateResults(results)
rh.printSysLog("Exit powerVM.deactivate, rc: " +
str(rh.results['overallRC']))
return rh.results['overallRC'] | Deactivate a virtual machine.
Input:
Request Handle with the following properties:
function - 'POWERVM'
subfunction - 'OFF'
userid - userid of the virtual machine
parms['maxQueries'] - Maximum number of queries to issue.
Optional.
parms['maxWait'] - Maximum time to wait in seconds. Optional,
unless 'maxQueries' is specified.
parms['poll'] - Polling interval in seconds. Optional,
unless 'maxQueries' is specified.
Output:
Request Handle updated with the results.
Return code - 0: ok, non-zero: error | entailment |
def getStatus(rh):
"""
Get the power (logon/off) status of a virtual machine.
Input:
Request Handle with the following properties:
function - 'POWERVM'
subfunction - 'STATUS'
userid - userid of the virtual machine
Output:
Request Handle updated with the results.
results['overallRC'] - 0: ok, non-zero: error
if ok:
results['rc'] - 0: for both on and off cases
results['rs'] - 0: powered on
results['rs'] - 1: powered off
"""
rh.printSysLog("Enter powerVM.getStatus, userid: " +
rh.userid)
results = isLoggedOn(rh, rh.userid)
if results['overallRC'] != 0:
# Unexpected error
pass
elif results['rs'] == 0:
rh.printLn("N", rh.userid + ": on")
else:
rh.printLn("N", rh.userid + ": off")
rh.updateResults(results)
rh.printSysLog("Exit powerVM.getStatus, rc: " +
str(rh.results['overallRC']))
return rh.results['overallRC'] | Get the power (logon/off) status of a virtual machine.
Input:
Request Handle with the following properties:
function - 'POWERVM'
subfunction - 'STATUS'
userid - userid of the virtual machine
Output:
Request Handle updated with the results.
results['overallRC'] - 0: ok, non-zero: error
if ok:
results['rc'] - 0: for both on and off cases
results['rs'] - 0: powered on
results['rs'] - 1: powered off | 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 powerVM.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 powerVM.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)
waiting = 0
if rh.results['overallRC'] == 0:
if rh.subfunction == 'WAIT':
waiting = 1
if rh.parms['desiredState'] not in vmOSUpDownStates:
# Desired state is not: down, off, on or up.
msg = msgs.msg['0013'][1] % (modId,
rh.parms['desiredState'], ", ".join(vmOSUpDownStates))
rh.printLn("ES", msg)
rh.updateResults(msgs.msg['0013'][0])
if (rh.results['overallRC'] == 0 and 'wait' in rh.parms):
waiting = 1
if 'desiredState' not in rh.parms:
if rh.subfunction in ['ON', 'RESET', 'REBOOT']:
rh.parms['desiredState'] = 'up'
else:
# OFF and SOFTOFF default to 'off'.
rh.parms['desiredState'] = 'off'
if rh.results['overallRC'] == 0 and waiting == 1:
if rh.subfunction == 'ON' or rh.subfunction == 'RESET':
if ('desiredState' not in rh.parms or
rh.parms['desiredState'] not in vmOSUpStates):
# Desired state is not: on or up.
msg = msgs.msg['0013'][1] % (modId,
rh.parms['desiredState'], ", ".join(vmOSUpStates))
rh.printLn("ES", msg)
rh.updateResults(msgs.msg['0013'][0])
if rh.results['overallRC'] == 0:
if 'maxWait' not in rh.parms:
rh.parms['maxWait'] = 300
if 'poll' not in rh.parms:
rh.parms['poll'] = 15
rh.parms['maxQueries'] = (rh.parms['maxWait'] +
rh.parms['poll'] - 1) / rh.parms['poll']
# If we had to do some rounding, give a warning
# out to the command line user that the wait
# won't be what they expected.
if rh.parms['maxWait'] % rh.parms['poll'] != 0:
msg = msgs.msg['0017'][1] % (modId,
rh.parms['maxWait'], rh.parms['poll'],
rh.parms['maxQueries'] * rh.parms['poll'],
rh.parms['maxQueries'])
rh.printLn("W", msg)
rh.printSysLog("Exit powerVM.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 pause(rh):
"""
Pause a virtual machine.
Input:
Request Handle with the following properties:
function - 'POWERVM'
subfunction - 'PAUSE'
userid - userid of the virtual machine
Output:
Request Handle updated with the results.
Return code - 0: ok, non-zero: error
"""
rh.printSysLog("Enter powerVM.pause, userid: " + rh.userid)
parms = ["-T", rh.userid, "-k", "PAUSE=YES"]
results = invokeSMCLI(rh, "Image_Pause", parms)
if results['overallRC'] != 0:
# SMAPI API failed.
rh.printLn("ES", results['response'])
rh.updateResults(results) # Use results from invokeSMCLI
rh.printSysLog("Exit powerVM.pause, rc: " + str(rh.results['overallRC']))
return rh.results['overallRC'] | Pause a virtual machine.
Input:
Request Handle with the following properties:
function - 'POWERVM'
subfunction - 'PAUSE'
userid - userid of the virtual machine
Output:
Request Handle updated with the results.
Return code - 0: ok, non-zero: error | entailment |
def reboot(rh):
"""
Reboot a virtual machine.
Input:
Request Handle with the following properties:
function - 'POWERVM'
subfunction - 'REBOOT'
userid - userid of the virtual machine
parms['desiredState'] - Desired state. Optional, unless
'maxQueries' is specified.
parms['maxQueries'] - Maximum number of queries to issue.
Optional.
parms['maxWait'] - Maximum time to wait in seconds. Optional,
unless 'maxQueries' is specified.
parms['poll'] - Polling interval in seconds. Optional,
unless 'maxQueries' is specified.
Output:
Request Handle updated with the results.
Return code - 0: ok, non-zero: error
"""
rh.printSysLog("Enter powerVM.reboot, userid: " + rh.userid)
strCmd = "shutdown -r now"
results = execCmdThruIUCV(rh, rh.userid, strCmd)
if results['overallRC'] != 0:
# Command failed to execute using IUCV.
rh.printLn("ES", results['response'])
rh.updateResults(results)
if rh.results['overallRC'] == 0:
# Wait for the OS to go down
results = waitForOSState(rh, rh.userid, "down",
maxQueries=30, sleepSecs=10)
if results['overallRC'] == 0:
rh.printLn("N", rh.userid + ": down (interim state)")
if rh.results['overallRC'] == 0 and 'maxQueries' in rh.parms:
results = waitForOSState(rh,
rh.userid,
'up',
maxQueries=rh.parms['maxQueries'],
sleepSecs=rh.parms['poll'])
if results['overallRC'] == 0:
rh.printLn("N", rh.userid + ": up")
else:
rh.updateResults(results)
rh.printSysLog("Exit powerVM.reboot, rc: " +
str(rh.results['overallRC']))
return rh.results['overallRC'] | Reboot a virtual machine.
Input:
Request Handle with the following properties:
function - 'POWERVM'
subfunction - 'REBOOT'
userid - userid of the virtual machine
parms['desiredState'] - Desired state. Optional, unless
'maxQueries' is specified.
parms['maxQueries'] - Maximum number of queries to issue.
Optional.
parms['maxWait'] - Maximum time to wait in seconds. Optional,
unless 'maxQueries' is specified.
parms['poll'] - Polling interval in seconds. Optional,
unless 'maxQueries' is specified.
Output:
Request Handle updated with the results.
Return code - 0: ok, non-zero: error | entailment |
def reset(rh):
"""
Reset a virtual machine.
Input:
Request Handle with the following properties:
function - 'POWERVM'
subfunction - 'RESET'
userid - userid of the virtual machine
parms['maxQueries'] - Maximum number of queries to issue.
Optional.
parms['maxWait'] - Maximum time to wait in seconds. Optional,
unless 'maxQueries' is specified.
parms['poll'] - Polling interval in seconds. Optional,
unless 'maxQueries' is specified.
Output:
Request Handle updated with the results.
Return code - 0: ok, non-zero: error
"""
rh.printSysLog("Enter powerVM.reset, userid: " + rh.userid)
# Log off the user
parms = ["-T", rh.userid]
results = invokeSMCLI(rh, "Image_Deactivate", parms)
if results['overallRC'] != 0:
if results['rc'] == 200 and results['rs'] == 12:
# Tolerated error. Machine is already in the desired state.
results['overallRC'] = 0
results['rc'] = 0
results['rs'] = 0
else:
# SMAPI API failed.
rh.printLn("ES", results['response'])
rh.updateResults(results) # Use results from invokeSMCLI
# Wait for the logoff to complete
if results['overallRC'] == 0:
results = waitForVMState(rh, rh.userid, "off",
maxQueries=30, sleepSecs=10)
# Log the user back on
if results['overallRC'] == 0:
parms = ["-T", rh.userid]
results = invokeSMCLI(rh, "Image_Activate", parms)
if results['overallRC'] != 0:
# SMAPI API failed.
rh.printLn("ES", results['response'])
rh.updateResults(results) # Use results from invokeSMCLI
if results['overallRC'] == 0 and 'maxQueries' in rh.parms:
if rh.parms['desiredState'] == 'up':
results = waitForOSState(
rh,
rh.userid,
rh.parms['desiredState'],
maxQueries=rh.parms['maxQueries'],
sleepSecs=rh.parms['poll'])
else:
results = waitForVMState(
rh,
rh.userid,
rh.parms['desiredState'],
maxQueries=rh.parms['maxQueries'],
sleepSecs=rh.parms['poll'])
if results['overallRC'] == 0:
rh.printLn("N", rh.userid + ": " +
rh.parms['desiredState'])
else:
rh.updateResults(results)
rh.printSysLog("Exit powerVM.reset, rc: " +
str(rh.results['overallRC']))
return rh.results['overallRC'] | Reset a virtual machine.
Input:
Request Handle with the following properties:
function - 'POWERVM'
subfunction - 'RESET'
userid - userid of the virtual machine
parms['maxQueries'] - Maximum number of queries to issue.
Optional.
parms['maxWait'] - Maximum time to wait in seconds. Optional,
unless 'maxQueries' is specified.
parms['poll'] - Polling interval in seconds. Optional,
unless 'maxQueries' is specified.
Output:
Request Handle updated with the results.
Return code - 0: ok, non-zero: error | entailment |
def softDeactivate(rh):
"""
Deactivate a virtual machine by first shutting down Linux and
then log it off.
Input:
Request Handle with the following properties:
function - 'POWERVM'
subfunction - 'SOFTOFF'
userid - userid of the virtual machine
parms['maxQueries'] - Maximum number of queries to issue.
Optional.
parms['maxWait'] - Maximum time to wait in seconds.
Optional,
unless 'maxQueries' is specified.
parms['poll'] - Polling interval in seconds. Optional,
unless 'maxQueries' is specified.
Output:
Request Handle updated with the results.
Return code - 0: ok, non-zero: error
"""
rh.printSysLog("Enter powerVM.softDeactivate, userid: " +
rh.userid)
strCmd = "echo 'ping'"
iucvResults = execCmdThruIUCV(rh, rh.userid, strCmd)
if iucvResults['overallRC'] == 0:
# We could talk to the machine, tell it to shutdown nicely.
strCmd = "shutdown -h now"
iucvResults = execCmdThruIUCV(rh, rh.userid, strCmd)
if iucvResults['overallRC'] == 0:
time.sleep(15)
else:
# Shutdown failed. Let CP take down the system
# after we log the results.
rh.printSysLog("powerVM.softDeactivate " + rh.userid +
" is unreachable. Treating it as already shutdown.")
else:
# Could not ping the machine. Treat it as a success
# after we log the results.
rh.printSysLog("powerVM.softDeactivate " + rh.userid +
" is unreachable. Treating it as already shutdown.")
# Tell z/VM to log off the system.
parms = ["-T", rh.userid]
smcliResults = invokeSMCLI(rh, "Image_Deactivate", parms)
if smcliResults['overallRC'] == 0:
pass
elif (smcliResults['overallRC'] == 8 and smcliResults['rc'] == 200 and
(smcliResults['rs'] == 12 or + smcliResults['rs'] == 16)):
# Tolerable error.
# Machine is already logged off or is logging off.
rh.printLn("N", rh.userid + " is already logged off.")
else:
# SMAPI API failed.
rh.printLn("ES", smcliResults['response'])
rh.updateResults(smcliResults) # Use results from invokeSMCLI
if rh.results['overallRC'] == 0 and 'maxQueries' in rh.parms:
# Wait for the system to log off.
waitResults = waitForVMState(
rh,
rh.userid,
'off',
maxQueries=rh.parms['maxQueries'],
sleepSecs=rh.parms['poll'])
if waitResults['overallRC'] == 0:
rh.printLn("N", "Userid '" + rh.userid +
" is in the desired state: off")
else:
rh.updateResults(waitResults)
rh.printSysLog("Exit powerVM.softDeactivate, rc: " +
str(rh.results['overallRC']))
return rh.results['overallRC'] | Deactivate a virtual machine by first shutting down Linux and
then log it off.
Input:
Request Handle with the following properties:
function - 'POWERVM'
subfunction - 'SOFTOFF'
userid - userid of the virtual machine
parms['maxQueries'] - Maximum number of queries to issue.
Optional.
parms['maxWait'] - Maximum time to wait in seconds.
Optional,
unless 'maxQueries' is specified.
parms['poll'] - Polling interval in seconds. Optional,
unless 'maxQueries' is specified.
Output:
Request Handle updated with the results.
Return code - 0: ok, non-zero: error | entailment |
def wait(rh):
"""
Wait for the virtual machine to go into the specified state.
Input:
Request Handle with the following properties:
function - 'POWERVM'
subfunction - 'WAIT'
userid - userid of the virtual machine
parms['desiredState'] - Desired state
parms['maxQueries'] - Maximum number of queries to issue
parms['maxWait'] - Maximum time to wait in seconds
parms['poll'] - Polling interval in seconds
Output:
Request Handle updated with the results.
Return code - 0: ok, non-zero: error
"""
rh.printSysLog("Enter powerVM.wait, userid: " + rh.userid)
if (rh.parms['desiredState'] == 'off' or
rh.parms['desiredState'] == 'on'):
results = waitForVMState(
rh,
rh.userid,
rh.parms['desiredState'],
maxQueries=rh.parms['maxQueries'],
sleepSecs=rh.parms['poll'])
else:
results = waitForOSState(
rh,
rh.userid,
rh.parms['desiredState'],
maxQueries=rh.parms['maxQueries'],
sleepSecs=rh.parms['poll'])
if results['overallRC'] == 0:
rh.printLn("N", rh.userid + ": " + rh.parms['desiredState'])
else:
rh.updateResults(results)
rh.printSysLog("Exit powerVM.wait, rc: " + str(rh.results['overallRC']))
return rh.results['overallRC'] | Wait for the virtual machine to go into the specified state.
Input:
Request Handle with the following properties:
function - 'POWERVM'
subfunction - 'WAIT'
userid - userid of the virtual machine
parms['desiredState'] - Desired state
parms['maxQueries'] - Maximum number of queries to issue
parms['maxWait'] - Maximum time to wait in seconds
parms['poll'] - Polling interval in seconds
Output:
Request Handle updated with the results.
Return code - 0: ok, non-zero: error | entailment |
def call(self, func, *api_args, **api_kwargs):
"""Send API call to SDK server and return results"""
if not isinstance(func, str) or (func == ''):
msg = ('Invalid input for API name, should be a'
'string, type: %s specified.') % type(func)
return self._construct_api_name_error(msg)
# Create client socket
try:
cs = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except socket.error as err:
return self._construct_socket_error(1, error=six.text_type(err))
try:
# Set socket timeout
cs.settimeout(self.timeout)
# Connect SDK server
try:
cs.connect((self.addr, self.port))
except socket.error as err:
return self._construct_socket_error(2, addr=self.addr,
port=self.port,
error=six.text_type(err))
# Prepare the data to be sent and switch to bytes if needed
api_data = json.dumps((func, api_args, api_kwargs))
api_data = api_data.encode()
# Send the API call data to SDK server
sent = 0
total_len = len(api_data)
got_error = False
try:
while (sent < total_len):
this_sent = cs.send(api_data[sent:])
if this_sent == 0:
got_error = True
break
sent += this_sent
except socket.error as err:
return self._construct_socket_error(5,
error=six.text_type(err))
if got_error or sent != total_len:
return self._construct_socket_error(3, sent=sent,
api=api_data)
# Receive data from server
return_blocks = []
try:
while True:
block = cs.recv(4096)
if not block:
break
block = bytes.decode(block)
return_blocks.append(block)
except socket.error as err:
# When the sdkserver cann't handle all the client request,
# some client request would be rejected.
# Under this case, the client socket can successfully
# connect/send, but would get exception in recv with error:
# "error: [Errno 104] Connection reset by peer"
return self._construct_socket_error(6,
error=six.text_type(err))
finally:
# Always close the client socket to avoid too many hanging
# socket left.
cs.close()
# Transform the received stream to standard result form
# This client assumes that the server would return result in
# the standard result form, so client just return the received
# data
if return_blocks:
results = json.loads(''.join(return_blocks))
else:
results = self._construct_socket_error(4)
return results | Send API call to SDK server and return results | entailment |
def send_results(self, client, addr, results):
""" send back results to client in the json format of:
{'overallRC': x, 'modID': x, 'rc': x, 'rs': x, 'errmsg': 'msg',
'output': 'out'}
"""
json_results = json.dumps(results)
json_results = json_results.encode()
sent = 0
total_len = len(json_results)
got_error = False
while (sent < total_len):
this_sent = client.send(json_results[sent:])
if this_sent == 0:
got_error = True
break
sent += this_sent
if got_error or sent != total_len:
self.log_error("(%s:%s) Failed to send back results to client, "
"results: %s" % (addr[0], addr[1], json_results))
else:
self.log_debug("(%s:%s) Results sent back to client successfully."
% (addr[0], addr[1])) | send back results to client in the json format of:
{'overallRC': x, 'modID': x, 'rc': x, 'rs': x, 'errmsg': 'msg',
'output': 'out'} | entailment |
def serve_API(self, client, addr):
""" Read client request and call target SDK API"""
self.log_debug("(%s:%s) Handling new request from client." %
(addr[0], addr[1]))
results = None
try:
data = client.recv(4096)
data = bytes.decode(data)
# When client failed to send the data or quit before sending the
# data, server side would receive null data.
# In such case, server would not send back any info and just
# terminate this thread.
if not data:
self.log_warn("(%s:%s) Failed to receive data from client." %
(addr[0], addr[1]))
return
api_data = json.loads(data)
# API_data should be in the form [funcname, args_list, kwargs_dict]
if not isinstance(api_data, list) or len(api_data) != 3:
msg = ("(%s:%s) SDK server got wrong input: '%s' from client."
% (addr[0], addr[1], data))
results = self.construct_internal_error(msg)
return
# Check called API is supported by SDK
(func_name, api_args, api_kwargs) = api_data
self.log_debug("(%s:%s) Request func: %s, args: %s, kwargs: %s" %
(addr[0], addr[1], func_name, str(api_args),
str(api_kwargs)))
try:
api_func = getattr(self.sdkapi, func_name)
except AttributeError:
msg = ("(%s:%s) SDK server got wrong API name: %s from"
"client." % (addr[0], addr[1], func_name))
results = self.construct_api_name_error(msg)
return
# invoke target API function
return_data = api_func(*api_args, **api_kwargs)
except exception.SDKBaseException as e:
self.log_error("(%s:%s) %s" % (addr[0], addr[1],
traceback.format_exc()))
# get the error info from exception attribute
# All SDKbaseexception should eventually has a
# results attribute defined which can be used by
# sdkserver here
if e.results is None:
msg = ("(%s:%s) SDK server got exception without results "
"defined, error: %s" % (addr[0], addr[1],
e.format_message()))
results = self.construct_internal_error(msg)
else:
results = {'overallRC': e.results['overallRC'],
'modID': e.results['modID'],
'rc': e.results['rc'],
'rs': e.results['rs'],
'errmsg': e.format_message(),
'output': ''}
except Exception as e:
self.log_error("(%s:%s) %s" % (addr[0], addr[1],
traceback.format_exc()))
msg = ("(%s:%s) SDK server got unexpected exception: "
"%s" % (addr[0], addr[1], repr(e)))
results = self.construct_internal_error(msg)
else:
if return_data is None:
return_data = ''
results = {'overallRC': 0, 'modID': None,
'rc': 0, 'rs': 0,
'errmsg': '',
'output': return_data}
# Send back the final results
try:
if results is not None:
self.send_results(client, addr, results)
except Exception as e:
# This should not happen in normal case.
# A special case is the server side socket is closed/removed
# before the send() action.
self.log_error("(%s:%s) %s" % (addr[0], addr[1], repr(e)))
finally:
# Close the connection to make sure the thread socket got
# closed even when it got unexpected exceptions.
self.log_debug("(%s:%s) Finish handling request, closing "
"socket." % (addr[0], addr[1]))
client.close() | Read client request and call target SDK API | entailment |
def dispatch(environ, start_response, mapper):
"""Find a matching route for the current request.
:raises: 404(not found) if no match request
405(method not allowed) if route exist but
method not provided.
"""
result = mapper.match(environ=environ)
if result is None:
info = environ.get('PATH_INFO', '')
LOG.debug('The route for %s can not be found', info)
raise webob.exc.HTTPNotFound(
json_formatter=util.json_error_formatter)
handler = result.pop('action')
environ['wsgiorg.routing_args'] = ((), result)
return handler(environ, start_response) | Find a matching route for the current request.
:raises: 404(not found) if no match request
405(method not allowed) if route exist but
method not provided. | entailment |
def handle_not_allowed(environ, start_response):
"""Return a 405 response when method is not allowed.
If _methods are in routing_args, send an allow header listing
the methods that are possible on the provided URL.
"""
_methods = util.wsgi_path_item(environ, '_methods')
headers = {}
if _methods:
headers['allow'] = str(_methods)
raise webob.exc.HTTPMethodNotAllowed(
('The method specified is not allowed for this resource.'),
headers=headers, json_formatter=util.json_error_formatter) | Return a 405 response when method is not allowed.
If _methods are in routing_args, send an allow header listing
the methods that are possible on the provided URL. | entailment |
def make_map(declarations):
"""Process route declarations to create a Route Mapper."""
mapper = routes.Mapper()
for route, methods in ROUTE_LIST:
allowed_methods = []
for method, func in methods.items():
mapper.connect(route, action=func,
conditions=dict(method=[method]))
allowed_methods.append(method)
allowed_methods = ', '.join(allowed_methods)
mapper.connect(route, action=handle_not_allowed,
_methods=allowed_methods)
return mapper | Process route declarations to create a Route Mapper. | entailment |
def _offline_fcp_device(self, fcp, target_wwpn, target_lun, multipath):
"""rhel offline zfcp. sampe to all rhel distro."""
offline_dev = 'chccwdev -d %s' % fcp
delete_records = self._delete_zfcp_config_records(fcp,
target_wwpn,
target_lun)
return '\n'.join((offline_dev,
delete_records)) | rhel offline zfcp. sampe to all rhel distro. | entailment |
def _delete_zfcp_config_records(self, fcp, target_wwpn, target_lun):
"""rhel"""
device = '0.0.%s' % fcp
data = {'wwpn': target_wwpn, 'lun': target_lun,
'device': device, 'zfcpConf': '/etc/zfcp.conf'}
delete_records_cmd = ('sed -i -e '
'\"/%(device)s %(wwpn)s %(lun)s/d\" '
'%(zfcpConf)s\n' % data)
return delete_records_cmd | rhel | entailment |
def _get_source_device_path(self, fcp, target_wwpn, target_lun):
"""rhel"""
device = '0.0.%s' % fcp
data = {'device': device, 'wwpn': target_wwpn, 'lun': target_lun}
var_source_device = ('SourceDevice="/dev/disk/by-path/ccw-%(device)s-'
'zfcp-%(wwpn)s:%(lun)s"\n' % data)
return var_source_device | rhel | entailment |
def _set_sysfs(self, fcp, target_wwpn, target_lun):
"""rhel6 set WWPN and LUN in sysfs"""
device = '0.0.%s' % fcp
port_add = "echo '%s' > " % target_wwpn
port_add += "/sys/bus/ccw/drivers/zfcp/%s/port_add" % device
unit_add = "echo '%s' > " % target_lun
unit_add += "/sys/bus/ccw/drivers/zfcp/%(device)s/%(wwpn)s/unit_add\n"\
% {'device': device, 'wwpn': target_wwpn}
return '\n'.join((port_add,
unit_add)) | rhel6 set WWPN and LUN in sysfs | entailment |
def _set_zfcp_config_files(self, fcp, target_wwpn, target_lun):
"""rhel6 set WWPN and LUN in configuration files"""
device = '0.0.%s' % fcp
set_zfcp_conf = 'echo "%(device)s %(wwpn)s %(lun)s" >> /etc/zfcp.conf'\
% {'device': device, 'wwpn': target_wwpn,
'lun': target_lun}
trigger_uevent = 'echo "add" >> /sys/bus/ccw/devices/%s/uevent\n'\
% device
return '\n'.join((set_zfcp_conf,
trigger_uevent)) | rhel6 set WWPN and LUN in configuration files | entailment |
def _set_sysfs(self, fcp, target_wwpn, target_lun):
"""rhel7 set WWPN and LUN in sysfs"""
device = '0.0.%s' % fcp
unit_add = "echo '%s' > " % target_lun
unit_add += "/sys/bus/ccw/drivers/zfcp/%(device)s/%(wwpn)s/unit_add\n"\
% {'device': device, 'wwpn': target_wwpn}
return unit_add | rhel7 set WWPN and LUN in sysfs | entailment |
def _get_udev_rules(self, channel_read, channel_write, channel_data):
"""construct udev rules info."""
sub_str = '%(read)s %%k %(read)s %(write)s %(data)s qeth' % {
'read': channel_read,
'read': channel_read,
'write': channel_write,
'data': channel_data}
rules_str = '# Configure qeth device at'
rules_str += ' %(read)s/%(write)s/%(data)s\n' % {
'read': channel_read,
'write': channel_write,
'data': channel_data}
rules_str += ('ACTION==\"add\", SUBSYSTEM==\"drivers\", KERNEL=='
'\"qeth\", IMPORT{program}=\"collect %s\"\n') % sub_str
rules_str += ('ACTION==\"add\", SUBSYSTEM==\"ccw\", KERNEL==\"'
'%(read)s\", IMPORT{program}="collect %(channel)s\"\n') % {
'read': channel_read, 'channel': sub_str}
rules_str += ('ACTION==\"add\", SUBSYSTEM==\"ccw\", KERNEL==\"'
'%(write)s\", IMPORT{program}=\"collect %(channel)s\"\n') % {
'write': channel_write, 'channel': sub_str}
rules_str += ('ACTION==\"add\", SUBSYSTEM==\"ccw\", KERNEL==\"'
'%(data)s\", IMPORT{program}=\"collect %(channel)s\"\n') % {
'data': channel_data, 'channel': sub_str}
rules_str += ('ACTION==\"remove\", SUBSYSTEM==\"drivers\", KERNEL==\"'
'qeth\", IMPORT{program}=\"collect --remove %s\"\n') % sub_str
rules_str += ('ACTION==\"remove\", SUBSYSTEM==\"ccw\", KERNEL==\"'
'%(read)s\", IMPORT{program}=\"collect --remove %(channel)s\"\n'
) % {'read': channel_read, 'channel': sub_str}
rules_str += ('ACTION==\"remove\", SUBSYSTEM==\"ccw\", KERNEL==\"'
'%(write)s\", IMPORT{program}=\"collect --remove %(channel)s\"\n'
) % {'write': channel_write, 'channel': sub_str}
rules_str += ('ACTION==\"remove\", SUBSYSTEM==\"ccw\", KERNEL==\"'
'%(data)s\", IMPORT{program}=\"collect --remove %(channel)s\"\n'
) % {'data': channel_data, 'channel': sub_str}
rules_str += ('TEST==\"[ccwgroup/%(read)s]\", GOTO=\"qeth-%(read)s'
'-end\"\n') % {'read': channel_read, 'read': channel_read}
rules_str += ('ACTION==\"add\", SUBSYSTEM==\"ccw\", ENV{COLLECT_'
'%(read)s}==\"0\", ATTR{[drivers/ccwgroup:qeth]group}=\"'
'%(read)s,%(write)s,%(data)s\"\n') % {
'read': channel_read, 'read': channel_read,
'write': channel_write, 'data': channel_data}
rules_str += ('ACTION==\"add\", SUBSYSTEM==\"drivers\", KERNEL==\"qeth'
'\", ENV{COLLECT_%(read)s}==\"0\", ATTR{[drivers/'
'ccwgroup:qeth]group}=\"%(read)s,%(write)s,%(data)s\"\n'
'LABEL=\"qeth-%(read)s-end\"\n') % {
'read': channel_read, 'read': channel_read, 'write': channel_write,
'data': channel_data, 'read': channel_read}
rules_str += ('ACTION==\"add\", SUBSYSTEM==\"ccwgroup\", KERNEL=='
'\"%s\", ATTR{layer2}=\"1\"\n') % channel_read
rules_str += ('ACTION==\"add\", SUBSYSTEM==\"ccwgroup\", KERNEL=='
'\"%s\", ATTR{online}=\"1\"\n') % channel_read
return rules_str | construct udev rules info. | entailment |
def _delete_vdev_info(self, vdev):
"""handle udev rules file."""
vdev = vdev.lower()
rules_file_name = '/etc/udev/rules.d/51-qeth-0.0.%s.rules' % vdev
cmd = 'rm -f %s\n' % rules_file_name
address = '0.0.%s' % str(vdev).zfill(4)
udev_file_name = '/etc/udev/rules.d/70-persistent-net.rules'
cmd += "sed -i '/%s/d' %s\n" % (address, udev_file_name)
cmd += "sed -i '/%s/d' %s\n" % (address,
'/boot/zipl/active_devices.txt')
return cmd | handle udev rules file. | entailment |
def _set_zfcp_config_files(self, fcp, target_wwpn, target_lun):
"""sles set WWPN and LUN in configuration files"""
device = '0.0.%s' % fcp
# host config
host_config = '/sbin/zfcp_host_configure %s 1' % device
# disk config
disk_config = '/sbin/zfcp_disk_configure ' +\
'%(device)s %(wwpn)s %(lun)s 1' %\
{'device': device, 'wwpn': target_wwpn,
'lun': target_lun}
create_config = 'touch /etc/udev/rules.d/51-zfcp-%s.rules' % device
# check if the file already contains the zFCP channel
check_channel = ('out=`cat "/etc/udev/rules.d/51-zfcp-%s.rules" '
'| egrep -i "ccw/%s]online"`\n' % (device, device))
check_channel += 'if [[ ! $out ]]; then\n'
check_channel += (' echo "ACTION==\\"add\\", SUBSYSTEM==\\"ccw\\", '
'KERNEL==\\"%(device)s\\", IMPORT{program}=\\"'
'collect %(device)s %%k %(device)s zfcp\\""'
'| tee -a /etc/udev/rules.d/51-zfcp-%(device)s.rules'
'\n' % {'device': device})
check_channel += (' echo "ACTION==\\"add\\", SUBSYSTEM==\\"drivers\\"'
', KERNEL==\\"zfcp\\", IMPORT{program}=\\"'
'collect %(device)s %%k %(device)s zfcp\\""'
'| tee -a /etc/udev/rules.d/51-zfcp-%(device)s.rules'
'\n' % {'device': device})
check_channel += (' echo "ACTION==\\"add\\", '
'ENV{COLLECT_%(device)s}==\\"0\\", '
'ATTR{[ccw/%(device)s]online}=\\"1\\""'
'| tee -a /etc/udev/rules.d/51-zfcp-%(device)s.rules'
'\n' % {'device': device})
check_channel += 'fi\n'
check_channel += ('echo "ACTION==\\"add\\", KERNEL==\\"rport-*\\", '
'ATTR{port_name}==\\"%(wwpn)s\\", '
'SUBSYSTEMS==\\"ccw\\", KERNELS==\\"%(device)s\\",'
'ATTR{[ccw/%(device)s]%(wwpn)s/unit_add}='
'\\"%(lun)s\\""'
'| tee -a /etc/udev/rules.d/51-zfcp-%(device)s.rules'
'\n' % {'device': device, 'wwpn': target_wwpn,
'lun': target_lun})
return '\n'.join((host_config,
'sleep 2',
disk_config,
'sleep 2',
create_config,
check_channel)) | sles set WWPN and LUN in configuration files | entailment |
def _set_zfcp_multipath(self):
"""sles"""
# modprobe DM multipath kernel module
modprobe = 'modprobe dm_multipath'
conf_file = '#blacklist {\n'
conf_file += '#\tdevnode \\"*\\"\n'
conf_file += '#}\n'
conf_cmd = 'echo -e "%s" > /etc/multipath.conf' % conf_file
restart = self._restart_multipath()
return '\n'.join((modprobe,
conf_cmd,
restart)) | sles | entailment |
def _offline_fcp_device(self, fcp, target_wwpn, target_lun, multipath):
"""sles offline zfcp. sampe to all rhel distro."""
device = '0.0.%s' % fcp
# disk config
disk_config = '/sbin/zfcp_disk_configure ' +\
'%(device)s %(wwpn)s %(lun)s 0' %\
{'device': device, 'wwpn': target_wwpn,
'lun': target_lun}
# host config
host_config = '/sbin/zfcp_host_configure %s 0' % device
return '\n'.join((disk_config,
host_config)) | sles offline zfcp. sampe to all rhel distro. | entailment |
def create_network_configuration_files(self, file_path, guest_networks,
first, active=False):
"""Generate network configuration files for guest vm
: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,
'dns_addr': (list) dns addresses,
'gateway_addr': (str) gateway address,
'cidr': (str) cidr format
'nic_vdev': (str) VDEV of the nic}
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'},
{'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}]
"""
cfg_files = []
cmd_strings = ''
network_config_file_name = self._get_network_file()
network_cfg_str = 'auto lo\n'
network_cfg_str += 'iface lo inet loopback\n'
net_enable_cmd = ''
if first:
clean_cmd = self._get_clean_command()
else:
clean_cmd = ''
network_cfg_str = ''
for network in guest_networks:
base_vdev = network['nic_vdev'].lower()
network_hw_config_fname = self._get_device_filename(base_vdev)
network_hw_config_str = self._get_network_hw_config_str(base_vdev)
cfg_files.append((network_hw_config_fname, network_hw_config_str))
(cfg_str, dns_str) = self._generate_network_configuration(network,
base_vdev)
LOG.debug('Network configure file content is: %s', cfg_str)
network_cfg_str += cfg_str
if len(dns_str) > 0:
network_cfg_str += dns_str
if first:
cfg_files.append((network_config_file_name, network_cfg_str))
else:
cmd_strings = ('echo "%s" >>%s\n' % (network_cfg_str,
network_config_file_name))
return cfg_files, cmd_strings, clean_cmd, net_enable_cmd | Generate network configuration files for guest vm
: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,
'dns_addr': (list) dns addresses,
'gateway_addr': (str) gateway address,
'cidr': (str) cidr format
'nic_vdev': (str) VDEV of the nic}
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'},
{'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}] | entailment |
def _delete_vdev_info(self, vdev):
"""handle vdev related info."""
vdev = vdev.lower()
network_config_file_name = self._get_network_file()
device = self._get_device_name(vdev)
cmd = '\n'.join(("num=$(sed -n '/auto %s/=' %s)" % (device,
network_config_file_name),
"dns=$(awk 'NR==(\"\'$num\'\"+6)&&"
"/dns-nameservers/' %s)" %
network_config_file_name,
"if [[ -n $dns ]]; then",
" sed -i '/auto %s/,+6d' %s" % (device,
network_config_file_name),
"else",
" sed -i '/auto %s/,+5d' %s" % (device,
network_config_file_name),
"fi"))
return cmd | handle vdev related info. | entailment |
def _set_zfcp_config_files(self, fcp, target_wwpn, target_lun):
"""ubuntu zfcp configuration """
host_config = '/sbin/chzdev zfcp-host %s -e' % fcp
device = '0.0.%s' % fcp
target = '%s:%s:%s' % (device, target_wwpn, target_lun)
disk_config = '/sbin/chzdev zfcp-lun %s -e\n' % target
return '\n'.join((host_config,
disk_config)) | ubuntu zfcp configuration | entailment |
def _offline_fcp_device(self, fcp, target_wwpn, target_lun, multipath):
"""ubuntu offline zfcp."""
device = '0.0.%s' % fcp
target = '%s:%s:%s' % (device, target_wwpn, target_lun)
disk_offline = '/sbin/chzdev zfcp-lun %s -d' % target
host_offline = '/sbin/chzdev zfcp-host %s -d' % fcp
offline_dev = 'chccwdev -d %s' % fcp
return '\n'.join((disk_offline,
host_offline,
offline_dev)) | ubuntu offline zfcp. | entailment |
def parse_dist(self, os_version):
"""Separate os and version from os_version.
Possible return value are only:
('rhel', x.y) and ('sles', x.y) where x.y may not be digits
"""
supported = {'rhel': ['rhel', 'redhat', 'red hat'],
'sles': ['suse', 'sles'],
'ubuntu': ['ubuntu']}
os_version = os_version.lower()
for distro, patterns in supported.items():
for i in patterns:
if os_version.startswith(i):
# Not guarrentee the version is digital
remain = os_version.split(i, 2)[1]
release = self._parse_release(os_version, distro, remain)
return distro, release
msg = 'Can not handle os: %s' % os_version
raise exception.ZVMException(msg=msg) | Separate os and version from os_version.
Possible return value are only:
('rhel', x.y) and ('sles', x.y) where x.y may not be digits | entailment |
def getStatus(rh):
"""
Get status of a VMRelocate request.
Input:
Request Handle with the following properties:
function - 'MIGRATEVM'
subfunction - 'STATUS'
userid - userid of the virtual machine
parms['all'] - If present, set status_target to ALL.
parms['incoming'] - If present, set status_target to INCOMING.
parms['outgoing'] - If present, set status_target to OUTGOING.
if parms does not contain 'all', 'incoming' or 'outgoing', the
status_target is set to 'USER <userid>'.
Output:
Request Handle updated with the results.
Return code - 0: ok, non-zero: error
"""
rh.printSysLog("Enter migrateVM.getStatus")
parms = ["-T", rh.userid]
if 'all' in rh.parms:
parms.extend(["-k", "status_target=ALL"])
elif 'incoming' in rh.parms:
parms.extend(["-k", "status_target=INCOMING"])
elif 'outgoing' in rh.parms:
parms.extend(["-k", "status_target=OUTGOING"])
else:
parms.extend(["-k", "status_target=USER " + rh.userid + ""])
results = invokeSMCLI(rh, "VMRELOCATE_Status", parms)
if results['overallRC'] != 0:
# SMAPI API failed.
rh.printLn("ES", results['response'])
rh.updateResults(results) # Use results from invokeSMCLI
if results['rc'] == 4 and results['rs'] == 3001:
# No relocation in progress
msg = msgs.msg['0419'][1] % (modId, rh.userid)
rh.printLn("ES", msg)
rh.updateResults(msgs.msg['0419'][0])
else:
rh.printLn("N", results['response'])
rh.printSysLog("Exit migrateVM.getStatus, rc: " +
str(rh.results['overallRC']))
return rh.results['overallRC'] | Get status of a VMRelocate request.
Input:
Request Handle with the following properties:
function - 'MIGRATEVM'
subfunction - 'STATUS'
userid - userid of the virtual machine
parms['all'] - If present, set status_target to ALL.
parms['incoming'] - If present, set status_target to INCOMING.
parms['outgoing'] - If present, set status_target to OUTGOING.
if parms does not contain 'all', 'incoming' or 'outgoing', the
status_target is set to 'USER <userid>'.
Output:
Request Handle updated with the results.
Return code - 0: ok, non-zero: error | entailment |
def driveFunction(self):
"""
Drive the function/subfunction call.
Input:
Self with request filled in.
Output:
Request Handle updated with the results.
Overall return code - 0: successful, non-zero: error
"""
if self.function == 'HELP':
# General help for all functions.
self.printLn("N", "")
self.printLn("N", "Usage:")
self.printLn("N", " python " + self.cmdName + " --help")
for key in sorted(ReqHandle.funcHandler):
ReqHandle.funcHandler[key][0](self)
self.printLn("N", "")
self.printLn("N", "Operand(s):")
for key in sorted(ReqHandle.funcHandler):
ReqHandle.funcHandler[key][1](self)
self.printLn("N", "")
self.updateResults({}, reset=1)
elif self.function == 'VERSION':
# Version of ReqHandle.
self.printLn("N", "Version: " + version)
self.updateResults({}, reset=1)
else:
# Some type of function/subfunction invocation.
if self.function in self.funcHandler:
# Invoke the functions doIt routine to route to the
# appropriate subfunction.
self.funcHandler[self.function][3](self)
else:
# Unrecognized function
msg = msgs.msg['0007'][1] % (modId, self.function)
self.printLn("ES", msg)
self.updateResults(msgs.msg['0007'][0])
return self.results | Drive the function/subfunction call.
Input:
Self with request filled in.
Output:
Request Handle updated with the results.
Overall return code - 0: successful, non-zero: error | entailment |
def parseCmdline(self, requestData):
"""
Parse the request command string.
Input:
Self with request filled in.
Output:
Request Handle updated with the parsed information so that
it is accessible via key/value pairs for later processing.
Return code - 0: successful, non-zero: error
"""
self.printSysLog("Enter ReqHandle.parseCmdline")
# Save the request data based on the type of operand.
if isinstance(requestData, list):
self.requestString = ' '.join(requestData) # Request as a string
self.request = requestData # Request as a list
elif isinstance(requestData, string_types):
self.requestString = requestData # Request as a string
self.request = shlex.split(requestData) # Request as a list
else:
# Request data type is not supported.
msg = msgs.msg['0012'][1] % (modId, type(requestData))
self.printLn("ES", msg)
self.updateResults(msgs.msg['0012'][0])
return self.results
self.totalParms = len(self.request) # Number of parms in the cmd
# Handle the request, parse it or return an error.
if self.totalParms == 0:
# Too few arguments.
msg = msgs.msg['0009'][1] % modId
self.printLn("ES", msg)
self.updateResults(msgs.msg['0009'][0])
elif self.totalParms == 1:
self.function = self.request[0].upper()
if self.function == 'HELP' or self.function == 'VERSION':
pass
else:
# Function is not HELP or VERSION.
msg = msgs.msg['0008'][1] % (modId, self.function)
self.printLn("ES", msg)
self.updateResults(msgs.msg['0008'][0])
else:
# Process based on the function operand.
self.function = self.request[0].upper()
if self.request[0] == 'HELP' or self.request[0] == 'VERSION':
pass
else:
# Handle the function related parms by calling the function
# parser.
if self.function in ReqHandle.funcHandler:
self.funcHandler[self.function][2](self)
else:
# Unrecognized function
msg = msgs.msg['0007'][1] % (modId, self.function)
self.printLn("ES", msg)
self.updateResults(msgs.msg['0007'][0])
self.printSysLog("Exit ReqHandle.parseCmdline, rc: " +
str(self.results['overallRC']))
return self.results | Parse the request command string.
Input:
Self with request filled in.
Output:
Request Handle updated with the parsed information so that
it is accessible via key/value pairs for later processing.
Return code - 0: successful, non-zero: error | entailment |
def printLn(self, respType, respString):
"""
Add one or lines of output to the response list.
Input:
Response type: One or more characters indicate type of response.
E - Error message
N - Normal message
S - Output should be logged
W - Warning message
"""
if 'E' in respType:
respString = '(Error) ' + respString
if 'W' in respType:
respString = '(Warning) ' + respString
if 'S' in respType:
self.printSysLog(respString)
self.results['response'] = (self.results['response'] +
respString.splitlines())
return | Add one or lines of output to the response list.
Input:
Response type: One or more characters indicate type of response.
E - Error message
N - Normal message
S - Output should be logged
W - Warning message | entailment |
def printSysLog(self, logString):
"""
Log one or more lines. Optionally, add them to logEntries list.
Input:
Strings to be logged.
"""
if zvmsdklog.LOGGER.getloglevel() <= logging.DEBUG:
# print log only when debug is enabled
if self.daemon == '':
self.logger.debug(self.requestId + ": " + logString)
else:
self.daemon.logger.debug(self.requestId + ": " + logString)
if self.captureLogs is True:
self.results['logEntries'].append(self.requestId + ": " +
logString)
return | Log one or more lines. Optionally, add them to logEntries list.
Input:
Strings to be logged. | entailment |
def updateResults(self, newResults, **kwArgs):
"""
Update the results related to this request excluding the 'response'
and 'logEntries' values.
We specifically update (if present):
overallRC, rc, rs, errno.
Input:
Dictionary containing the results to be updated or an empty
dictionary the reset keyword was specified.
Reset keyword:
0 - Not a reset. This is the default is reset keyword was not
specified.
1 - Reset failure related items in the result dictionary.
This exclude responses and log entries.
2 - Reset all result items in the result dictionary.
Output:
Request handle is updated with the results.
"""
if 'reset' in kwArgs.keys():
reset = kwArgs['reset']
else:
reset = 0
if reset == 0:
# Not a reset. Set the keys from the provided dictionary.
for key in newResults.keys():
if key == 'response' or key == 'logEntries':
continue
self.results[key] = newResults[key]
elif reset == 1:
# Reset all failure related items.
self.results['overallRC'] = 0
self.results['rc'] = 0
self.results['rs'] = 0
self.results['errno'] = 0
self.results['strError'] = ''
elif reset == 2:
# Reset all results information including any responses and
# log entries.
self.results['overallRC'] = 0
self.results['rc'] = 0
self.results['rs'] = 0
self.results['errno'] = 0
self.results['strError'] = ''
self.results['logEntries'] = ''
self.results['response'] = ''
return | Update the results related to this request excluding the 'response'
and 'logEntries' values.
We specifically update (if present):
overallRC, rc, rs, errno.
Input:
Dictionary containing the results to be updated or an empty
dictionary the reset keyword was specified.
Reset keyword:
0 - Not a reset. This is the default is reset keyword was not
specified.
1 - Reset failure related items in the result dictionary.
This exclude responses and log entries.
2 - Reset all result items in the result dictionary.
Output:
Request handle is updated with the results. | entailment |
def filter(self, field, operator, value):
""" Add a query filter to be applied to the next API list call for this resource.
:param field: Field name to filter by
:type field: str
:param operator: Operator value
:type operator: str
:param value: Value of filter
:type value: str
:param object_type: Optional. Checks field for object association
:type object_type: str
Known Filters:
Question [question(2)] surveyresponse
Question Option [question(2), option(10001)] surveyresponse
Date Submitted datesubmitted surveyresponse
Is Test Data istestdata surveyresponse
Status status surveyresponse
Contact ID contact_id surveyresponse
Creation Time createdon survey
Last Modified Time modifiedon survey
Survey Title title survey
Type of Project subtype survey
Team Survey Belongs To team survey
Status status survey
Type of Link type surveycampaign
Name of Link name surveycampaign
Secure / Unsecure Link ssl surveycampaign
Link Created Date datecreated surveycampaign
Link Last Modified Date datemodified surveycampaign
Known Operators:
= Is equal to (==)
<> Is equal to (!=)
IS NULL Value is not answered or is blank
IS NOT NULL Value is answered or is not blank
in Value is in comma separated list
Unknown Operators:
Not officially mentioned in documentation, but may work.
==
!=
>=
<=
>
<
"""
instance = copy(self)
i = len(instance._filters)
instance._filters.append({
'filter[field][%d]' % i: str(field),
'filter[operator][%d]' % i: str(operator),
'filter[value][%d]' % i: str(value),
})
return instance | Add a query filter to be applied to the next API list call for this resource.
:param field: Field name to filter by
:type field: str
:param operator: Operator value
:type operator: str
:param value: Value of filter
:type value: str
:param object_type: Optional. Checks field for object association
:type object_type: str
Known Filters:
Question [question(2)] surveyresponse
Question Option [question(2), option(10001)] surveyresponse
Date Submitted datesubmitted surveyresponse
Is Test Data istestdata surveyresponse
Status status surveyresponse
Contact ID contact_id surveyresponse
Creation Time createdon survey
Last Modified Time modifiedon survey
Survey Title title survey
Type of Project subtype survey
Team Survey Belongs To team survey
Status status survey
Type of Link type surveycampaign
Name of Link name surveycampaign
Secure / Unsecure Link ssl surveycampaign
Link Created Date datecreated surveycampaign
Link Last Modified Date datemodified surveycampaign
Known Operators:
= Is equal to (==)
<> Is equal to (!=)
IS NULL Value is not answered or is blank
IS NOT NULL Value is answered or is not blank
in Value is in comma separated list
Unknown Operators:
Not officially mentioned in documentation, but may work.
==
!=
>=
<=
>
< | entailment |
def resultsperpage(self, value):
""" Set the number of results that will be retrieved by the request.
:param value: 'resultsperpage' parameter value for the rest api call
:type value: str
Take a look at https://apihelp.surveygizmo.com/help/surveyresponse-sub-object
"""
instance = copy(self)
instance._filters.append({
'resultsperpage': value
})
return instance | Set the number of results that will be retrieved by the request.
:param value: 'resultsperpage' parameter value for the rest api call
:type value: str
Take a look at https://apihelp.surveygizmo.com/help/surveyresponse-sub-object | entailment |
def page(self, value):
""" Set the page which will be returned.
:param value: 'page' parameter value for the rest api call
:type value: str
Take a look at https://apihelp.surveygizmo.com/help/surveyresponse-sub-object
"""
instance = copy(self)
instance._filters.append({
'page': value
})
return instance | Set the page which will be returned.
:param value: 'page' parameter value for the rest api call
:type value: str
Take a look at https://apihelp.surveygizmo.com/help/surveyresponse-sub-object | entailment |
def filters(self):
"""
Returns a merged dictionary of filters.
"""
params = {}
for _filter in self._filters:
params.update(_filter)
return params | Returns a merged dictionary of filters. | entailment |
def json_error_formatter(body, status, title, environ):
"""A json_formatter for webob exceptions."""
body = webob.exc.strip_tags(body)
status_code = int(status.split(None, 1)[0])
error_dict = {
'status': status_code,
'title': title,
'detail': body
}
return {'errors': [error_dict]} | A json_formatter for webob exceptions. | entailment |
def call_func(self, req, *args, **kwargs):
"""Add json_error_formatter to any webob HTTPExceptions."""
try:
return super(SdkWsgify, self).call_func(req, *args, **kwargs)
except webob.exc.HTTPException as exc:
msg = ('encounter %(error)s error') % {'error': exc}
LOG.debug(msg)
exc.json_formatter = json_error_formatter
code = exc.status_int
explanation = six.text_type(exc)
fault_data = {
'overallRC': 400,
'rc': 400,
'rs': code,
'modID': SDKWSGI_MODID,
'output': '',
'errmsg': explanation}
exc.text = six.text_type(json.dumps(fault_data))
raise exc | Add json_error_formatter to any webob HTTPExceptions. | entailment |
def _load_GeoTransform(self):
"""Calculate latitude and longitude variable calculated from the
gdal.Open.GetGeoTransform method"""
def load_lon():
return arange(ds.RasterXSize)*b[1]+b[0]
def load_lat():
return arange(ds.RasterYSize)*b[5]+b[3]
ds = self.ds
b = self.ds.GetGeoTransform() # bbox, interval
if with_dask:
lat = Array(
{('lat', 0): (load_lat,)}, 'lat', (self.ds.RasterYSize,),
shape=(self.ds.RasterYSize,), dtype=float)
lon = Array(
{('lon', 0): (load_lon,)}, 'lon', (self.ds.RasterXSize,),
shape=(self.ds.RasterXSize,), dtype=float)
else:
lat = load_lat()
lon = load_lon()
return Variable(('lat',), lat), Variable(('lon',), lon) | Calculate latitude and longitude variable calculated from the
gdal.Open.GetGeoTransform method | entailment |
def psyplot_fname(env_key='PSYPLOTRC', fname='psyplotrc.yml',
if_exists=True):
"""
Get the location of the config file.
The file location is determined in the following order
- `$PWD/psyplotrc.yml`
- environment variable `PSYPLOTRC` (pointing to the file location or a
directory containing the file `psyplotrc.yml`)
- `$PSYPLOTCONFIGDIR/psyplot`
- On Linux and osx,
- `$HOME/.config/psyplot/psyplotrc.yml`
- On other platforms,
- `$HOME/.psyplot/psyplotrc.yml` if `$HOME` is defined.
- Lastly, it looks in `$PSYPLOTDATA/psyplotrc.yml` for a
system-defined copy.
Parameters
----------
env_key: str
The environment variable that can be used for the configuration
directory
fname: str
The name of the configuration file
if_exists: bool
If True, the path is only returned if the file exists
Returns
-------
None or str
None, if no file could be found and `if_exists` is True, else the path
to the psyplot configuration file
Notes
-----
This function is motivated by the :func:`matplotlib.matplotlib_fname`
function"""
cwd = getcwd()
full_fname = os.path.join(cwd, fname)
if os.path.exists(full_fname):
return full_fname
if env_key in os.environ:
path = os.environ[env_key]
if os.path.exists(path):
if os.path.isdir(path):
full_fname = os.path.join(path, fname)
if os.path.exists(full_fname):
return full_fname
else:
return path
configdir = get_configdir()
if configdir is not None:
full_fname = os.path.join(configdir, fname)
if os.path.exists(full_fname) or not if_exists:
return full_fname
return None | Get the location of the config file.
The file location is determined in the following order
- `$PWD/psyplotrc.yml`
- environment variable `PSYPLOTRC` (pointing to the file location or a
directory containing the file `psyplotrc.yml`)
- `$PSYPLOTCONFIGDIR/psyplot`
- On Linux and osx,
- `$HOME/.config/psyplot/psyplotrc.yml`
- On other platforms,
- `$HOME/.psyplot/psyplotrc.yml` if `$HOME` is defined.
- Lastly, it looks in `$PSYPLOTDATA/psyplotrc.yml` for a
system-defined copy.
Parameters
----------
env_key: str
The environment variable that can be used for the configuration
directory
fname: str
The name of the configuration file
if_exists: bool
If True, the path is only returned if the file exists
Returns
-------
None or str
None, if no file could be found and `if_exists` is True, else the path
to the psyplot configuration file
Notes
-----
This function is motivated by the :func:`matplotlib.matplotlib_fname`
function | entailment |
def validate_path_exists(s):
"""If s is a path, return s, else False"""
if s is None:
return None
if os.path.exists(s):
return s
else:
raise ValueError('"%s" should be a path but it does not exist' % s) | If s is a path, return s, else False | entailment |
def validate_dict(d):
"""Validate a dictionary
Parameters
----------
d: dict or str
If str, it must be a path to a yaml file
Returns
-------
dict
Raises
------
ValueError"""
try:
return dict(d)
except TypeError:
d = validate_path_exists(d)
try:
with open(d) as f:
return dict(yaml.load(f))
except Exception:
raise ValueError("Could not convert {} to dictionary!".format(d)) | Validate a dictionary
Parameters
----------
d: dict or str
If str, it must be a path to a yaml file
Returns
-------
dict
Raises
------
ValueError | entailment |
def validate_bool_maybe_none(b):
'Convert b to a boolean or raise'
if isinstance(b, six.string_types):
b = b.lower()
if b is None or b == 'none':
return None
return validate_bool(b) | Convert b to a boolean or raise | entailment |
def validate_bool(b):
"""Convert b to a boolean or raise"""
if isinstance(b, six.string_types):
b = b.lower()
if b in ('t', 'y', 'yes', 'on', 'true', '1', 1, True):
return True
elif b in ('f', 'n', 'no', 'off', 'false', '0', 0, False):
return False
else:
raise ValueError('Could not convert "%s" to boolean' % b) | Convert b to a boolean or raise | entailment |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.