desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Create a worker that calls a method in a proxy object'
def create_worker(self, topic, proxy, pool_name):
proxy_cb = rpc_amqp.ProxyCallback(self.conf, proxy, rpc_amqp.get_connection_pool(self.conf, Connection)) self.proxy_callbacks.append(proxy_cb) self.declare_topic_consumer(topic, proxy_cb, pool_name)
'Register as a member of a group of consumers for a given topic from the specified exchange. Exactly one member of a given pool will receive each message. A message will be delivered to multiple pools, if more than one is created.'
def join_consumer_pool(self, callback, pool_name, topic, exchange_name=None):
callback_wrapper = rpc_amqp.CallbackWrapper(conf=self.conf, callback=callback, connection_pool=rpc_amqp.get_connection_pool(self.conf, Connection)) self.proxy_callbacks.append(callback_wrapper) self.declare_topic_consumer(queue_name=pool_name, topic=topic, exchange_name=exchange_name, callback=callback_wrap...
'Init a brain using json instead of a rules dictionary.'
@classmethod def load_json(cls, data, default_rule=None):
rules_dict = jsonutils.loads(data) return cls(rules=rules_dict, default_rule=default_rule)
'Checks authorization of some rules against credentials. Detailed description of the check with examples in policy.enforce(). :param match_list: nested tuples of data to match against :param target_dict: dict of object properties :param credentials_dict: dict of actor properties :returns: True if the check passes'
def check(self, match_list, target_dict, cred_dict):
if (not match_list): return True for and_list in match_list: if isinstance(and_list, basestring): and_list = (and_list,) if all([self._check(item, target_dict, cred_dict) for item in and_list]): return True return False
'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 monitor.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
'How weighted this weigher should be. Normally this would be overriden in a subclass based on a config value.'
def _weight_multiplier(self):
return 1.0
'Override in a subclass to specify a weight for a specific object.'
def _weigh_object(self, obj, weight_properties):
return 0.0
'Weigh multiple objects. Override in a subclass if you need need access to all objects in order to manipulate weights.'
def weigh_objects(self, weighed_obj_list, weight_properties):
constant = self._weight_multiplier() for obj in weighed_obj_list: obj.weight += (constant * self._weigh_object(obj.obj, weight_properties))
'Return whether an object is a class of the correct type and is not prefixed with an underscore.'
def _is_correct_class(self, obj):
return (inspect.isclass(obj) and (not obj.__name__.startswith('_')) and issubclass(obj, self.weighed_object_type))
'Return a sorted (highest score first) list of WeighedObjects.'
def get_weighed_objects(self, weigher_classes, obj_list, weighing_properties):
if (not obj_list): return [] weighed_objs = [self.object_class(obj, 0.0) for obj in obj_list] for weigher_cls in weigher_classes: weigher = weigher_cls() weigher.weigh_objects(weighed_objs, weighing_properties) return sorted(weighed_objs, key=(lambda x: x.weight), reverse=True)
'Return True if the object passes the filter, otherwise False.'
def _filter_one(self, obj, filter_properties):
return self.host_passes(obj, filter_properties)
'Return True if the HostState passes the filter, otherwise False. Override this in a subclass.'
def host_passes(self, host_state, filter_properties):
raise NotImplementedError()
'Check that the capabilities provided by the services satisfy the extra specs associated with the instance type'
def _satisfies_extra_specs(self, capabilities, resource_type):
extra_specs = resource_type.get('extra_specs', []) if (not extra_specs): return True for (key, req) in extra_specs.iteritems(): scope = key.split(':') if ((len(scope) > 1) and (scope[0] != 'capabilities')): continue elif (scope[0] == 'capabilities'): d...
'Return a list of hosts that can create instance_type.'
def host_passes(self, host_state, filter_properties):
resource_type = filter_properties.get('resource_type') if (not self._satisfies_extra_specs(host_state.capabilities, resource_type)): return False return True
'Returns True if the specified operator can successfully compare the first item in the args with all the rest. Will return False if only one item is in the list.'
def _op_compare(self, args, op):
if (len(args) < 2): return False if (op is operator.contains): bad = (args[0] not in args[1:]) else: bad = [arg for arg in args[1:] if (not op(args[0], arg))] return (not bool(bad))
'First term is == all the other terms.'
def _equals(self, args):
return self._op_compare(args, operator.eq)
'First term is < all the other terms.'
def _less_than(self, args):
return self._op_compare(args, operator.lt)
'First term is > all the other terms.'
def _greater_than(self, args):
return self._op_compare(args, operator.gt)
'First term is in set of remaining terms'
def _in(self, args):
return self._op_compare(args, operator.contains)
'First term is <= all the other terms.'
def _less_than_equal(self, args):
return self._op_compare(args, operator.le)
'First term is >= all the other terms.'
def _greater_than_equal(self, args):
return self._op_compare(args, operator.ge)
'Flip each of the arguments.'
def _not(self, args):
return [(not arg) for arg in args]
'True if any arg is True.'
def _or(self, args):
return any(args)
'True if all args are True.'
def _and(self, args):
return all(args)
'Strings prefixed with $ are capability lookups in the form \'$variable\' where \'variable\' is an attribute in the HostState class. If $variable is a dictionary, you may use: $variable.dictkey'
def _parse_string(self, string, host_state):
if (not string): return None if (not string.startswith('$')): return string path = string[1:].split('.') obj = getattr(host_state, path[0], None) if (obj is None): return None for item in path[1:]: obj = obj.get(item, None) if (obj is None): re...
'Recursively parse the query structure.'
def _process_filter(self, query, host_state):
if (not query): return True cmd = query[0] method = self.commands[cmd] cooked_args = [] for arg in query[1:]: if isinstance(arg, list): arg = self._process_filter(arg, host_state) elif isinstance(arg, basestring): arg = self._parse_string(arg, host_sta...
'Return a list of hosts that can fulfill the requirements specified in the query.'
def host_passes(self, host_state, filter_properties):
try: query = filter_properties['scheduler_hints']['query'] except KeyError: query = None if (not query): return True result = self._process_filter(jsonutils.loads(query), host_state) if isinstance(result, list): result = any(result) if result: return True ...
'Return True if it passes the filter, False otherwise. Override this in a subclass.'
def _filter_one(self, obj, filter_properties):
return True
'Yield objects that pass the filter. Can be overriden in a subclass, if you need to base filtering decisions on all objects. Otherwise, one can just override _filter_one() to filter a single object.'
def filter_all(self, filter_obj_list, filter_properties):
for obj in filter_obj_list: if self._filter_one(obj, filter_properties): (yield obj)
'Return whether an object is a class of the correct type and is not prefixed with an underscore.'
def _is_correct_class(self, obj):
return (inspect.isclass(obj) and (not obj.__name__.startswith('_')) and issubclass(obj, self.filter_class_type))
'Returns existing executable, or empty string if none found'
def get_exec(self, exec_dirs=[]):
if (self.real_exec is not None): return self.real_exec self.real_exec = '' if self.exec_path.startswith('/'): if os.access(self.exec_path, os.X_OK): self.real_exec = self.exec_path else: for binary_path in exec_dirs: expanded_path = os.path.join(binary_pat...
'Only check that the first argument (command) matches exec_path'
def match(self, userargs):
if (os.path.basename(self.exec_path) == userargs[0]): return True return False
'Returns command to execute (with sudo -u if run_as != root).'
def get_command(self, userargs, exec_dirs=[]):
to_exec = (self.get_exec(exec_dirs=exec_dirs) or self.exec_path) if (self.run_as != 'root'): return (['sudo', '-u', self.run_as, to_exec] + userargs[1:]) return ([to_exec] + userargs[1:])
'Returns specific environment to set, None if none'
def get_environment(self, userargs):
return None
'Metaclass that allows us to collect decorated periodic tasks.'
def __init__(cls, names, bases, dict_):
super(ManagerMeta, cls).__init__(names, bases, dict_) try: cls._periodic_tasks = cls._periodic_tasks[:] except AttributeError: cls._periodic_tasks = [] try: cls._short_cycle_tasks = cls._short_cycle_tasks[:] except AttributeError: cls._short_cycle_tasks = [] try: ...
'Get the rpc dispatcher for this manager. If a manager would like to set an rpc API version, or support more than one class as the target of rpc messages, override this method.'
def create_rpc_dispatcher(self):
return rpc_dispatcher.RpcDispatcher([self])
'Tasks to be run at a periodic interval.'
def periodic_tasks(self, context, raise_on_error=False):
for (task_name, task) in self._periodic_tasks: full_task_name = '.'.join([self.__class__.__name__, task_name]) ticks_to_skip = self._ticks_to_skip[task_name] if (ticks_to_skip > 0): LOG.debug(_('Skipping %(full_task_name)s, %(ticks_to_skip)s ticks left until nex...
'Handle initialization if this is a standalone service. Child classes should override this method.'
def init_host(self):
pass
'Get a specific quota by project.'
def get_by_project(self, context, project_id, resource):
return db.quota_get(context, project_id, resource)
'Get a specific quota by quota class.'
def get_by_class(self, context, quota_class, resource):
return db.quota_class_get(context, quota_class, resource)
'Given a list of resources, retrieve the default quotas. :param context: The request context, for access checks. :param resources: A dictionary of the registered resources.'
def get_defaults(self, context, resources):
quotas = {} for resource in resources.values(): quotas[resource.name] = resource.default return quotas
'Given a list of resources, retrieve the quotas for the given quota class. :param context: The request context, for access checks. :param resources: A dictionary of the registered resources. :param quota_class: The name of the quota class to return quotas for. :param defaults: If True, the default value will be reporte...
def get_class_quotas(self, context, resources, quota_class, defaults=True):
quotas = {} class_quotas = db.quota_class_get_all_by_name(context, quota_class) for resource in resources.values(): if (defaults or (resource.name in class_quotas)): quotas[resource.name] = class_quotas.get(resource.name, resource.default) return quotas
'Given a list of resources, retrieve the quotas for the given project. :param context: The request context, for access checks. :param resources: A dictionary of the registered resources. :param project_id: The ID of the project to return quotas for. :param quota_class: If project_id != context.project_id, the quota cla...
def get_project_quotas(self, context, resources, project_id, quota_class=None, defaults=True, usages=True):
quotas = {} project_quotas = db.quota_get_all_by_project(context, project_id) if usages: project_usages = db.quota_usage_get_all_by_project(context, project_id) if (project_id == context.project_id): quota_class = context.quota_class if quota_class: class_quotas = db.quota_cl...
'A helper method which retrieves the quotas for the specific resources identified by keys, and which apply to the current context. :param context: The request context, for access checks. :param resources: A dictionary of the registered resources. :param keys: A list of the desired quotas to retrieve. :param has_sync: I...
def _get_quotas(self, context, resources, keys, has_sync, project_id=None):
if has_sync: sync_filt = (lambda x: hasattr(x, 'sync')) else: sync_filt = (lambda x: (not hasattr(x, 'sync'))) desired = set(keys) sub_resources = dict(((k, v) for (k, v) in resources.items() if ((k in desired) and sync_filt(v)))) if (len(keys) != len(sub_resources)): unknown...
'Check simple quota limits. For limits--those quotas for which there is no usage synchronization function--this method checks that a set of proposed values are permitted by the limit restriction. This method will raise a QuotaResourceUnknown exception if a given resource is unknown or if it is not a simple limit resour...
def limit_check(self, context, resources, values, project_id=None):
unders = [key for (key, val) in values.items() if (val < 0)] if unders: raise exception.InvalidQuotaValue(unders=sorted(unders)) if (project_id is None): project_id = context.project_id quotas = self._get_quotas(context, resources, values.keys(), has_sync=False, project_id=project_id) ...
'Check quotas and reserve resources. For counting quotas--those quotas for which there is a usage synchronization function--this method checks quotas against current usage and the desired deltas. This method will raise a QuotaResourceUnknown exception if a given resource is unknown or if it does not have a usage synchr...
def reserve(self, context, resources, deltas, expire=None, project_id=None):
if (expire is None): expire = FLAGS.reservation_expire if isinstance(expire, (int, long)): expire = datetime.timedelta(seconds=expire) if isinstance(expire, datetime.timedelta): expire = (timeutils.utcnow() + expire) if (not isinstance(expire, datetime.datetime)): raise e...
'Commit reservations. :param context: The request context, for access checks. :param reservations: A list of the reservation UUIDs, as returned by the reserve() method. :param project_id: Specify the project_id if current context is admin and admin wants to impact on common user\'s tenant.'
def commit(self, context, reservations, project_id=None):
if (project_id is None): project_id = context.project_id db.reservation_commit(context, reservations, project_id=project_id)
'Roll back reservations. :param context: The request context, for access checks. :param reservations: A list of the reservation UUIDs, as returned by the reserve() method. :param project_id: Specify the project_id if current context is admin and admin wants to impact on common user\'s tenant.'
def rollback(self, context, reservations, project_id=None):
if (project_id is None): project_id = context.project_id db.reservation_rollback(context, reservations, project_id=project_id)
'Destroy all quotas, usages, and reservations associated with a project. :param context: The request context, for access checks. :param project_id: The ID of the project being deleted.'
def destroy_all_by_project(self, context, project_id):
db.quota_destroy_all_by_project(context, project_id)
'Expire reservations. Explores all currently existing reservations and rolls back any that have expired. :param context: The request context, for access checks.'
def expire(self, context):
db.reservation_expire(context)
'Initializes a Resource. :param name: The name of the resource, i.e., "servicemanages". :param flag: The name of the flag or configuration option which specifies the default value of the quota for this resource.'
def __init__(self, name, flag=None):
self.name = name self.flag = flag
'Given a driver and context, obtain the quota for this resource. :param driver: A quota driver. :param context: The request context. :param project_id: The project to obtain the quota value for. If not provided, it is taken from the context. If it is given as None, no project-specific quota will be searched for. :para...
def quota(self, driver, context, **kwargs):
project_id = kwargs.get('project_id', context.project_id) quota_class = kwargs.get('quota_class', context.quota_class) if project_id: try: return driver.get_by_project(context, project_id, self.name) except exception.ProjectQuotaNotFound: pass if quota_class: ...
'Return the default value of the quota.'
@property def default(self):
return (FLAGS[self.flag] if self.flag else (-1))
'Initializes a ReservableResource. Reservable resources are those resources which directly correspond to objects in the database, i.e., servicemanages, gigabytes, etc. A ReservableResource must be constructed with a usage synchronization function, which will be called to determine the current counts of one or more res...
def __init__(self, name, sync, flag=None):
super(ReservableResource, self).__init__(name, flag=flag) self.sync = sync
'Initializes a CountableResource. Countable resources are those resources which directly correspond to objects in the database, i.e., servicemanages, gigabytes, etc., but for which a count by project ID is inappropriate. A CountableResource must be constructed with a counting function, which will be called to determin...
def __init__(self, name, count, flag=None):
super(CountableResource, self).__init__(name, flag=flag) self.count = count
'Initialize a Quota object.'
def __init__(self, quota_driver_class=None):
if (not quota_driver_class): quota_driver_class = FLAGS.quota_driver if isinstance(quota_driver_class, basestring): quota_driver_class = importutils.import_object(quota_driver_class) self._resources = {} self._driver = quota_driver_class
'Register a resource.'
def register_resource(self, resource):
self._resources[resource.name] = resource
'Register a list of resources.'
def register_resources(self, resources):
for resource in resources: self.register_resource(resource)
'Get a specific quota by project.'
def get_by_project(self, context, project_id, resource):
return self._driver.get_by_project(context, project_id, resource)
'Get a specific quota by quota class.'
def get_by_class(self, context, quota_class, resource):
return self._driver.get_by_class(context, quota_class, resource)
'Retrieve the default quotas. :param context: The request context, for access checks.'
def get_defaults(self, context):
return self._driver.get_defaults(context, self._resources)
'Retrieve the quotas for the given quota class. :param context: The request context, for access checks. :param quota_class: The name of the quota class to return quotas for. :param defaults: If True, the default value will be reported if there is no specific value for the resource.'
def get_class_quotas(self, context, quota_class, defaults=True):
return self._driver.get_class_quotas(context, self._resources, quota_class, defaults=defaults)
'Retrieve the quotas for the given project. :param context: The request context, for access checks. :param project_id: The ID of the project to return quotas for. :param quota_class: If project_id != context.project_id, the quota class cannot be determined. This parameter allows it to be specified. :param defaults: If...
def get_project_quotas(self, context, project_id, quota_class=None, defaults=True, usages=True):
return self._driver.get_project_quotas(context, self._resources, project_id, quota_class=quota_class, defaults=defaults, usages=usages)
'Count a resource. For countable resources, invokes the count() function and returns its result. Arguments following the context and resource are passed directly to the count function declared by the resource. :param context: The request context, for access checks. :param resource: The name of the resource, as a strin...
def count(self, context, resource, *args, **kwargs):
res = self._resources.get(resource) if ((not res) or (not hasattr(res, 'count'))): raise exception.QuotaResourceUnknown(unknown=[resource]) return res.count(context, *args, **kwargs)
'Check simple quota limits. For limits--those quotas for which there is no usage synchronization function--this method checks that a set of proposed values are permitted by the limit restriction. The values to check are given as keyword arguments, where the key identifies the specific quota limit to check, and the val...
def limit_check(self, context, project_id=None, **values):
return self._driver.limit_check(context, self._resources, values, project_id=project_id)
'Check quotas and reserve resources. For counting quotas--those quotas for which there is a usage synchronization function--this method checks quotas against current usage and the desired deltas. The deltas are given as keyword arguments, and current usage and other reservations are factored into the quota check. This...
def reserve(self, context, expire=None, project_id=None, **deltas):
reservations = self._driver.reserve(context, self._resources, deltas, expire=expire, project_id=project_id) LOG.debug((_('Created reservations %(reservations)s') % locals())) return reservations
'Commit reservations. :param context: The request context, for access checks. :param reservations: A list of the reservation UUIDs, as returned by the reserve() method. :param project_id: Specify the project_id if current context is admin and admin wants to impact on common user\'s tenant.'
def commit(self, context, reservations, project_id=None):
try: self._driver.commit(context, reservations, project_id=project_id) except Exception: LOG.exception((_('Failed to commit reservations %(reservations)s') % locals()))
'Roll back reservations. :param context: The request context, for access checks. :param reservations: A list of the reservation UUIDs, as returned by the reserve() method. :param project_id: Specify the project_id if current context is admin and admin wants to impact on common user\'s tenant.'
def rollback(self, context, reservations, project_id=None):
try: self._driver.rollback(context, reservations, project_id=project_id) except Exception: LOG.exception((_('Failed to roll back reservations %(reservations)s') % locals()))
'Destroy all quotas, usages, and reservations associated with a project. :param context: The request context, for access checks. :param project_id: The ID of the project being deleted.'
def destroy_all_by_project(self, context, project_id):
self._driver.destroy_all_by_project(context, project_id)
'Expire reservations. Explores all currently existing reservations and rolls back any that have expired. :param context: The request context, for access checks.'
def expire(self, context):
self._driver.expire(context)
'Initialize, but do not start, a WSGI server. :param name: Pretty name for logging. :param app: The WSGI application to serve. :param host: IP address to serve the application. :param port: Port number to server the application. :param pool_size: Maximum number of eventlets to spawn concurrently. :returns: None'
def __init__(self, name, app, host=None, port=None, pool_size=None, protocol=eventlet.wsgi.HttpProtocol):
self.name = name self.app = app self._host = (host or '0.0.0.0') self._port = (port or 0) self._server = None self._socket = None self._protocol = protocol self._pool = eventlet.GreenPool((pool_size or self.default_pool_size)) self._logger = logging.getLogger('eventlet.wsgi.server') ...
'Run the blocking eventlet WSGI server. :returns: None'
def _start(self):
eventlet.wsgi.server(self._socket, self.app, protocol=self._protocol, custom_pool=self._pool, log=self._wsgi_logger)
'Start serving a WSGI application. :param backlog: Maximum number of queued connections. :returns: None :raises: monitor.exception.InvalidInput'
def start(self, backlog=128):
if (backlog < 1): raise exception.InvalidInput(reason='The backlog must be more than 1') self._socket = self._get_socket(self._host, self._port, backlog=backlog) self._server = eventlet.spawn(self._start) (self._host, self._port) = self._socket.getsockname()[0:2] LOG.info((...
'Stop this server. This is not a very nice action, as currently the method by which a server is stopped is by killing its eventlet. :returns: None'
def stop(self):
LOG.info(_('Stopping WSGI server.')) self._server.kill()
'Block, until the server has stopped. Waits on the server\'s eventlet to finish, then returns. :returns: None'
def wait(self):
try: self._server.wait() except greenlet.GreenletExit: LOG.info(_('WSGI server has stopped.'))
'Used for paste app factories in paste.deploy config files. Any local configuration (that is, values under the [app:APPNAME] section of the paste config) will be passed into the `__init__` method as kwargs. A hypothetical configuration would look like: [app:wadl] latest_version = 1.3 paste.app_factory = monitor.api.fan...
@classmethod def factory(cls, global_config, **local_config):
return cls(**local_config)
'Subclasses will probably want to implement __call__ like this: @webob.dec.wsgify(RequestClass=Request) def __call__(self, req): # Any of the following objects work as responses: # Option 1: simple string res = \'message\n\' # Option 2: a nicely formatted HTTP exception page res = exc.HTTPForbidden(detail=\'Nice try\')...
def __call__(self, environ, start_response):
raise NotImplementedError(_('You must implement __call__'))
'Used for paste app factories in paste.deploy config files. Any local configuration (that is, values under the [filter:APPNAME] section of the paste config) will be passed into the `__init__` method as kwargs. A hypothetical configuration would look like: [filter:analytics] redis_host = 127.0.0.1 paste.filter_factory =...
@classmethod def factory(cls, global_config, **local_config):
def _factory(app): return cls(app, **local_config) return _factory
'Called on each request. If this returns None, the next application down the stack will be executed. If it returns a response then that response will be returned and execution will stop here.'
def process_request(self, req):
return None
'Do whatever you\'d like to the response.'
def process_response(self, response):
return response
'Iterator that prints the contents of a wrapper string.'
@staticmethod def print_generator(app_iter):
print (('*' * 40) + ' BODY') for part in app_iter: sys.stdout.write(part) sys.stdout.flush() (yield part) print
'Create a router for the given routes.Mapper. Each route in `mapper` must specify a \'controller\', which is a WSGI app to call. You\'ll probably want to specify an \'action\' as well and have your controller be an object that can route the request to the action-specific method. Examples: mapper = routes.Mapper() sc =...
def __init__(self, mapper):
self.map = mapper self._router = routes.middleware.RoutesMiddleware(self._dispatch, self.map)
'Route the incoming request to a controller based on self.map. If no match, return a 404.'
@webob.dec.wsgify(RequestClass=Request) def __call__(self, req):
return self._router
'Dispatch the request to the appropriate controller. Called by self._router after matching the incoming request to a route and putting the information into req.environ. Either returns 404 or the routed WSGI app\'s response.'
@staticmethod @webob.dec.wsgify(RequestClass=Request) def _dispatch(req):
match = req.environ['wsgiorg.routing_args'][1] if (not match): return webob.exc.HTTPNotFound() app = match['controller'] return app
'Initialize the loader, and attempt to find the config. :param config_path: Full or relative path to the paste config. :returns: None'
def __init__(self, config_path=None):
config_path = (config_path or FLAGS.api_paste_config) self.config_path = utils.find_config(config_path)
'Return the paste URLMap wrapped WSGI application. :param name: Name of the application to load. :returns: Paste URLMap object wrapping the requested application. :raises: `monitor.exception.PasteAppNotFound`'
def load_app(self, name):
try: return deploy.loadapp(('config:%s' % self.config_path), name=name) except LookupError as err: LOG.error(err) raise exception.PasteAppNotFound(name=name, path=self.config_path)
':param read_deleted: \'no\' indicates deleted records are hidden, \'yes\' indicates deleted records are visible, \'only\' indicates that *only* deleted records are visible. :param overwrite: Set to False to ensure that the greenthread local copy of the index is not overwritten. :param kwargs: Extra arguments that migh...
def __init__(self, user_id, project_id, is_admin=None, read_deleted='no', roles=None, remote_address=None, timestamp=None, request_id=None, auth_token=None, overwrite=True, quota_class=None, **kwargs):
if kwargs: LOG.warn((_('Arguments dropped when creating context: %s') % str(kwargs))) self.user_id = user_id self.project_id = project_id self.roles = (roles or []) self.is_admin = is_admin if (self.is_admin is None): self.is_admin = policy.check_is_admin(self.role...
'Return a version of this context with admin flag set.'
def elevated(self, read_deleted=None, overwrite=False):
context = copy.copy(self) context.is_admin = True if ('admin' not in context.roles): context.roles.append('admin') if (read_deleted is not None): context.read_deleted = read_deleted return context
':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))