desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Spawn a thread to handle incoming messages. Spawn a thread that will be responsible for handling all incoming messages for consumers that were set up on this connection. Message dispatching inside of this is expected to be implemented in a non-blocking manner. An example implementation would be having this thread pul...
def consume_in_thread(self):
raise NotImplementedError()
'Return a version of this context with admin flag set.'
def elevated(self, read_deleted=None, overwrite=False):
context = self.deepcopy() context.values['is_admin'] = True context.values.setdefault('roles', []) if ('admin' not in context.values['roles']): context.values['roles'].append('admin') if (read_deleted is not None): context.values['read_deleted'] = read_deleted return context
'Declare a queue on an amqp channel. \'channel\' is the amqp channel to use \'callback\' is the callback to call when messages are received \'tag\' is a unique ID for the consumer on the channel queue name, exchange name, and other kombu options are passed in here as a dictionary.'
def __init__(self, channel, callback, tag, **kwargs):
self.callback = callback self.tag = str(tag) self.kwargs = kwargs self.queue = None self.reconnect(channel)
'Re-declare the queue after a rabbit reconnect'
def reconnect(self, channel):
self.channel = channel self.kwargs['channel'] = channel self.queue = kombu.entity.Queue(**self.kwargs) self.queue.declare()
'Actually declare the consumer on the amqp channel. This will start the flow of messages from the queue. Using the Connection.iterconsume() iterator will process the messages, calling the appropriate callback. If a callback is specified in kwargs, use that. Otherwise, use the callback passed during __init__() If kwa...
def consume(self, *args, **kwargs):
options = {'consumer_tag': self.tag} options['nowait'] = kwargs.get('nowait', False) callback = kwargs.get('callback', self.callback) if (not callback): raise ValueError('No callback defined') def _callback(raw_message): message = self.channel.message_to_python(raw_message) ...
'Cancel the consuming from the queue, if it has started'
def cancel(self):
try: self.queue.cancel(self.tag) except KeyError as e: if (str(e) != ("u'%s'" % self.tag)): raise self.queue = None
'Init a \'direct\' queue. \'channel\' is the amqp channel to use \'msg_id\' is the msg_id to listen on \'callback\' is the callback to call when messages are received \'tag\' is a unique ID for the consumer on the channel Other kombu options may be passed'
def __init__(self, conf, channel, msg_id, callback, tag, **kwargs):
options = {'durable': False, 'queue_arguments': _get_queue_arguments(conf), 'auto_delete': True, 'exclusive': False} options.update(kwargs) exchange = kombu.entity.Exchange(name=msg_id, type='direct', durable=options['durable'], auto_delete=options['auto_delete']) super(DirectConsumer, self).__init__(ch...
'Init a \'topic\' queue. :param channel: the amqp channel to use :param topic: the topic to listen on :paramtype topic: str :param callback: the callback to call when messages are received :param tag: a unique ID for the consumer on the channel :param name: optional queue name, defaults to topic :paramtype name: str Ot...
def __init__(self, conf, channel, topic, callback, tag, name=None, exchange_name=None, **kwargs):
options = {'durable': conf.rabbit_durable_queues, 'queue_arguments': _get_queue_arguments(conf), 'auto_delete': False, 'exclusive': False} options.update(kwargs) exchange_name = (exchange_name or rpc_amqp.get_control_exchange(conf)) exchange = kombu.entity.Exchange(name=exchange_name, type='topic', dura...
'Init a \'fanout\' queue. \'channel\' is the amqp channel to use \'topic\' is the topic to listen on \'callback\' is the callback to call when messages are received \'tag\' is a unique ID for the consumer on the channel Other kombu options may be passed'
def __init__(self, conf, channel, topic, callback, tag, **kwargs):
unique = uuid.uuid4().hex exchange_name = ('%s_fanout' % topic) queue_name = ('%s_fanout_%s' % (topic, unique)) options = {'durable': False, 'queue_arguments': _get_queue_arguments(conf), 'auto_delete': True, 'exclusive': False} options.update(kwargs) exchange = kombu.entity.Exchange(name=exchan...
'Init the Publisher class with the exchange_name, routing_key, and other options'
def __init__(self, channel, exchange_name, routing_key, **kwargs):
self.exchange_name = exchange_name self.routing_key = routing_key self.kwargs = kwargs self.reconnect(channel)
'Re-establish the Producer after a rabbit reconnection'
def reconnect(self, channel):
self.exchange = kombu.entity.Exchange(name=self.exchange_name, **self.kwargs) self.producer = kombu.messaging.Producer(exchange=self.exchange, channel=channel, routing_key=self.routing_key)
'Send a message'
def send(self, msg, timeout=None):
if timeout: self.producer.publish(msg, headers={'ttl': (timeout * 1000)}) else: self.producer.publish(msg)
'init a \'direct\' publisher. Kombu options may be passed as keyword args to override defaults'
def __init__(self, conf, channel, msg_id, **kwargs):
options = {'durable': False, 'auto_delete': True, 'exclusive': False} options.update(kwargs) super(DirectPublisher, self).__init__(channel, msg_id, msg_id, type='direct', **options)
'init a \'topic\' publisher. Kombu options may be passed as keyword args to override defaults'
def __init__(self, conf, channel, topic, **kwargs):
options = {'durable': conf.rabbit_durable_queues, 'auto_delete': False, 'exclusive': False} options.update(kwargs) exchange_name = rpc_amqp.get_control_exchange(conf) super(TopicPublisher, self).__init__(channel, exchange_name, topic, type='topic', **options)
'init a \'fanout\' publisher. Kombu options may be passed as keyword args to override defaults'
def __init__(self, conf, channel, topic, **kwargs):
options = {'durable': False, 'auto_delete': True, 'exclusive': False} options.update(kwargs) super(FanoutPublisher, self).__init__(channel, ('%s_fanout' % topic), None, type='fanout', **options)
'Handles fetching what ssl params should be used for the connection (if any)'
def _fetch_ssl_params(self):
ssl_params = dict() if self.conf.kombu_ssl_version: ssl_params['ssl_version'] = self.conf.kombu_ssl_version if self.conf.kombu_ssl_keyfile: ssl_params['keyfile'] = self.conf.kombu_ssl_keyfile if self.conf.kombu_ssl_certfile: ssl_params['certfile'] = self.conf.kombu_ssl_certfile ...
'Connect to rabbit. Re-establish any queues that may have been declared before if we are reconnecting. Exceptions should be handled by the caller.'
def _connect(self, params):
if self.connection: LOG.info((_('Reconnecting to AMQP server on %(hostname)s:%(port)d') % params)) try: self.connection.release() except self.connection_errors: pass self.connection = None self.connection = kombu.connection.BrokerConnection(...
'Handles reconnecting and re-establishing queues. Will retry up to self.max_retries number of times. self.max_retries = 0 means to retry forever. Sleep between tries, starting at self.interval_start seconds, backing off self.interval_stepping number of seconds each attempt.'
def reconnect(self):
attempt = 0 while True: params = self.params_list[(attempt % len(self.params_list))] attempt += 1 try: self._connect(params) return except (IOError, self.connection_errors) as e: pass except Exception as e: if ('timeout' not...
'Convenience call for bin/clear_rabbit_queues'
def get_channel(self):
return self.channel
'Close/release this connection'
def close(self):
self.cancel_consumer_thread() self.wait_on_proxy_callbacks() self.connection.release() self.connection = None
'Reset a connection so it can be used again'
def reset(self):
self.cancel_consumer_thread() self.wait_on_proxy_callbacks() self.channel.close() self.channel = self.connection.channel() if self.memory_transport: self.channel._new_queue('ae.undeliver') self.consumers = []
'Create a Consumer using the class that was passed in and add it to our list of consumers'
def declare_consumer(self, consumer_cls, topic, callback):
def _connect_error(exc): log_info = {'topic': topic, 'err_str': str(exc)} LOG.error((_("Failed to declare consumer for topic '%(topic)s': %(err_str)s") % log_info)) def _declare_consumer(): consumer = consumer_cls(self.conf, self.channel, topic, callback, self.consum...
'Return an iterator that will consume from all queues/consumers'
def iterconsume(self, limit=None, timeout=None):
info = {'do_consume': True} def _error_callback(exc): if isinstance(exc, socket.timeout): LOG.debug((_('Timed out waiting for RPC response: %s') % str(exc))) raise rpc_common.Timeout() else: LOG.exception((_('Failed to consume messag...
'Cancel a consumer thread'
def cancel_consumer_thread(self):
if (self.consumer_thread is not None): self.consumer_thread.kill() try: self.consumer_thread.wait() except greenlet.GreenletExit: pass self.consumer_thread = None
'Wait for all proxy callback threads to exit.'
def wait_on_proxy_callbacks(self):
for proxy_cb in self.proxy_callbacks: proxy_cb.wait()
'Send to a publisher based on the publisher class'
def publisher_send(self, cls, topic, msg, timeout=None, **kwargs):
def _error_callback(exc): log_info = {'topic': topic, 'err_str': str(exc)} LOG.exception((_("Failed to publish message to topic '%(topic)s': %(err_str)s") % log_info)) def _publish(): publisher = cls(self.conf, self.channel, topic, **kwargs) publisher.send(ms...
'Create a \'direct\' queue. In nova\'s use, this is generally a msg_id queue used for responses for call/multicall'
def declare_direct_consumer(self, topic, callback):
self.declare_consumer(DirectConsumer, topic, callback)
'Create a \'topic\' consumer.'
def declare_topic_consumer(self, topic, callback=None, queue_name=None, exchange_name=None):
self.declare_consumer(functools.partial(TopicConsumer, name=queue_name, exchange_name=exchange_name), topic, callback)
'Create a \'fanout\' consumer'
def declare_fanout_consumer(self, topic, callback):
self.declare_consumer(FanoutConsumer, topic, callback)
'Send a \'direct\' message'
def direct_send(self, msg_id, msg):
self.publisher_send(DirectPublisher, msg_id, msg)
'Send a \'topic\' message'
def topic_send(self, topic, msg, timeout=None):
self.publisher_send(TopicPublisher, topic, msg, timeout)
'Send a \'fanout\' message'
def fanout_send(self, topic, msg):
self.publisher_send(FanoutPublisher, topic, msg)
'Send a notify message on a topic'
def notify_send(self, topic, msg, **kwargs):
self.publisher_send(NotifyPublisher, topic, msg, None, **kwargs)
'Consume from all queues/consumers'
def consume(self, limit=None):
it = self.iterconsume(limit=limit) while True: try: it.next() except StopIteration: return
'Consumer from all queues/consumers in a greenthread'
def consume_in_thread(self):
def _consumer_thread(): try: self.consume() except greenlet.GreenletExit: return if (self.consumer_thread is None): self.consumer_thread = eventlet.spawn(_consumer_thread) return self.consumer_thread
'Create a consumer that calls a method in a proxy object'
def create_consumer(self, topic, proxy, fanout=False):
proxy_cb = rpc_amqp.ProxyCallback(self.conf, proxy, rpc_amqp.get_connection_pool(self.conf, Connection)) self.proxy_callbacks.append(proxy_cb) if fanout: self.declare_fanout_consumer(topic, proxy_cb) else: self.declare_topic_consumer(topic, proxy_cb)
'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...
':param retvalue: Value that LoopingCall.wait() should return.'
def __init__(self, retvalue=True):
self.retvalue = retvalue
'Allow loading of JSON rule data.'
@classmethod def load_json(cls, data, default_rule=None):
rules = dict(((k, parse_rule(v)) for (k, v) in jsonutils.loads(data).items())) return cls(rules, default_rule)
'Initialize the Rules store.'
def __init__(self, rules=None, default_rule=None):
super(Rules, self).__init__((rules or {})) self.default_rule = default_rule
'Implements the default rule handling.'
def __missing__(self, key):
if ((not self.default_rule) or (self.default_rule not in self)): raise KeyError(key) return self[self.default_rule]
'Dumps a string representation of the rules.'
def __str__(self):
out_rules = {} for (key, value) in self.items(): if isinstance(value, TrueCheck): out_rules[key] = '' else: out_rules[key] = str(value) return jsonutils.dumps(out_rules, indent=4)
'Retrieve a string representation of the Check tree rooted at this node.'
@abc.abstractmethod def __str__(self):
pass
'Perform the check. Returns False to reject the access or a true value (not necessary True) to accept the access.'
@abc.abstractmethod def __call__(self, target, cred):
pass
'Return a string representation of this check.'
def __str__(self):
return '!'
'Check the policy.'
def __call__(self, target, cred):
return False
'Return a string representation of this check.'
def __str__(self):
return '@'
'Check the policy.'
def __call__(self, target, cred):
return True
':param kind: The kind of the check, i.e., the field before the :param match: The match of the check, i.e., the field after the \':\'.'
def __init__(self, kind, match):
self.kind = kind self.match = match
'Return a string representation of this check.'
def __str__(self):
return ('%s:%s' % (self.kind, self.match))
'Initialize the \'not\' check. :param rule: The rule to negate. Must be a Check.'
def __init__(self, rule):
self.rule = rule
'Return a string representation of this check.'
def __str__(self):
return ('not %s' % self.rule)
'Check the policy. Returns the logical inverse of the wrapped check.'
def __call__(self, target, cred):
return (not self.rule(target, cred))
'Initialize the \'and\' check. :param rules: A list of rules that will be tested.'
def __init__(self, rules):
self.rules = rules
'Return a string representation of this check.'
def __str__(self):
return ('(%s)' % ' and '.join((str(r) for r in self.rules)))
'Check the policy. Requires that all rules accept in order to return True.'
def __call__(self, target, cred):
for rule in self.rules: if (not rule(target, cred)): return False return True
'Allows addition of another rule to the list of rules that will be tested. Returns the AndCheck object for convenience.'
def add_check(self, rule):
self.rules.append(rule) return self
'Initialize the \'or\' check. :param rules: A list of rules that will be tested.'
def __init__(self, rules):
self.rules = rules
'Return a string representation of this check.'
def __str__(self):
return ('(%s)' % ' or '.join((str(r) for r in self.rules)))
'Check the policy. Requires that at least one rule accept in order to return True.'
def __call__(self, target, cred):
for rule in self.rules: if rule(target, cred): return True return False
'Allows addition of another rule to the list of rules that will be tested. Returns the OrCheck object for convenience.'
def add_check(self, rule):
self.rules.append(rule) return self
'Create the class. Injects the \'reducers\' list, a list of tuples matching token sequences to the names of the corresponding reduction methods.'
def __new__(mcs, name, bases, cls_dict):
reducers = [] for (key, value) in cls_dict.items(): if (not hasattr(value, 'reducers')): continue for reduction in value.reducers: reducers.append((reduction, key)) cls_dict['reducers'] = reducers return super(ParseStateMeta, mcs).__new__(mcs, name, bases, cls_dic...
'Initialize the ParseState.'
def __init__(self):
self.tokens = [] self.values = []
'Perform a greedy reduction of the token stream. If a reducer method matches, it will be executed, then the reduce() method will be called recursively to search for any more possible reductions.'
def reduce(self):
for (reduction, methname) in self.reducers: if ((len(self.tokens) >= len(reduction)) and (self.tokens[(- len(reduction)):] == reduction)): meth = getattr(self, methname) results = meth(*self.values[(- len(reduction)):]) self.tokens[(- len(reduction)):] = [r[0] for r in re...
'Adds one more token to the state. Calls reduce().'
def shift(self, tok, value):
self.tokens.append(tok) self.values.append(value) self.reduce()
'Obtain the final result of the parse. Raises ValueError if the parse failed to reduce to a single result.'
@property def result(self):
if (len(self.values) != 1): raise ValueError('Could not parse rule') return self.values[0]
'Turn parenthesized expressions into a \'check\' token.'
@reducer('(', 'check', ')') @reducer('(', 'and_expr', ')') @reducer('(', 'or_expr', ')') def _wrap_check(self, _p1, check, _p2):
return [('check', check)]
'Create an \'and_expr\' from two checks joined by the \'and\' operator.'
@reducer('check', 'and', 'check') def _make_and_expr(self, check1, _and, check2):
return [('and_expr', AndCheck([check1, check2]))]
'Extend an \'and_expr\' by adding one more check.'
@reducer('and_expr', 'and', 'check') def _extend_and_expr(self, and_expr, _and, check):
return [('and_expr', and_expr.add_check(check))]
'Create an \'or_expr\' from two checks joined by the \'or\' operator.'
@reducer('check', 'or', 'check') def _make_or_expr(self, check1, _or, check2):
return [('or_expr', OrCheck([check1, check2]))]
'Extend an \'or_expr\' by adding one more check.'
@reducer('or_expr', 'or', 'check') def _extend_or_expr(self, or_expr, _or, check):
return [('or_expr', or_expr.add_check(check))]
'Invert the result of another check.'
@reducer('not', 'check') def _make_not_expr(self, _not, check):
return [('check', NotCheck(check))]
'Recursively checks credentials based on the defined rules.'
def __call__(self, target, creds):
try: return _rules[self.match](target, creds) except KeyError: return False
'Check that there is a matching role in the cred dict.'
def __call__(self, target, creds):
return (self.match.lower() in [x.lower() for x in creds['roles']])
'Check http: rules by calling to a remote server. This example implementation simply verifies that the response is exactly \'True\'.'
def __call__(self, target, creds):
url = (('http:' + self.match) % target) data = {'target': jsonutils.dumps(target), 'credentials': jsonutils.dumps(creds)} post_data = urllib.urlencode(data) f = urllib2.urlopen(url, post_data) return (f.read() == 'True')
'Check an individual match. Matches look like: tenant:%(tenant_id)s role:compute:admin'
def __call__(self, target, creds):
match = (self.match % target) if (self.kind in creds): return (match == unicode(creds[self.kind])) return False
'Initialize the service launcher. :returns: None'
def __init__(self):
self._services = threadgroup.ThreadGroup() eventlet_backdoor.initialize_if_enabled()
'Start and wait for a service to finish. :param service: service to run and wait for. :returns: None'
@staticmethod def run_service(service):
service.start() service.wait()
'Load and start the given service. :param service: The service you would like to start. :returns: None'
def launch_service(self, service):
self._services.add_thread(self.run_service, service)
'Stop all services which are currently running. :returns: None'
def stop(self):
self._services.stop()
'Waits until all services have been stopped, and then returns. :returns: None'
def wait(self):
self._services.wait()
'Loop waiting on children to die and respawning as necessary'
def wait(self):
LOG.debug(_('Full set of CONF:')) CONF.log_opt_values(LOG, std_logging.DEBUG) 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)): ...
'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 quantum.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
'Handle initialization if this is a standalone service. Child classes should override this method.'
def init_host(self):
pass
'Handler post initialization stuff. Child classes can override this method.'
def after_start(self):
pass
'Start a WSGI service in a new green thread.'
def _run(self, application, socket):
logger = logging.getLogger('eventlet.wsgi.server') eventlet.wsgi.server(socket, application, custom_pool=self.pool, protocol=UnixDomainHttpProtocol, log=logging.WritableLogger(logger))
'Populate the networks cache when the DHCP-agent starts'
def _populate_networks_cache(self):
try: existing_networks = self.dhcp_driver_cls.existing_dhcp_networks(self.conf, self.root_helper) for net_id in existing_networks: net = DictModel({'id': net_id, 'subnets': [], 'ports': []}) self.cache.put(net) except NotImplementedError: LOG.debug(_("The '%s' ...
'Activate the DHCP agent.'
def run(self):
self.sync_state() self.periodic_resync() self.lease_relay.start()
'Invoke an action on a DHCP driver instance.'
def call_driver(self, action, network):
try: driver = self.dhcp_driver_cls(self.conf, network, self.root_helper, self.device_manager, self._ns_name(network)) getattr(driver, action)() return True except Exception as e: self.needs_resync = True LOG.exception(_('Unable to %s dhcp.'), action)
'Sync the local DHCP state with Quantum.'
def sync_state(self):
LOG.info(_('Synchronizing state')) known_networks = set(self.cache.get_network_ids()) try: active_networks = set(self.plugin_rpc.get_active_networks()) for deleted_id in (known_networks - active_networks): self.disable_dhcp_helper(deleted_id) for network_id in active_n...
'Resync the dhcp state at the configured interval.'
def _periodic_resync_helper(self):
while True: eventlet.sleep(self.conf.resync_interval) if self.needs_resync: self.needs_resync = False self.sync_state()
'Spawn a thread to periodically resync the dhcp state.'
def periodic_resync(self):
eventlet.spawn(self._periodic_resync_helper)
'Enable DHCP for a network that meets enabling criteria.'
def enable_dhcp_helper(self, network_id):
try: network = self.plugin_rpc.get_network_info(network_id) except: self.needs_resync = True LOG.exception(_('Network %s RPC info call failed.'), network_id) return if (not network.admin_state_up): return for subnet in network.subnets: if su...