desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Return a single servicemanage type item.'
@wsgi.serializers(xml=ServiceManageTypeTemplate) def show(self, req, id):
context = req.environ['monitor.context'] try: vol_type = servicemanage_types.get_servicemanage_type(context, id) except exception.NotFound: raise exc.HTTPNotFound() vol_type['id'] = str(vol_type['id']) return self._view_builder.show(req, vol_type)
'Return all global and rate limit information.'
@wsgi.serializers(xml=LimitsTemplate) def index(self, req):
context = req.environ['monitor.context'] quotas = QUOTAS.get_project_quotas(context, context.project_id, usages=False) abs_limits = dict(((k, v['limit']) for (k, v) in quotas.items())) rate_limits = req.environ.get('monitor.limits', []) builder = self._get_view_builder(req) return builder.build(...
'Initialize a new `Limit`. @param verb: HTTP verb (POST, PUT, etc.) @param uri: Human-readable URI @param regex: Regular expression format for this limit @param value: Integer number of requests which can be made @param unit: Unit of measure for the value parameter'
def __init__(self, verb, uri, regex, value, unit):
self.verb = verb self.uri = uri self.regex = regex self.value = int(value) self.unit = unit self.unit_string = self.display_unit().lower() self.remaining = int(value) if (value <= 0): raise ValueError('Limit value must be > 0') self.last_request = None self...
'Represents a call to this limit from a relevant request. @param verb: string http verb (POST, GET, etc.) @param url: string URL'
def __call__(self, verb, url):
if ((self.verb != verb) or (not re.match(self.regex, url))): return now = self._get_time() if (self.last_request is None): self.last_request = now leak_value = (now - self.last_request) self.water_level -= leak_value self.water_level = max(self.water_level, 0) self.water_leve...
'Retrieve the current time. Broken out for testability.'
def _get_time(self):
return time.time()
'Display the string name of the unit.'
def display_unit(self):
return self.UNITS.get(self.unit, 'UNKNOWN')
'Return a useful representation of this class.'
def display(self):
return {'verb': self.verb, 'URI': self.uri, 'regex': self.regex, 'value': self.value, 'remaining': int(self.remaining), 'unit': self.display_unit(), 'resetTime': int((self.next_request or self._get_time()))}
'Initialize new `RateLimitingMiddleware`, which wraps the given WSGI application and sets up the given limits. @param application: WSGI application to wrap @param limits: String describing limits @param limiter: String identifying class for representing limits Other parameters are passed to the constructor for the limi...
def __init__(self, application, limits=None, limiter=None, **kwargs):
base_wsgi.Middleware.__init__(self, application) if (limiter is None): limiter = Limiter else: limiter = importutils.import_class(limiter) if (limits is not None): limits = limiter.parse_limits(limits) self._limiter = limiter((limits or DEFAULT_LIMITS), **kwargs)
'Represents a single call through this middleware. We should record the request if we have a limit relevant to it. If no limit is relevant to the request, ignore it. If the request should be rate limited, return a fault telling the user they are over the limit and need to retry later.'
@webob.dec.wsgify(RequestClass=wsgi.Request) def __call__(self, req):
verb = req.method url = req.url context = req.environ.get('monitor.context') if context: username = context.user_id else: username = None (delay, error) = self._limiter.check_for_delay(verb, url, username) if delay: msg = _('This request was rate-limited.') ...
'Initialize the new `Limiter`. @param limits: List of `Limit` objects'
def __init__(self, limits, **kwargs):
self.limits = copy.deepcopy(limits) self.levels = collections.defaultdict((lambda : copy.deepcopy(limits))) for (key, value) in kwargs.items(): if key.startswith('user:'): username = key[5:] self.levels[username] = self.parse_limits(value)
'Return the limits for a given user.'
def get_limits(self, username=None):
return [limit.display() for limit in self.levels[username]]
'Check the given verb/user/user triplet for limit. @return: Tuple of delay (in seconds) and error message (or None, None)'
def check_for_delay(self, verb, url, username=None):
delays = [] for limit in self.levels[username]: delay = limit(verb, url) if delay: delays.append((delay, limit.error_message)) if delays: delays.sort() return delays[0] return (None, None)
'Convert a string into a list of Limit instances. This implementation expects a semicolon-separated sequence of parenthesized groups, where each group contains a comma-separated sequence consisting of HTTP method, user-readable URI, a URI reg-exp, an integer number of requests which can be made, and a unit of measure....
@staticmethod def parse_limits(limits):
limits = limits.strip() if (not limits): return [] result = [] for group in limits.split(';'): group = group.strip() if ((group[:1] != '(') or (group[(-1):] != ')')): raise ValueError('Limit rules must be surrounded by parentheses') group = g...
'Initialize the new `WsgiLimiter`. @param limits: List of `Limit` objects'
def __init__(self, limits=None):
self._limiter = Limiter((limits or DEFAULT_LIMITS))
'Handles a call to this application. Returns 204 if the request is acceptable to the limiter, else a 403 is returned with a relevant header indicating when the request *will* succeed.'
@webob.dec.wsgify(RequestClass=wsgi.Request) def __call__(self, request):
if (request.method != 'POST'): raise webob.exc.HTTPMethodNotAllowed() try: info = dict(jsonutils.loads(request.body)) except ValueError: raise webob.exc.HTTPBadRequest() username = request.path_info_pop() verb = info.get('verb') path = info.get('path') (delay, error) ...
'Initialize the new `WsgiLimiterProxy`. @param limiter_address: IP/port combination of where to request limit'
def __init__(self, limiter_address):
self.limiter_address = limiter_address
'Ignore a limits string--simply doesn\'t apply for the limit proxy. @return: Empty list.'
@staticmethod def parse_limits(limits):
return []
'Find parameters in Accept header for given content type.'
def content_type_params(self, best_content_type):
for (content_type, params) in self._content_types: if (best_content_type == content_type): return params return {}
'Find longest match for a given URL path.'
def _match(self, host, port, path_info):
for ((domain, app_url), app) in self.applications: if (domain and (domain != host) and (domain != ((host + ':') + port))): continue if ((path_info == app_url) or path_info.startswith((app_url + '/'))): return (app, app_url) return (None, None)
'Check path suffix for MIME type and path prefix for API version.'
def _path_strategy(self, host, port, path_info):
mime_type = app = app_url = None parts = path_info.rsplit('.', 1) if (len(parts) > 1): possible_type = ('application/' + parts[1]) if (possible_type in wsgi.SUPPORTED_CONTENT_TYPES): mime_type = possible_type parts = path_info.split('/') if (len(parts) > 1): (poss...
'Check Content-Type header for API version.'
def _content_type_strategy(self, host, port, environ):
app = None params = parse_options_header(environ.get('CONTENT_TYPE', ''))[1] if ('version' in params): (app, app_url) = self._match(host, port, ('/v' + params['version'])) if app: app = self._set_script_name(app, app_url) return app
'Check Accept header for best matching MIME type and API version.'
def _accept_strategy(self, host, port, environ, supported_content_types):
accept = Accept(environ.get('HTTP_ACCEPT', '')) app = None (mime_type, params) = accept.best_match(supported_content_types) if ('version' in params): (app, app_url) = self._match(host, port, ('/v' + params['version'])) if app: app = self._set_script_name(app, app_url) ret...
'Sets the specified host\'s ability to accept new servicemanages.'
def _set_enabled_status(self, req, host, enabled):
context = req.environ['monitor.context'] state = ('enabled' if enabled else 'disabled') LOG.audit((_('Setting host %(host)s to %(state)s.') % locals())) result = self.api.set_host_enabled(context, host=host, enabled=enabled) if (result not in ('enabled', 'disabled')): raise webob...
'Shows the servicemanage usage info given by hosts. :param context: security context :param host: hostname :returns: expected to use HostShowTemplate. ex.:: {\'host\': {\'resource\':D},..} D: {\'host\': \'hostname\',\'project\': \'admin\', \'servicemanage_count\': 1, \'total_servicemanage_gb\': 2048}'
@wsgi.serializers(xml=HostShowTemplate) def show(self, req, id):
host = id context = req.environ['monitor.context'] if (not context.is_admin): msg = _('Describe-resource is admin only functionality') raise webob.exc.HTTPForbidden(explanation=msg) try: host_ref = db.service_get_by_host_and_topic(context, host, FLAGS.servicemanage_to...
'Returns the list of extra specs for a given servicemanage type'
@wsgi.serializers(xml=ServiceManageTypeExtraSpecsTemplate) def index(self, req, type_id):
context = req.environ['monitor.context'] authorize(context) self._check_type(context, type_id) return self._get_extra_specs(context, type_id)
'Return a single extra spec item.'
@wsgi.serializers(xml=ServiceManageTypeExtraSpecTemplate) def show(self, req, type_id, id):
context = req.environ['monitor.context'] authorize(context) self._check_type(context, type_id) specs = self._get_extra_specs(context, type_id) if (id in specs['extra_specs']): return {id: specs['extra_specs'][id]} else: raise webob.exc.HTTPNotFound()
'Deletes an existing extra spec'
def delete(self, req, type_id, id):
context = req.environ['monitor.context'] self._check_type(context, type_id) authorize(context) db.servicemanage_type_extra_specs_delete(context, type_id, id) return webob.Response(status_int=202)
'Convert the quota object to a result dict'
def _format_quota_set(self, quota_class, quota_set):
result = dict(id=str(quota_class)) for resource in QUOTAS.resources: result[resource] = quota_set[resource] return dict(quota_class_set=result)
'Return a list of all running services. Filter by host & service name.'
@wsgi.serializers(xml=ServicesIndexTemplate) def index(self, req):
context = req.environ['monitor.context'] authorize(context) now = timeutils.utcnow() services = db.service_get_all(context) host = '' if ('host' in req.GET): host = req.GET['host'] service = '' if ('service' in req.GET): service = req.GET['service'] if host: s...
'Enable/Disable scheduling for a service'
@wsgi.serializers(xml=ServicesUpdateTemplate) def update(self, req, id, body):
context = req.environ['monitor.context'] authorize(context) if (id == 'enable'): disabled = False elif (id == 'disable'): disabled = True else: raise webob.exc.HTTPNotFound('Unknown action') try: host = body['host'] service = body['service'] except ...
'Convert the quota object to a result dict'
def _format_quota_set(self, project_id, quota_set):
result = dict(id=str(project_id)) for resource in QUOTAS.resources: result[resource] = quota_set[resource] return dict(quota_set=result)
'Return data about the given backup.'
@wsgi.serializers(xml=BackupTemplate) def show(self, req, id):
LOG.debug(_('show called for member %s'), id) context = req.environ['monitor.context'] try: backup = self.backup_api.get(context, backup_id=id) except exception.BackupNotFound as error: raise exc.HTTPNotFound(explanation=unicode(error)) return self._view_builder.detail(re...
'Delete a backup.'
def delete(self, req, id):
LOG.debug(_('delete called for member %s'), id) context = req.environ['monitor.context'] LOG.audit(_('Delete backup with id: %s'), id, context=context) try: self.backup_api.delete(context, id) except exception.BackupNotFound as error: raise exc.HTTPNotFound(ex...
'Returns a summary list of backups.'
@wsgi.serializers(xml=BackupsTemplate) def index(self, req):
return self._get_backups(req, is_detail=False)
'Returns a detailed list of backups.'
@wsgi.serializers(xml=BackupsTemplate) def detail(self, req):
return self._get_backups(req, is_detail=True)
'Returns a list of backups, transformed through view builder.'
def _get_backups(self, req, is_detail):
context = req.environ['monitor.context'] backups = self.backup_api.get_all(context) limited_list = common.limited(backups, req) if is_detail: backups = self._view_builder.detail_list(req, limited_list) else: backups = self._view_builder.summary_list(req, limited_list) return back...
'Create a new backup.'
@wsgi.response(202) @wsgi.serializers(xml=BackupTemplate) @wsgi.deserializers(xml=CreateDeserializer) def create(self, req, body):
LOG.debug(_('Creating new backup %s'), body) if (not self.is_valid_body(body, 'backup')): raise exc.HTTPBadRequest() context = req.environ['monitor.context'] try: backup = body['backup'] servicemanage_id = backup['servicemanage_id'] except KeyError: msg = _('...
'Restore an existing backup to a servicemanage.'
@wsgi.response(202) @wsgi.serializers(xml=BackupRestoreTemplate) @wsgi.deserializers(xml=RestoreDeserializer) def restore(self, req, id, body):
backup_id = id LOG.debug((_('Restoring backup %(backup_id)s (%(body)s)') % locals())) if (not self.is_valid_body(body, 'restore')): raise exc.HTTPBadRequest() context = req.environ['monitor.context'] try: restore = body['restore'] except KeyError: msg = _('Incorr...
'Creates a new servicemanage type.'
@wsgi.action('create') @wsgi.serializers(xml=types.ServiceManageTypeTemplate) def _create(self, req, body):
context = req.environ['monitor.context'] authorize(context) if (not self.is_valid_body(body, 'servicemanage_type')): raise webob.exc.HTTPBadRequest() vol_type = body['servicemanage_type'] name = vol_type.get('name', None) specs = vol_type.get('extra_specs', {}) if ((name is None) or ...
'Deletes an existing servicemanage type.'
@wsgi.action('delete') def _delete(self, req, id):
context = req.environ['monitor.context'] authorize(context) try: vol_type = servicemanage_types.get_servicemanage_type(context, id) servicemanage_types.destroy(context, vol_type['id']) except exception.NotFound: raise webob.exc.HTTPNotFound() return webob.Response(status_int=...
'Add attachment metadata.'
@wsgi.action('os-attach') def _attach(self, req, id, body):
context = req.environ['monitor.context'] servicemanage = self.servicemanage_api.get(context, id) instance_uuid = body['os-attach']['instance_uuid'] mountpoint = body['os-attach']['mountpoint'] self.servicemanage_api.attach(context, servicemanage, instance_uuid, mountpoint) return webob.Response(...
'Clear attachment metadata.'
@wsgi.action('os-detach') def _detach(self, req, id, body):
context = req.environ['monitor.context'] servicemanage = self.servicemanage_api.get(context, id) self.servicemanage_api.detach(context, servicemanage) return webob.Response(status_int=202)
'Mark servicemanage as reserved.'
@wsgi.action('os-reserve') def _reserve(self, req, id, body):
context = req.environ['monitor.context'] servicemanage = self.servicemanage_api.get(context, id) self.servicemanage_api.reserve_servicemanage(context, servicemanage) return webob.Response(status_int=202)
'Unmark servicemanage as reserved.'
@wsgi.action('os-unreserve') def _unreserve(self, req, id, body):
context = req.environ['monitor.context'] servicemanage = self.servicemanage_api.get(context, id) self.servicemanage_api.unreserve_servicemanage(context, servicemanage) return webob.Response(status_int=202)
'Update servicemanage status to \'detaching\'.'
@wsgi.action('os-begin_detaching') def _begin_detaching(self, req, id, body):
context = req.environ['monitor.context'] servicemanage = self.servicemanage_api.get(context, id) self.servicemanage_api.begin_detaching(context, servicemanage) return webob.Response(status_int=202)
'Roll back servicemanage status to \'in-use\'.'
@wsgi.action('os-roll_detaching') def _roll_detaching(self, req, id, body):
context = req.environ['monitor.context'] servicemanage = self.servicemanage_api.get(context, id) self.servicemanage_api.roll_detaching(context, servicemanage) return webob.Response(status_int=202)
'Initialize servicemanage attachment.'
@wsgi.action('os-initialize_connection') def _initialize_connection(self, req, id, body):
context = req.environ['monitor.context'] servicemanage = self.servicemanage_api.get(context, id) connector = body['os-initialize_connection']['connector'] info = self.servicemanage_api.initialize_connection(context, servicemanage, connector) return {'connection_info': info}
'Terminate servicemanage attachment.'
@wsgi.action('os-terminate_connection') def _terminate_connection(self, req, id, body):
context = req.environ['monitor.context'] servicemanage = self.servicemanage_api.get(context, id) connector = body['os-terminate_connection']['connector'] self.servicemanage_api.terminate_connection(context, servicemanage, connector) return webob.Response(status_int=202)
'Uploads the specified servicemanage to image service.'
@wsgi.response(202) @wsgi.action('os-servicemanage_upload_image') @wsgi.serializers(xml=ServiceManageToImageSerializer) @wsgi.deserializers(xml=ServiceManageToImageDeserializer) def _servicemanage_upload_image(self, req, id, body):
context = req.environ['monitor.context'] try: params = body['os-servicemanage_upload_image'] except (TypeError, KeyError): msg = _('Invalid request body') raise webob.exc.HTTPBadRequest(explanation=msg) if (not params.get('image_name')): msg = _('No image_name ...
'Reset status on the resource.'
@wsgi.action('os-reset_status') def _reset_status(self, req, id, body):
context = req.environ['monitor.context'] self.authorize(context, 'reset_status') update = self.validate_update(body['os-reset_status']) msg = _("Updating %(resource)s '%(id)s' with '%(update)r'") LOG.debug(msg, {'resource': self.resource_name, 'id': id, 'update': update}) try: ...
'Delete a resource, bypassing the check that it must be available.'
@wsgi.action('os-force_delete') def _force_delete(self, req, id, body):
context = req.environ['monitor.context'] self.authorize(context, 'force_delete') try: resource = self._get(context, id) except exception.NotFound: raise exc.HTTPNotFound() self._delete(context, resource, force=True) return webob.Response(status_int=202)
'Roll back a bad detach after the servicemanage been disconnected from the hypervisor.'
@wsgi.action('os-force_detach') def _force_detach(self, req, id, body):
context = req.environ['monitor.context'] self.authorize(context, 'force_detach') try: servicemanage = self._get(context, id) except exception.NotFound: raise exc.HTTPNotFound() self.servicemanage_api.terminate_connection(context, servicemanage, {}, force=True) self.servicemanage_...
'Return all versions.'
@wsgi.serializers(xml=VersionsTemplate, atom=VersionsAtomSerializer) def index(self, req):
builder = views_versions.get_view_builder(req) return builder.build_versions(VERSIONS)
'Return multiple choices.'
@wsgi.serializers(xml=ChoicesTemplate) @wsgi.response(300) def multi(self, req):
builder = views_versions.get_view_builder(req) return builder.build_choices(VERSIONS, req)
'Parse dictionary created by routes library.'
def get_action_args(self, request_environment):
args = {} if (request_environment['PATH_INFO'] == '/'): args['action'] = 'index' else: args['action'] = 'multi' return args
'Save this object.'
def save(self, session=None):
if (not session): session = get_session() session.add(self) try: session.flush() except IntegrityError as e: if str(e).endswith('is not unique'): raise exception.Duplicate(str(e)) else: raise
'Delete this object.'
def delete(self, session=None):
self.deleted = True self.deleted_at = timeutils.utcnow() self.save(session=session)
'Make the model object behave like a dict.'
def update(self, values):
for (k, v) in values.iteritems(): setattr(self, k, v)
'Make the model object behave like a dict. Includes attributes from joins.'
def iteritems(self):
local = dict(self) joined = dict([(k, v) for (k, v) in self.__dict__.iteritems() if (not (k[0] == '_'))]) local.update(joined) return local.iteritems()
'Return an item from the pool, when one is available. This may cause the calling greenthread to block. Check if a connection is active before returning it. For dead connections create and return a new connection.'
def get(self):
if self.free_items: conn = self.free_items.popleft() if conn: if conn.get_transport().is_active(): return conn else: conn.close() return self.create() if (self.current_size < self.max_size): created = self.create() s...
':param retvalue: Value that LoopingCall.wait() should return.'
def __init__(self, retvalue=True):
self.retvalue = retvalue
'Rollback a series of actions then re-raise the exception. .. note:: (sirp) This should only be called within an exception handler.'
def rollback_and_reraise(self, msg=None, **kwargs):
with excutils.save_and_reraise_exception(): if msg: LOG.exception(msg, **kwargs) self._rollback()
'Initialize the service launcher. :returns: None'
def __init__(self):
self._services = []
'Start and wait for a server to finish. :param service: Server to run and wait for. :returns: None'
@staticmethod def run_server(server):
server.start() server.wait()
'Load and start the given server. :param server: The server you would like to start. :returns: None'
def launch_server(self, server):
gt = eventlet.spawn(self.run_server, server) self._services.append(gt)
'Stop all services which are currently running. :returns: None'
def stop(self):
for service in self._services: service.kill()
'Waits until all services have been stopped, and then returns. :returns: None'
def wait(self):
def sigterm(sig, frame): LOG.audit(_('SIGTERM received')) raise KeyboardInterrupt signal.signal(signal.SIGTERM, sigterm) for service in self._services: try: service.wait() except greenlet.GreenletExit: pass
'Loop waiting on children to die and respawning as necessary.'
def wait(self):
while self.running: wrap = self._wait_child() if (not wrap): eventlet.greenthread.sleep(0.01) continue while (self.running and (len(wrap.children) < wrap.workers)): self._start_child(wrap) if self.sigcaught: signame = {signal.SIGTERM: 'SIGTERM'...
'Instantiates class and passes back application object. :param host: defaults to FLAGS.host :param binary: defaults to basename of executable :param topic: defaults to bin_name - \'monitor-\' part :param manager: defaults to FLAGS.<topic>_manager :param report_interval: defaults to FLAGS.report_interval :param periodic...
@classmethod def create(cls, host=None, binary=None, topic=None, manager=None, report_interval=None, periodic_interval=None, periodic_fuzzy_delay=None, service_name=None):
if (not host): host = FLAGS.host if (not binary): binary = os.path.basename(inspect.stack()[(-1)][1]) if (not topic): topic = binary if (not manager): subtopic = topic.rpartition('monitor-')[2] manager = FLAGS.get(('%s_manager' % subtopic), None) if (report_in...
'Destroy the service object in the datastore.'
def kill(self):
self.stop() try: db.service_destroy(context.get_admin_context(), self.service_id) except exception.NotFound: LOG.warn(_('Service killed that has no database entry'))
'Tasks to be run at a periodic interval.'
def periodic_tasks(self, raise_on_error=False):
ctxt = context.get_admin_context() self.manager.periodic_tasks(ctxt, raise_on_error=raise_on_error)
'Update the state of this service in the datastore.'
def report_state(self):
ctxt = context.get_admin_context() zone = FLAGS.monitor_availability_zone state_catalog = {} try: try: service_ref = db.service_get(ctxt, self.service_id) except exception.NotFound: LOG.debug(_('The service database object disappeared, Recreating ...
'Initialize, but do not start the WSGI server. :param name: The name of the WSGI server given to the loader. :param loader: Loads the WSGI application using the given name. :returns: None'
def __init__(self, name, loader=None):
self.name = name self.manager = self._get_manager() self.loader = (loader or wsgi.Loader()) self.app = self.loader.load_app(name) self.host = getattr(FLAGS, ('%s_listen' % name), '0.0.0.0') self.port = getattr(FLAGS, ('%s_listen_port' % name), 0) self.server = wsgi.Server(name, self.app, hos...
'Initialize a Manager object appropriate for this service. Use the service name to look up a Manager subclass from the configuration and initialize an instance. If no class name is configured, just return None. :returns: a Manager instance, or None.'
def _get_manager(self):
fl = ('%s_manager' % self.name) if (fl not in FLAGS): return None manager_class_name = FLAGS.get(fl, None) if (not manager_class_name): return None manager_class = importutils.import_class(manager_class_name) return manager_class()
'Start serving this service using loaded configuration. Also, retrieve updated port number in case \'0\' was passed in, which indicates a random port should be used. :returns: None'
def start(self):
if self.manager: self.manager.init_host() self.server.start() self.port = self.server.port
'Stop serving this API. :returns: None'
def stop(self):
self.server.stop()
'Wait for the service to stop serving this API. :returns: None'
def wait(self):
self.server.wait()
'Uses contextstring if request_id is set, otherwise default.'
def format(self, record):
for key in ('instance', 'color'): if (key not in record.__dict__): record.__dict__[key] = '' if record.__dict__.get('request_id', None): self._fmt = CONF.logging_context_format_string else: self._fmt = CONF.logging_default_format_string if ((record.levelno == logging....
'Format exception output with CONF.logging_exception_prefix.'
def formatException(self, exc_info, record=None):
if (not record): return logging.Formatter.formatException(self, exc_info) stringbuffer = cStringIO.StringIO() traceback.print_exception(exc_info[0], exc_info[1], exc_info[2], None, stringbuffer) lines = stringbuffer.getvalue().split('\n') stringbuffer.close() if (CONF.logging_exception_p...
'Initialize an RpcProxy. :param topic: The topic to use for all messages. :param default_version: The default API version to request in all outgoing messages. This can be overridden on a per-message basis.'
def __init__(self, topic, default_version):
self.topic = topic self.default_version = default_version self.host = os.popen('hostname').read().strip() super(RpcProxy, self).__init__()
'Helper method to set the version in a message. :param msg: The message having a version added to it. :param vers: The version number to add to the message.'
def _set_version(self, msg, vers):
msg['version'] = (vers if vers else self.default_version)
'Return the topic to use for a message.'
def _get_topic(self, topic):
return (topic if topic else self.topic)
'rpc.call() a remote method. :param context: The request context :param msg: The message to send, including the method and args. :param topic: Override the topic for this message. :param timeout: (Optional) A timeout to use when waiting for the response. If no timeout is specified, a default timeout will be used that ...
def call(self, context, msg, topic=None, version=None, timeout=None):
self._set_version(msg, version) return rpc.call(context, self._get_topic(topic), msg, timeout)
'rpc.multicall() a remote method. :param context: The request context :param msg: The message to send, including the method and args. :param topic: Override the topic for this message. :param timeout: (Optional) A timeout to use when waiting for the response. If no timeout is specified, a default timeout will be used ...
def multicall(self, context, msg, topic=None, version=None, timeout=None):
self._set_version(msg, version) return rpc.multicall(context, self._get_topic(topic), msg, timeout)
'rpc.cast() a remote method. :param context: The request context :param msg: The message to send, including the method and args. :param topic: Override the topic for this message. :param version: (Optional) Override the requested API version in this message. :returns: None. rpc.cast() does not wait on any return value...
def cast(self, context, msg, topic=None, version=None):
self._set_version(msg, version) rpc.cast(context, self._get_topic(topic), msg)
'rpc.fanout_cast() a remote method. :param context: The request context :param msg: The message to send, including the method and args. :param topic: Override the topic for this message. :param version: (Optional) Override the requested API version in this message. :returns: None. rpc.fanout_cast() does not wait on an...
def fanout_cast(self, context, msg, topic=None, version=None):
self._set_version(msg, version) rpc.fanout_cast(context, self._get_topic(topic), msg)
'rpc.cast_to_server() a remote method. :param context: The request context :param server_params: Server parameters. See rpc.cast_to_server() for details. :param msg: The message to send, including the method and args. :param topic: Override the topic for this message. :param version: (Optional) Override the requested ...
def cast_to_server(self, context, server_params, msg, topic=None, version=None):
self._set_version(msg, version) rpc.cast_to_server(context, server_params, self._get_topic(topic), msg)
'rpc.fanout_cast_to_server() a remote method. :param context: The request context :param server_params: Server parameters. See rpc.cast_to_server() for details. :param msg: The message to send, including the method and args. :param topic: Override the topic for this message. :param version: (Optional) Override the req...
def fanout_cast_to_server(self, context, server_params, msg, topic=None, version=None):
self._set_version(msg, version) rpc.fanout_cast_to_server(context, server_params, self._get_topic(topic), msg)
'Create a new connection, or get one from the pool'
def __init__(self, conf, connection_pool, pooled=True, server_params=None):
self.connection = None self.conf = conf self.connection_pool = connection_pool if pooled: self.connection = connection_pool.get() else: self.connection = connection_pool.connection_cls(conf, server_params=server_params) self.pooled = pooled
'When with ConnectionContext() is used, return self'
def __enter__(self):
return self
'If the connection came from a pool, clean it up and put it back. If it did not come from a pool, close it.'
def _done(self):
if self.connection: if self.pooled: self.connection.reset() self.connection_pool.put(self.connection) else: try: self.connection.close() except Exception: pass self.connection = None
'End of \'with\' statement. We\'re done here.'
def __exit__(self, exc_type, exc_value, tb):
self._done()
'Caller is done with this connection. Make sure we cleaned up.'
def __del__(self):
self._done()
'Caller is done with this connection.'
def close(self):
self._done()
'Proxy all other calls to the Connection instance'
def __getattr__(self, key):
if self.connection: return getattr(self.connection, key) else: raise rpc_common.InvalidRPCConnectionReuse()
'AMQP consumers may read same message twice when exceptions occur before ack is returned. This method prevents doing it.'
def check_duplicate_message(self, message_data):
if (UNIQUE_ID in message_data): msg_id = message_data[UNIQUE_ID] if (msg_id not in self.prev_msgids): self.prev_msgids.append(msg_id) else: raise rpc_common.DuplicateMessageError(msg_id=msg_id)
'Wait for all callback threads to exit.'
def wait(self):
self.pool.waitall()
':param conf: cfg.CONF instance :param callback: a callable (probably a function) :param connection_pool: connection pool as returned by get_connection_pool()'
def __init__(self, conf, callback, connection_pool):
super(CallbackWrapper, self).__init__(conf=conf, connection_pool=connection_pool) self.callback = callback
'Consumer callback to call a method on a proxy object. Parses the message for validity and fires off a thread to call the proxy object method. Message data should be a dictionary with two keys: method: string representing the method to call args: dictionary of arg: value Example: {\'method\': \'echo\', \'args\': {\'val...
def __call__(self, message_data):
if hasattr(local.store, 'context'): del local.store.context rpc_common._safe_log(LOG.debug, _('received %s'), message_data) self.msg_id_cache.check_duplicate_message(message_data) ctxt = unpack_context(self.conf, message_data) method = message_data.get('method') args = message_data.ge...
'Process a message in a new thread. If the proxy object we have has a dispatch method (see rpc.dispatcher.RpcDispatcher), pass it the version, method, and args and let it dispatch as appropriate. If not, use the old behavior of magically calling the specified method on the proxy we have here.'
def _process_data(self, ctxt, version, method, args):
ctxt.update_store() try: rval = self.proxy.dispatch(ctxt, version, method, **args) if inspect.isgenerator(rval): for x in rval: ctxt.reply(x, None, connection_pool=self.connection_pool) else: ctxt.reply(rval, None, connection_pool=self.connection_p...