desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Print arguments for bash_completion. Prints all of the commands and options to stdout so that the monitor.bash_completion script doesn\'t have to hard code them.'
def do_bash_completion(self, args):
commands = set() options = set() for (sc_str, sc) in self.subcommands.items(): commands.add(sc_str) for option in sc._optionals._option_string_actions.keys(): options.add(option) commands.remove('bash-completion') commands.remove('bash_completion') print ' '.join((...
'Display help about this program or one of its subcommands.'
@utils.arg('command', metavar='<subcommand>', nargs='?', help='Display help for <subcommand>') def do_help(self, args):
if args.command: if (args.command in self.subcommands): self.subcommands[args.command].print_help() else: raise exc.CommandError(("'%s' is not a valid subcommand" % args.command)) else: self.parser.print_help()
'Ignores the passed in args.'
def __init__(self, *args, **kwargs):
self.cache = {}
'Retrieves the value for a key or None. this expunges expired keys during each get'
def get(self, key):
now = timeutils.utcnow_ts() for k in self.cache.keys(): (timeout, _value) = self.cache[k] if (timeout and (now >= timeout)): del self.cache[k] return self.cache.get(key, (0, None))[1]
'Sets the value for a key.'
def set(self, key, value, time=0, min_compress_len=0):
timeout = 0 if (time != 0): timeout = (timeutils.utcnow_ts() + time) self.cache[key] = (timeout, value) return True
'Sets the value for a key if it doesn\'t exist.'
def add(self, key, value, time=0, min_compress_len=0):
if (self.get(key) is not None): return False return self.set(key, value, time, min_compress_len)
'Increments the value for a key.'
def incr(self, key, delta=1):
value = self.get(key) if (value is None): return None new_value = (int(value) + delta) self.cache[key] = (self.cache[key][0], str(new_value)) return new_value
'Deletes the value associated with a key.'
def delete(self, key, time=0):
if (key in self.cache): del self.cache[key]
'Object that understands versioning for a package :param package: name of the python package, such as glance, or python-glanceclient'
def __init__(self, package):
self.package = package self.release = None self.version = None self._cached_version = None
'Make the VersionInfo object behave like a string.'
def __str__(self):
return self.version_string()
'Include the name.'
def __repr__(self):
return ('VersionInfo(%s:%s)' % (self.package, self.version_string()))
'Get the version of the package from the pkg_resources record associated with the package.'
def _get_version_from_pkg_resources(self):
try: requirement = pkg_resources.Requirement.parse(self.package) provider = pkg_resources.get_provider(requirement) return provider.version except pkg_resources.DistributionNotFound: from monitorclient.openstack.common import setup return setup.get_version(self.package)
'Return the full version of the package including suffixes indicating VCS status.'
def release_string(self):
if (self.release is None): self.release = self._get_version_from_pkg_resources() return self.release
'Return the short version minus any alpha/beta tags.'
def version_string(self):
if (self.version is None): parts = [] for part in self.release_string().split('.'): if part[0].isdigit(): parts.append(part) else: break self.version = '.'.join(parts) return self.version
'Generate an object which will expand in a string context to the results of version_string(). We do this so that don\'t call into pkg_resources every time we start up a program when passing version information into the CONF constructor, but rather only do the calculation when and if a version is requested'
def cached_version_string(self, prefix=''):
if (not self._cached_version): self._cached_version = ('%s%s' % (prefix, self.version_string())) return self._cached_version
'Restore a backup to a monitor. :param backup_id: The ID of the backup to restore. :param monitor_id: The ID of the monitor to restore the backup to. :rtype: :class:`Restore`'
def restore(self, backup_id, monitor_id=None):
body = {'restore': {'monitor_id': monitor_id}} return self._create(('/backups/%s/restore' % backup_id), body, 'restore')
'QuotaClassSet does not have a \'id\' attribute but base.Resource needs it to self-refresh and QuotaSet is indexed by class_name'
@property def id(self):
return self.class_name
'Authenticate against the server. Normally this is called automatically when you first access the API, but you can call this method to force authentication right now. Returns on success; raises :exc:`exceptions.Unauthorized` if the credentials are wrong.'
def authenticate(self):
self.client.authenticate()
'Get extra specs from a monitor type. :param vol_type: The :class:`ServiceManageType` to get extra specs from'
def get_keys(self):
(_resp, body) = self.manager.api.client.get(('/types/%s/extra_specs' % base.getid(self))) return body['extra_specs']
'Set extra specs on a monitor type. :param type : The :class:`ServiceManageType` to set extra spec on :param metadata: A dict of key/value pairs to be set'
def set_keys(self, metadata):
body = {'extra_specs': metadata} return self.manager._create(('/types/%s/extra_specs' % base.getid(self)), body, 'extra_specs', return_raw=True)
'Unset extra specs on a volue type. :param type_id: The :class:`ServiceManageType` to unset extra spec on :param keys: A list of keys to be unset'
def unset_keys(self, keys):
resp = None for k in keys: resp = self.manager._delete(('/types/%s/extra_specs/%s' % (base.getid(self), k))) if (resp is not None): return resp
'Get a list of all monitor types. :rtype: list of :class:`ServiceManageType`.'
def list(self):
return self._list('/types', 'monitor_types')
'Get a specific monitor type. :param monitor_type: The ID of the :class:`ServiceManageType` to get. :rtype: :class:`ServiceManageType`'
def get(self, monitor_type):
return self._get(('/types/%s' % base.getid(monitor_type)), 'monitor_type')
'Delete a specific monitor_type. :param monitor_type: The ID of the :class:`ServiceManageType` to get.'
def delete(self, monitor_type):
self._delete(('/types/%s' % base.getid(monitor_type)))
'Create a monitor type. :param name: Descriptive name of the monitor type :rtype: :class:`ServiceManageType`'
def create(self, name):
body = {'monitor_type': {'name': name}} return self._create('/types', body, 'monitor_type')
'Delete this monitor backup.'
def delete(self):
return self.manager.delete(self)
'Create a monitor backup. :param monitor_id: The ID of the monitor to backup. :param container: The name of the backup service container. :param name: The name of the backup. :param description: The description of the backup. :rtype: :class:`ServiceManageBackup`'
def create(self, monitor_id, container=None, name=None, description=None):
body = {'backup': {'monitor_id': monitor_id, 'container': container, 'name': name, 'description': description}} return self._create('/backups', body, 'backup')
'Show details of a monitor backup. :param backup_id: The ID of the backup to display. :rtype: :class:`ServiceManageBackup`'
def get(self, backup_id):
return self._get(('/backups/%s' % backup_id), 'backup')
'Get a list of all monitor backups. :rtype: list of :class:`ServiceManageBackup`'
def list(self, detailed=True):
if (detailed is True): return self._list('/backups/detail', 'backups') else: return self._list('/backups', 'backups')
'Delete a monitor backup. :param backup: The :class:`ServiceManageBackup` to delete.'
def delete(self, backup):
self._delete(('/backups/%s' % base.getid(backup)))
'Delete this snapshot.'
def delete(self):
self.manager.delete(self)
'Update the display_name or display_description for this snapshot.'
def update(self, **kwargs):
self.manager.update(self, **kwargs)
'Create a snapshot of the given monitor. :param monitor_id: The ID of the monitor to snapshot. :param force: If force is True, create a snapshot even if the monitor is attached to an instance. Default is False. :param display_name: Name of the snapshot :param display_description: Description of the snapshot :rtype: :cl...
def create(self, monitor_id, force=False, display_name=None, display_description=None):
body = {'snapshot': {'monitor_id': monitor_id, 'force': force, 'display_name': display_name, 'display_description': display_description}} return self._create('/snapshots', body, 'snapshot')
'Get a snapshot. :param snapshot_id: The ID of the snapshot to get. :rtype: :class:`Snapshot`'
def get(self, snapshot_id):
return self._get(('/snapshots/%s' % snapshot_id), 'snapshot')
'Get a list of all snapshots. :rtype: list of :class:`Snapshot`'
def list(self, detailed=True, search_opts=None):
if (search_opts is None): search_opts = {} qparams = {} for (opt, val) in search_opts.iteritems(): if val: qparams[opt] = val query_string = (('?%s' % urllib.urlencode(qparams)) if qparams else '') detail = '' if detailed: detail = '/detail' return self._l...
'Delete a snapshot. :param snapshot: The :class:`Snapshot` to delete.'
def delete(self, snapshot):
self._delete(('/snapshots/%s' % base.getid(snapshot)))
'Update the display_name or display_description for a snapshot. :param snapshot: The :class:`Snapshot` to delete.'
def update(self, snapshot, **kwargs):
if (not kwargs): return body = {'snapshot': kwargs} self._update(('/snapshots/%s' % base.getid(snapshot)), body)
'QuotaSet does not have a \'id\' attribute but base.Resource needs it to self-refresh and QuotaSet is indexed by tenant_id'
@property def id(self):
return self.tenant_id
'Delete this monitor.'
def delete(self):
self.manager.delete(self)
'Update the display_name or display_description for this monitor.'
def update(self, **kwargs):
self.manager.update(self, **kwargs)
'Set attachment metadata. :param instance_uuid: uuid of the attaching instance. :param mountpoint: mountpoint on the attaching instance.'
def attach(self, instance_uuid, mountpoint):
return self.manager.attach(self, instance_uuid, mountpoint)
'Clear attachment metadata.'
def detach(self):
return self.manager.detach(self)
'Reserve this monitor.'
def reserve(self, monitor):
return self.manager.reserve(self)
'Unreserve this monitor.'
def unreserve(self, monitor):
return self.manager.unreserve(self)
'Begin detaching monitor.'
def begin_detaching(self, monitor):
return self.manager.begin_detaching(self)
'Roll detaching monitor.'
def roll_detaching(self, monitor):
return self.manager.roll_detaching(self)
'Initialize a monitor connection. :param connector: connector dict from nova.'
def initialize_connection(self, monitor, connector):
return self.manager.initialize_connection(self, connector)
'Terminate a monitor connection. :param connector: connector dict from nova.'
def terminate_connection(self, monitor, connector):
return self.manager.terminate_connection(self, connector)
'Set or Append metadata to a monitor. :param type : The :class: `ServiceManage` to set metadata on :param metadata: A dict of key/value pairs to set'
def set_metadata(self, monitor, metadata):
return self.manager.set_metadata(self, metadata)
'Upload a monitor to image service as an image.'
def upload_to_image(self, force, image_name, container_format, disk_format):
self.manager.upload_to_image(self, force, image_name, container_format, disk_format)
'Delete the specified monitor ignoring its current state. :param monitor: The UUID of the monitor to force-delete.'
def force_delete(self):
self.manager.force_delete(self)
'Create a monitor. :param size: Size of monitor in GB :param snapshot_id: ID of the snapshot :param display_name: Name of the monitor :param display_description: Description of the monitor :param monitor_type: Type of monitor :rtype: :class:`ServiceManage` :param user_id: User id derived from context :param project_id:...
def create(self, size, snapshot_id=None, source_volid=None, display_name=None, display_description=None, monitor_type=None, user_id=None, project_id=None, availability_zone=None, metadata=None, imageRef=None):
if (metadata is None): monitor_metadata = {} else: monitor_metadata = metadata body = {'monitor': {'size': size, 'snapshot_id': snapshot_id, 'display_name': display_name, 'display_description': display_description, 'monitor_type': monitor_type, 'user_id': user_id, 'project_id': project_id, '...
'Get a monitor. :param monitor_id: The ID of the monitor to delete. :rtype: :class:`ServiceManage`'
def get(self, monitor_id):
return self._get(('/monitors/%s' % monitor_id), 'monitor')
'Get a list of all monitors. :rtype: list of :class:`ServiceManage`'
def list(self, detailed=True, search_opts=None):
if (search_opts is None): search_opts = {} qparams = {} for (opt, val) in search_opts.iteritems(): if val: qparams[opt] = val query_string = (('?%s' % urllib.urlencode(qparams)) if qparams else '') detail = '' if detailed: detail = '/detail' ret = self._li...
'Delete a monitor. :param monitor: The :class:`ServiceManage` to delete.'
def delete(self, monitor):
self._delete(('/monitors/%s' % base.getid(monitor)))
'Update the display_name or display_description for a monitor. :param monitor: The :class:`ServiceManage` to delete.'
def update(self, monitor, **kwargs):
if (not kwargs): return body = {'monitor': kwargs} self._update(('/monitors/%s' % base.getid(monitor)), body)
'Perform a monitor "action."'
def _action(self, action, monitor, info=None, **kwargs):
body = {action: info} self.run_hooks('modify_body_for_action', body, **kwargs) url = ('/monitors/%s/action' % base.getid(monitor)) return self.api.client.post(url, body=body)
'Perform a monitor "action."'
def host_status(self, req=None):
body = {'request': req} url = '/dbservice/host_status' return self.api.client.post(url, body=body)
'Perform a monitor "action."'
def test_service(self, req=None):
url = '/conductor/test_service' return self.api.client.post(url)
'Perform a monitor "action."'
def resource_info(self, req=None):
body = {'request': req} url = '/dbservice/resource_info' return self.api.client.post(url, body=body)
'Perform a monitor "action."'
def asm_settings(self, req=None):
body = {'request': req} url = '/dbservice/asm_settings' return self.api.client.post(url, body=body)
'Perform a monitor "action."'
def asm_settings_update(self, req=None):
body = {'request': req} url = '/dbservice/asm_settings_update' return self.api.client.post(url, body=body)
'Perform a monitor "action."'
def asm_start_host(self, req=None):
body = {'request': req} url = '/asm/asm_start_host' return self.api.client.post(url, body=body)
'Perform a pas "action."'
def pas_host_select(self, req=None):
body = {'request': req} url = '/pas/pas_host_select' return self.api.client.post(url, body=body)
'Set attachment metadata. :param monitor: The :class:`ServiceManage` (or its ID) you would like to attach. :param instance_uuid: uuid of the attaching instance. :param mountpoint: mountpoint on the attaching instance.'
def attach(self, monitor, instance_uuid, mountpoint):
return self._action('os-attach', monitor, {'instance_uuid': instance_uuid, 'mountpoint': mountpoint})
'Clear attachment metadata. :param monitor: The :class:`ServiceManage` (or its ID) you would like to detach.'
def detach(self, monitor):
return self._action('os-detach', monitor)
'Reserve this monitor. :param monitor: The :class:`ServiceManage` (or its ID) you would like to reserve.'
def reserve(self, monitor):
return self._action('os-reserve', monitor)
'Unreserve this monitor. :param monitor: The :class:`ServiceManage` (or its ID) you would like to unreserve.'
def unreserve(self, monitor):
return self._action('os-unreserve', monitor)
'Begin detaching this monitor. :param monitor: The :class:`ServiceManage` (or its ID) you would like to detach.'
def begin_detaching(self, monitor):
return self._action('os-begin_detaching', monitor)
'Roll detaching this monitor. :param monitor: The :class:`ServiceManage` (or its ID) you would like to roll detaching.'
def roll_detaching(self, monitor):
return self._action('os-roll_detaching', monitor)
'Initialize a monitor connection. :param monitor: The :class:`ServiceManage` (or its ID). :param connector: connector dict from nova.'
def initialize_connection(self, monitor, connector):
return self._action('os-initialize_connection', monitor, {'connector': connector})[1]['connection_info']
'Terminate a monitor connection. :param monitor: The :class:`ServiceManage` (or its ID). :param connector: connector dict from nova.'
def terminate_connection(self, monitor, connector):
self._action('os-terminate_connection', monitor, {'connector': connector})
'Update/Set a monitors metadata. :param monitor: The :class:`ServiceManage`. :param metadata: A list of keys to be set.'
def set_metadata(self, monitor, metadata):
body = {'metadata': metadata} return self._create(('/monitors/%s/metadata' % base.getid(monitor)), body, 'metadata')
'Delete specified keys from monitors metadata. :param monitor: The :class:`ServiceManage`. :param metadata: A list of keys to be removed.'
def delete_metadata(self, monitor, keys):
for k in keys: self._delete(('/monitors/%s/metadata/%s' % (base.getid(monitor), k)))
'Upload monitor to image service as image. :param monitor: The :class:`ServiceManage` to upload.'
def upload_to_image(self, monitor, force, image_name, container_format, disk_format):
return self._action('os-monitor_upload_image', monitor, {'force': force, 'image_name': image_name, 'container_format': container_format, 'disk_format': disk_format})
'Get a specific extension. :rtype: :class:`Limits`'
def get(self):
return self._get('/limits', 'limits')
'Fetch the public URL from the Compute service for a particular endpoint attribute. If none given, return the first. See tests for sample service catalog.'
def url_for(self, attr=None, filter_value=None, service_type=None, endpoint_type='publicURL', service_name=None, monitor_service_name=None):
matching_endpoints = [] if ('endpoints' in self.catalog): for endpoint in self.catalog['endpoints']: if ((not filter_value) or (endpoint[attr] == filter_value)): matching_endpoints.append(endpoint) if (not matching_endpoints): raise monitorclient.exception...
'Runs a command in an out-of-process shell. Returns the output of that command. Working directory is self.root.'
def run_command_with_code(self, cmd, redirect_output=True, check_exit_code=True):
if redirect_output: stdout = subprocess.PIPE else: stdout = None proc = subprocess.Popen(cmd, cwd=self.root, stdout=stdout) output = proc.communicate()[0] if (check_exit_code and (proc.returncode != 0)): self.die('Command "%s" failed.\n%s', ' '.join(cmd), output) ...
'Creates the virtual environment and installs PIP. Creates the virtual environment and installs PIP only into the virtual environment.'
def create_virtualenv(self, no_site_packages=True):
if (not os.path.isdir(self.venv)): print 'Creating venv...', if no_site_packages: self.run_command(['virtualenv', '-q', '--no-site-packages', self.venv]) else: self.run_command(['virtualenv', '-q', self.venv]) print 'done.' print 'Installing pip ...
'Parses command-line arguments.'
def parse_args(self, argv):
parser = argparse.ArgumentParser() parser.add_argument('-n', '--no-site-packages', action='store_true', help='Do not inherit packages from global Python install') return parser.parse_args(argv[1:])
'Any distribution-specific post-processing gets done here. In particular, this is useful for applying patches to code inside the venv.'
def post_process(self):
pass
'Workaround for a bug in eventlet. This currently affects RHEL6.1, but the fix can safely be applied to all RHEL and Fedora distributions. This can be removed when the fix is applied upstream. Nova: https://bugs.launchpad.net/nova/+bug/884915 Upstream: https://bitbucket.org/which_linden/eventlet/issue/89'
def post_process(self):
if (not self.check_pkg('patch')): self.yum_install('patch') self.apply_patch(os.path.join(self.venv, 'lib', self.py_version, 'site-packages', 'eventlet/green/subprocess.py'), 'contrib/redhat-eventlet.patch')
':param data: Underlying data object :param limit: maximum number of bytes the reader should allow'
def __init__(self, data, limit):
self.data = data self.limit = limit self.bytes_read = 0
'Register extension with the extension manager.'
def __init__(self, ext_mgr):
ext_mgr.register(self)
'List of extensions.ResourceExtension extension objects. Resources define new nouns, and are accessible through URLs.'
def get_resources(self):
resources = [] return resources
'List of extensions.ControllerExtension extension objects. Controller extensions are used to extend existing controllers.'
def get_controller_extensions(self):
controller_exts = [] return controller_exts
'Synthesize a namespace map from extension.'
@classmethod def nsmap(cls):
nsmap = ext_nsmap.copy() nsmap[cls.alias] = cls.namespace return nsmap
'Synthesize element and attribute names.'
@classmethod def xmlname(cls, name):
return ('{%s}%s' % (cls.namespace, name))
'Returns a list of ResourceExtension objects.'
def get_resources(self):
resources = [] resources.append(ResourceExtension('extensions', ExtensionsResource(self))) for ext in self.extensions.values(): try: resources.extend(ext.get_resources()) except AttributeError: pass return resources
'Returns a list of ControllerExtension objects.'
def get_controller_extensions(self):
controller_exts = [] for ext in self.extensions.values(): try: get_ext_method = ext.get_controller_extensions except AttributeError: continue controller_exts.extend(get_ext_method()) return controller_exts
'Checks for required methods in extension objects.'
def _check_extension(self, extension):
try: LOG.debug(_('Ext name: %s'), extension.name) LOG.debug(_('Ext alias: %s'), extension.alias) LOG.debug(_('Ext description: %s'), ' '.join(extension.__doc__.strip().split())) LOG.debug(_('Ext namespace: %s'), extension.namespace) LOG.debug(_('Ext...
'Execute an extension factory. Loads an extension. The \'ext_factory\' is the name of a callable that will be imported and called with one argument--the extension manager. The factory callable is expected to call the register() method at least once.'
def load_extension(self, ext_factory):
LOG.debug(_('Loading extension %s'), ext_factory) factory = importutils.import_class(ext_factory) LOG.debug(_('Calling extension factory %s'), ext_factory) factory(self)
'Load extensions specified on the command line.'
def _load_extensions(self):
extensions = list(self.cls_list) old_contrib_path = 'monitor.api.openstack.servicemanage.contrib.standard_extensions' new_contrib_path = 'monitor.api.contrib.standard_extensions' if (old_contrib_path in extensions): LOG.warn(_('osapi_servicemanage_extension is set to deprecated pa...
'Return href string with proper limit and marker params.'
def _get_next_link(self, request, identifier):
params = request.params.copy() params['marker'] = identifier prefix = self._update_link_prefix(request.application_url, FLAGS.osapi_servicemanage_base_URL) url = os.path.join(prefix, request.environ['monitor.context'].project_id, self._collection_name) return ('%s?%s' % (url, dict_to_query_str(param...
'Return an href string pointing to this object.'
def _get_href_link(self, request, identifier):
prefix = self._update_link_prefix(request.application_url, FLAGS.osapi_servicemanage_base_URL) return os.path.join(prefix, request.environ['monitor.context'].project_id, self._collection_name, str(identifier))
'Create a URL that refers to a specific resource.'
def _get_bookmark_link(self, request, identifier):
base_url = remove_version_from_href(request.application_url) base_url = self._update_link_prefix(base_url, FLAGS.osapi_servicemanage_base_URL) return os.path.join(base_url, request.environ['monitor.context'].project_id, self._collection_name, str(identifier))
'Retrieve \'next\' link, if applicable.'
def _get_collection_links(self, request, items, id_key='uuid'):
links = [] limit = int(request.params.get('limit', 0)) if (limit and (limit == len(items))): last_item = items[(-1)] if (id_key in last_item): last_item_id = last_item[id_key] else: last_item_id = last_item['id'] links.append({'rel': 'next', 'href': se...
'Marshal the metadata attribute of a parsed request'
def extract_metadata(self, metadata_node):
if (metadata_node is None): return {} metadata = {} for meta_node in self.find_children_named(metadata_node, 'meta'): key = meta_node.getAttribute('key') metadata[key] = self.extract_text(meta_node) return metadata
'Initialize view builder.'
def __init__(self):
super(ViewBuilder, self).__init__()
'Show a list of backups without many details.'
def summary_list(self, request, backups):
return self._list_view(self.summary, request, backups)