desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Adds to the "used" metric for the given quota.'
def tally(self, name, value):
value = (value or 0) if ('used' not in self.usages[name]): self.usages[name]['used'] = 0 self.usages[name]['used'] += int(value) self.update_available(name)
'Updates the "available" metric for the given quota.'
def update_available(self, name):
available = (self.usages[name]['quota'] - self.usages[name]['used']) if (available < 0): available = 0 self.usages[name]['available'] = available
'Returns the URL to redirect to after a successful action.'
def get_success_url(self, request=None):
current_container = self.table.kwargs.get('container_name', None) if (current_container in self.success_ids): return self.success_url return request.get_full_path()
'Returns a list of objects given the subfolder\'s path. The path is from the kwargs of the request.'
@property def objects(self):
if (not hasattr(self, '_objects')): objects = [] self._more = None marker = self.request.GET.get('marker', None) container_name = self.kwargs['container_name'] subfolder = self.kwargs['subfolder_path'] prefix = None if container_name: self.navigati...
'Returns a list of objects within the current folder.'
def get_objects_data(self):
filtered_objects = [item for item in self.objects if (not self.is_subdir(item))] return filtered_objects
'Returns a list of subfolders within the current folder.'
def get_subfolders_data(self):
filtered_objects = [item for item in self.objects if self.is_subdir(item)] return filtered_objects
'Setup subnet parameters This methods setups subnet parameters which are available in both create and update.'
def _setup_subnet_parameters(self, params, data, is_create=True):
is_update = (not is_create) params['enable_dhcp'] = data['enable_dhcp'] if (is_create and data['allocation_pools']): pools = [dict(zip(['start', 'end'], pool.strip().split(','))) for pool in data['allocation_pools'].split('\n') if pool.strip()] params['allocation_pools'] = pools if (data...
'Delete the created network when subnet creation failed'
def _delete_network(self, request, network):
try: api.quantum.network_delete(request, network.id) msg = (_('Delete the created network "%s" due to subnet creation failure.') % network.name) LOG.debug(msg) redirect = self.get_failure_url() messages.info(request, msg) raise exceptions.Ht...
'The form will not be valid if both copy_from and image_file are not provided.'
def test_no_location_or_file(self):
post = {'name': u'Ubuntu 11.10', 'disk_format': u'qcow2', 'minimum_disk': 15, 'minimum_ram': 512, 'is_public': 1} files = {} form = CreateImageForm(post, files) self.assertEqual(form.is_valid(), False)
'If HORIZON_IMAGES_ALLOW_UPLOAD is false, the image_file field widget will be a HiddenInput widget instead of a FileInput widget.'
@override_settings(HORIZON_IMAGES_ALLOW_UPLOAD=False) def test_image_upload_disabled(self):
form = CreateImageForm({}) self.assertEqual(isinstance(form.fields['image_file'].widget, HiddenInput), True)
'Check to make sure password fields match.'
def clean(self):
data = super(forms.Form, self).clean() if ('password' in data): if (data['password'] != data.get('confirm_password', None)): raise ValidationError(_('Passwords do not match.')) return data
'Naive case-insensitive search'
def filter(self, table, users, filter_string):
q = filter_string.lower() return [user for user in users if ((q in user.name.lower()) or (q in user.email.lower()))]
'Really naive case-insensitive search.'
def filter(self, table, tenants, filter_string):
q = filter_string.lower() def comp(tenant): if (q in tenant.name.lower()): return True return False return filter(comp, tenants)
'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
'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 openstack_dashboard.openstack.common import setup return setup.get_version_from_pkg_...
'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
'Tests api.keystone.remove_tenant_user Verifies that remove_tenant_user is called with the right arguments after iterating the user\'s roles. There are no assertions in this test because the checking is handled by mox in the VerifyAll() call in tearDown().'
def test_remove_tenant_user(self):
keystoneclient = self.stub_keystoneclient() tenant = self.tenants.first() keystoneclient.roles = self.mox.CreateMockAnything() keystoneclient.roles.roles_for_user(self.user.id, tenant.id).AndReturn(self.roles) for role in self.roles: keystoneclient.roles.remove_user_role(self.user.id, role.i...
'Asserts that the given response issued a 302 redirect without processing the view which is redirected to.'
def assertRedirectsNoFollow(self, response, expected_url):
assert ((response.status_code / 100) == 3), 'The response did not return a redirect.' self.assertEqual(response._headers.get('location', None), ('Location', (settings.TESTSERVER + expected_url))) self.assertEqual(response.status_code, 302)
'Asserts that the response either does not contain a form in it\'s context, or that if it does, that form has no errors.'
def assertNoFormErrors(self, response, context_name='form'):
context = getattr(response, 'context', {}) if ((not context) or (context_name not in context)): return True errors = response.context[context_name]._errors assert (len(errors) == 0), ('Unexpected errors were found on the form: %s' % errors)
'Asserts that the response does contain a form in it\'s context, and that form has errors, if count were given, it must match the exact numbers of errors'
def assertFormErrors(self, response, count=0, message=None, context_name='form'):
context = getattr(response, 'context', {}) assert (context and (context_name in context)), 'The response did not contain a form.' errors = response.context[context_name]._errors if count: assert (len(errors) == count), ('%d errors were found on the form, %d...
'Add a new object to this container. Generally this method should only be used during data loading, since adding data during a test can affect the results of other tests.'
def add(self, *args):
for obj in args: if (obj not in self._objects): self._objects.append(obj)
'Returns a list of all objects in this container.'
def list(self):
return self._objects
'Returns objects in this container whose attributes match the given keyword arguments.'
def filter(self, filtered=None, **kwargs):
if (filtered is None): filtered = self._objects try: (key, value) = kwargs.popitem() except KeyError: return filtered def get_match(obj): return (hasattr(obj, key) and (getattr(obj, key) == value)) return self.filter(filtered=filter(get_match, filtered), **kwargs)
'Returns the single object in this container whose attributes match the given keyword arguments. An error will be raised if the arguments provided don\'t return exactly one match.'
def get(self, **kwargs):
matches = self.filter(**kwargs) if (not matches): raise Exception('No matches found.') elif (len(matches) > 1): raise Exception('Multiple matches found.') else: return matches.pop()
'Returns the first object from this container.'
def first(self):
return self._objects[0]
'The hashes here were generated by running the same requests against boto.utils.canonical_string'
def test_canonical_string(self):
def verify(hash, path, headers): req = Request.blank(path, headers=headers) self.assertEquals(hash, hashlib.md5(swift3.canonical_string(req)).hexdigest()) verify('6dd08c75e42190a1ce9468d1fd2eb787', '/bucket/object', {'Content-Type': 'text/plain', 'X-Amz-Something': 'test', 'Date': 'whatever'}) ...
'Handle GET Service request'
def GET(self, env, start_response):
env['QUERY_STRING'] = 'format=json' body_iter = self._app_call(env) status = self._get_status_int() if (status != HTTP_OK): if (status in (HTTP_UNAUTHORIZED, HTTP_FORBIDDEN)): return get_err_response('AccessDenied') else: return get_err_response('InvalidURI') ...
'Handle GET Bucket (List Objects) request'
def GET(self, env, start_response):
if ('QUERY_STRING' in env): args = dict(urlparse.parse_qsl(env['QUERY_STRING'], 1)) else: args = {} if ('max-keys' in args): if (args.get('max-keys').isdigit() is False): return get_err_response('InvalidArgument') max_keys = min(int(args.get('max-keys', MAX_BUCKET_LIS...
'Handle PUT Bucket request'
def PUT(self, env, start_response):
if ('HTTP_X_AMZ_ACL' in env): amz_acl = env['HTTP_X_AMZ_ACL'] del env['HTTP_X_AMZ_ACL'] if ('QUERY_STRING' in env): del env['QUERY_STRING'] translated_acl = swift_acl_translate(amz_acl) if (translated_acl == 'Unsupported'): return get_err_response('Uns...
'Handle DELETE Bucket request'
def DELETE(self, env, start_response):
body_iter = self._app_call(env) status = self._get_status_int() if (status != HTTP_NO_CONTENT): if (status in (HTTP_UNAUTHORIZED, HTTP_FORBIDDEN)): return get_err_response('AccessDenied') elif (status == HTTP_NOT_FOUND): return get_err_response('NoSuchBucket') ...
'Handle POST Bucket (Delete/Upload Multiple Objects) request'
def POST(self, env, start_response):
if ('QUERY_STRING' in env): args = dict(urlparse.parse_qsl(env['QUERY_STRING'], 1)) else: args = {} if ('delete' in args): return self._delete_multiple_objects(env) if ('uploads' in args): return self.app(env, start_response) if ('uploadId' in args): return se...
'Handle HEAD Object request'
def HEAD(self, env, start_response):
return self.GETorHEAD(env, start_response)
'Handle GET Object request'
def GET(self, env, start_response):
return self.GETorHEAD(env, start_response)
'Handle PUT Object and PUT Object (Copy) request'
def PUT(self, env, start_response):
for (key, value) in env.items(): if key.startswith('HTTP_X_AMZ_META_'): del env[key] env[('HTTP_X_OBJECT_META_' + key[16:])] = value elif (key == 'HTTP_CONTENT_MD5'): if (value == ''): return get_err_response('InvalidDigest') try: ...
'Handle DELETE Object request'
def DELETE(self, env, start_response):
body_iter = self._app_call(env) status = self._get_status_int() if (status != HTTP_NO_CONTENT): if (status in (HTTP_UNAUTHORIZED, HTTP_FORBIDDEN)): return get_err_response('AccessDenied') elif (status == HTTP_NOT_FOUND): return get_err_response('NoSuchKey') el...
'Fake a transformerManager for pipeline The faked entry point setting is below: update: TransformerClass except: TransformerClassException drop: TransformerClassDrop'
def fake_tem_init(self):
pass
'Do not accept cross posting samples to different projects.'
def test_wrong_project_id(self):
s1 = [{'counter_name': 'my_counter_name', 'counter_type': 'gauge', 'counter_unit': 'instance', 'counter_volume': 1, 'source': 'closedstack', 'resource_id': 'bd9431c1-8d69-4ad3-803a-8d4a6b89fd36', 'project_id': '35b17138-b364-4e6a-a131-8f3099c5be68', 'user_id': 'efd87807-12d2-4b38-9c70-5f5c2ac427ff', 'resource_metad...
'Send multiple samples. The usecase here is to reduce the chatter and send the counters at a slower cadence.'
def test_multiple_samples(self):
samples = [] stamps = [] for x in range(6): dt = datetime.datetime(2012, 8, 27, x, 0, tzinfo=None) stamps.append(dt) s = {'counter_name': 'apples', 'counter_type': 'gauge', 'counter_unit': 'instance', 'counter_volume': float((x * 3)), 'source': 'evil', 'timestamp': dt.isoformat(), 'r...
'Do not accept posting samples with missing mandatory fields.'
def test_missing_mandatory_fields(self):
s1 = [{'counter_name': 'my_counter_name', 'counter_type': 'gauge', 'counter_unit': 'instance', 'counter_volume': 1, 'source': 'closedstack', 'resource_id': 'bd9431c1-8d69-4ad3-803a-8d4a6b89fd36', 'project_id': '35b17138-b364-4e6a-a131-8f3099c5be68', 'user_id': 'efd87807-12d2-4b38-9c70-5f5c2ac427ff', 'resource_metad...
'Do not accept a single post of mixed sources.'
def test_multiple_sources(self):
s1 = [{'counter_name': 'my_counter_name', 'counter_type': 'gauge', 'counter_unit': 'instance', 'counter_volume': 1, 'source': 'closedstack', 'project_id': '35b17138-b364-4e6a-a131-8f3099c5be68', 'user_id': 'efd87807-12d2-4b38-9c70-5f5c2ac427ff', 'resource_id': 'bd9431c1-8d69-4ad3-803a-8d4a6b89fd36'}, {'counter_name...
'Do accept a single post with some null sources this is a convience feature so you only have to set one of the sample\'s source field.'
def test_multiple_samples_some_null_sources(self):
s1 = [{'counter_name': 'my_counter_name', 'counter_type': 'gauge', 'counter_unit': 'instance', 'counter_volume': 1, 'source': 'paperstack', 'project_id': '35b17138-b364-4e6a-a131-8f3099c5be68', 'user_id': 'efd87807-12d2-4b38-9c70-5f5c2ac427ff', 'resource_id': 'bd9431c1-8d69-4ad3-803a-8d4a6b89fd36'}, {'counter_name'...
'Test even for arbitrary request method, this will still work.'
def test_bogus_request(self):
app = swift_middleware.CeilometerMiddleware(FakeApp(body=['']), {}) req = Request.blank('/1.0/account/container/obj', environ={'REQUEST_METHOD': 'BOGUS'}) list(app(req.environ, self.start_response)) counters = self.pipeline_manager.pipelines[0].counters self.assertEqual(len(counters), 1) data = ...
'Send a metering message for publishing :param context: Execution context from the service or RPC call :param counter: Counter from pipeline after transformation :param source: counter source'
def publish_counters(self, context, counters, source):
self.counters.extend(counters)
'Send a metering message for publishing :param context: Execution context from the service or RPC call :param counter: Counter from pipeline after transformation :param source: counter source'
def publish_counters(self, context, counters, source):
for counter in counters: msg = counter._asdict() msg['source'] = source host = self.host port = self.port LOG.debug((_('Publishing counter %(msg)s over UDP to %(host)s:%(port)d') % locals())) try: self.socket.sendto(msgpack.dumps(msg), (s...
'Send a metering message for publishing :param context: Execution context from the service or RPC call :param counter: Counter from pipeline after transformation :param source: counter source'
def publish_counters(self, context, counters, source):
meters = [meter_message_from_counter(counter, cfg.CONF.publisher_rpc.metering_secret, source) for counter in counters] topic = cfg.CONF.publisher_rpc.metering_topic msg = {'method': 'record_metering_data', 'version': '1.0', 'args': {'data': meters}} LOG.debug('PUBLISH: %s', str(msg)) rpc.cast(con...
'Return samples for the meter. :param q: Filter rules for the data to be returned. :param limit: Maximum number of samples to return.'
@wsme_pecan.wsexpose([Sample], [Query], int) def get_all(self, q=[], limit=None):
if (limit and (limit < 0)): raise ValueError('Limit must be positive') kwargs = _query_to_kwargs(q, storage.SampleFilter.__init__) kwargs['meter'] = self._id f = storage.SampleFilter(**kwargs) return [Sample.from_db_model(e) for e in pecan.request.storage_conn.get_samples(f, limit=l...
'Post a list of new Samples to Ceilometer. :param body: a list of samples within the request body.'
@wsme.validate([Sample]) @wsme_pecan.wsexpose([Sample], body=[Sample]) def post(self, body):
def get_consistent_source(): 'Find a source that can be applied across the sample group\n or raise InvalidInput if the sources are inconsistent.\n If all are...
'Computes the statistics of the samples in the time range given. :param q: Filter rules for the data to be returned. :param period: Returned result will be an array of statistics for a period long of that number of seconds.'
@wsme_pecan.wsexpose([Statistics], [Query], int) def statistics(self, q=[], period=None):
kwargs = _query_to_kwargs(q, storage.SampleFilter.__init__) kwargs['meter'] = self._id f = storage.SampleFilter(**kwargs) computed = pecan.request.storage_conn.get_meter_statistics(f, period) LOG.debug('computed value coming from %r', pecan.request.storage_conn) start = end = None ...
'Return all known meters, based on the data recorded so far. :param q: Filter rules for the meters to be returned.'
@wsme_pecan.wsexpose([Meter], [Query]) def get_all(self, q=[]):
kwargs = _query_to_kwargs(q, pecan.request.storage_conn.get_meters) return [Meter.from_db_model(m) for m in pecan.request.storage_conn.get_meters(**kwargs)]
'Retrieve details about one resource. :param resource_id: The UUID of the resource.'
@wsme_pecan.wsexpose(Resource, unicode) def get_one(self, resource_id):
authorized_project = acl.get_limited_to_project(pecan.request.headers) r = list(pecan.request.storage_conn.get_resources(resource=resource_id, project=authorized_project))[0] return Resource.from_db_and_links(r, self._resource_links(resource_id))
'Retrieve definitions of all of the resources. :param q: Filter rules for the resources to be returned.'
@wsme_pecan.wsexpose([Resource], [Query]) def get_all(self, q=[]):
kwargs = _query_to_kwargs(q, pecan.request.storage_conn.get_resources) resources = [Resource.from_db_and_links(r, self._resource_links(r.resource_id)) for r in pecan.request.storage_conn.get_resources(**kwargs)] return resources
'Create a new alarm.'
@wsme.validate(Alarm) @wsme_pecan.wsexpose(Alarm, body=Alarm, status_code=201) def post(self, data):
conn = pecan.request.storage_conn data.user_id = pecan.request.headers.get('X-User-Id') data.project_id = pecan.request.headers.get('X-Project-Id') data.alarm_id = wsme.Unset data.state_timestamp = wsme.Unset data.timestamp = timeutils.utcnow() alarms = list(conn.get_alarms(name=data.name, p...
'Modify an alarm.'
@wsme.validate(Alarm) @wsme_pecan.wsexpose(Alarm, wtypes.text, body=Alarm) def put(self, alarm_id, data):
conn = pecan.request.storage_conn data.state_timestamp = wsme.Unset data.alarm_id = alarm_id data.user_id = pecan.request.headers.get('X-User-Id') data.project_id = pecan.request.headers.get('X-Project-Id') alarms = list(conn.get_alarms(alarm_id=alarm_id, project=data.project_id)) if (len(al...
'Delete an alarm.'
@wsme_pecan.wsexpose(None, wtypes.text, status_code=204) def delete(self, alarm_id):
conn = pecan.request.storage_conn auth_project = acl.get_limited_to_project(pecan.request.headers) alarms = list(conn.get_alarms(alarm_id=alarm_id, project=auth_project)) if (len(alarms) < 1): raise wsme.exc.ClientSideError(_('Unknown alarm')) conn.delete_alarm(alarm_id)
'Return one alarm.'
@wsme_pecan.wsexpose(Alarm, wtypes.text) def get_one(self, alarm_id):
conn = pecan.request.storage_conn auth_project = acl.get_limited_to_project(pecan.request.headers) alarms = list(conn.get_alarms(alarm_id=alarm_id, project=auth_project)) if (len(alarms) < 1): raise wsme.exc.ClientSideError(_('Unknown alarm')) return Alarm.from_db_model(alarms[0])
'Return all alarms, based on the query provided. :param q: Filter rules for the alarms to be returned.'
@wsme_pecan.wsexpose([Alarm], [Query]) def get_all(self, q=[]):
kwargs = _query_to_kwargs(q, pecan.request.storage_conn.get_alarms) return [Alarm.from_db_model(m) for m in pecan.request.storage_conn.get_alarms(**kwargs)]
'Initializes client.'
def __init__(self, url, token=None):
self.url = url self.token = token
'Returns a list of dicts describing all probes.'
def iter_probes(self):
probes_url = (self.url + '/probes/') headers = {} if (self.token is not None): headers = {'X-Auth-Token': self.token} request = requests.get(probes_url, headers=headers) message = request.json probes = message['probes'] for (key, value) in probes.iteritems(): probe_dict = val...
'Returns a KwapiClient configured with the proper url and token.'
@staticmethod def get_kwapi_client(ksclient):
endpoint = ksclient.service_catalog.url_for(service_type='energy', endpoint_type='internalURL') return KwapiClient(endpoint, ksclient.auth_token)
'Iterate over all probes.'
def iter_probes(self, ksclient):
try: client = self.get_kwapi_client(ksclient) except exceptions.EndpointNotFound: LOG.debug(_('Kwapi endpoint not found')) return [] return client.iter_probes()
'Returns all counters.'
def get_counters(self, manager):
for probe in self.iter_probes(manager.keystone): (yield counter.Counter(name='energy', type=counter.TYPE_CUMULATIVE, unit='kWh', volume=probe['kwh'], user_id=None, project_id=None, resource_id=probe['id'], timestamp=datetime.datetime.fromtimestamp(probe['timestamp']).isoformat(), resource_metadata={})) ...
'Tasks to be run at a periodic interval.'
def poll_and_publish(self):
with self.publish_context as publisher: for pollster in self.pollsters: try: LOG.info('Polling pollster %s', pollster.name) publisher(list(pollster.obj.get_counters(self.manager))) except Exception as err: LOG.warning('Continue ...
'Counter rules checking At least one meaningful counter exist Included type and excluded type counter can\'t co-exist at the same pipeline Included type counter and wildcard can\'t co-exist at same pipeline'
def _check_counters(self):
counters = self.counters if (not counters): raise PipelineException('No counter specified', self.cfg) if ([x for x in counters if (x[0] not in '!*')] and [x for x in counters if (x[0] == '!')]): raise PipelineException('Both included and excluded counters specified', cfg...
'Push counter into pipeline for publishing. param start: the first transformer that the counter will be injected. This is mainly for flush() invocation that transformer may emit counters param ctxt: execution context from the manager or service param counters: counter list param source: counter source'
def _publish_counters(self, start, ctxt, counters, source):
transformed_counters = [] for counter in counters: LOG.audit('Pipeline %s: Transform counter %s from %s transformer', self, counter, start) counter = self._transform_counter(start, ctxt, counter, source) if counter: transformed_counters.append(counter) ...
'Flush data after all counter have been injected to pipeline.'
def flush(self, ctxt, source):
LOG.audit('Flush pipeline %s', self) for (i, transformer) in enumerate(self.transformers): try: self._publish_counters((i + 1), ctxt, list(transformer.flush(ctxt, source)), source) except Exception as err: LOG.warning('Pipeline %s: Error flushing transfo...
'Setup the pipelines according to config. The top of the cfg is a list of pipeline definitions. Pipeline definition is an dictionary specifying the target counters, the tranformers involved, and the target publishers: "name": pipeline_name "interval": interval_time "counters" : ["counter_1", "counter_2"], "tranformers...
def __init__(self, cfg, transformer_manager):
self.pipelines = [Pipeline(pipedef, transformer_manager) for pipedef in cfg]
'Build a new Publisher for these manager pipelines. :param context: The context. :param source: Counter source.'
def publisher(self, context, source):
return PublishContext(context, source, self.pipelines)
'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...
'Serialize something to primitive form. :param context: Security context :param entity: Entity to be serialized :returns: Serialized form of entity'
@abc.abstractmethod def serialize_entity(self, context, entity):
pass
'Deserialize something from primitive form. :param context: Security context :param entity: Primitive to be deserialized :returns: Deserialized form of entity'
@abc.abstractmethod def deserialize_entity(self, context, entity):
pass
'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. :param version_cap: Optionally cap the maximum version used for sent messages. :param serializer: Optionaly (de-)...
def __init__(self, topic, default_version, version_cap=None, serializer=None):
self.topic = topic self.default_version = default_version self.version_cap = version_cap if (serializer is None): serializer = rpc_serializer.NoOpSerializer() self.serializer = serializer 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):
v = (vers if vers else self.default_version) if (self.version_cap and (not rpc_common.version_is_compatible(self.version_cap, v))): raise rpc_common.RpcVersionCapError(version=self.version_cap) msg['version'] = v
'Return the topic to use for a message.'
def _get_topic(self, topic):
return (topic if topic else self.topic)
'Check to see if a version is compatible with the version cap.'
def can_send_version(self, version):
return ((not self.version_cap) or rpc_common.version_is_compatible(self.version_cap, version))
'Helper method called to serialize message arguments. This calls our serializer on each argument, returning a new set of args that have been serialized. :param context: The request context :param kwargs: The arguments to serialize :returns: A new set of serialized arguments'
def _serialize_msg_args(self, context, kwargs):
new_kwargs = dict() for (argname, arg) in kwargs.iteritems(): new_kwargs[argname] = self.serializer.serialize_entity(context, arg) return new_kwargs
'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 version: (Optional) Override the requested API version in this message. :param timeout: (Optional) A timeout to use when waiting for ...
def call(self, context, msg, topic=None, version=None, timeout=None):
self._set_version(msg, version) msg['args'] = self._serialize_msg_args(context, msg['args']) real_topic = self._get_topic(topic) try: result = rpc.call(context, real_topic, msg, timeout) return self.serializer.deserialize_entity(context, result) except rpc.common.Timeout as exc: ...
'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 version: (Optional) Override the requested API version in this message. :param timeout: (Optional) A timeout to use when waiting...
def multicall(self, context, msg, topic=None, version=None, timeout=None):
self._set_version(msg, version) msg['args'] = self._serialize_msg_args(context, msg['args']) real_topic = self._get_topic(topic) try: result = rpc.multicall(context, real_topic, msg, timeout) return self.serializer.deserialize_entity(context, result) except rpc.common.Timeout as exc:...
'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) msg['args'] = self._serialize_msg_args(context, msg['args']) 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) msg['args'] = self._serialize_msg_args(context, msg['args']) 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) msg['args'] = self._serialize_msg_args(context, msg['args']) 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) msg['args'] = self._serialize_msg_args(context, msg['args']) 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()
'Initiates CallbackWrapper object. :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, namespace, args):
ctxt.update_store() try: rval = self.proxy.dispatch(ctxt, version, method, namespace, **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.c...
'Return a result until we get a reply with an \'ending\' flag.'
def __iter__(self):
if self._done: raise StopIteration while True: try: data = self._dataqueue.get(timeout=self._timeout) result = self._process_data(data) except queue.Empty: self.done() raise rpc_common.Timeout() except Exception: with ex...
'Initialize the rpc dispatcher. :param callbacks: List of proxy objects that are an instance of a class with rpc methods exposed. Each proxy object should have an RPC_API_VERSION attribute. :param serializer: The Serializer object that will be used to deserialize arguments before the method call and to serialize the r...
def __init__(self, callbacks, serializer=None):
self.callbacks = callbacks if (serializer is None): serializer = rpc_serializer.NoOpSerializer() self.serializer = serializer super(RpcDispatcher, self).__init__()
'Helper method called to deserialize args before dispatch. This calls our serializer on each argument, returning a new set of args that have been deserialized. :param context: The request context :param kwargs: The arguments to be deserialized :returns: A new set of deserialized args'
def _deserialize_args(self, context, kwargs):
new_kwargs = dict() for (argname, arg) in kwargs.iteritems(): new_kwargs[argname] = self.serializer.deserialize_entity(context, arg) return new_kwargs
'Dispatch a message based on a requested version. :param ctxt: The request context :param version: The requested API version from the incoming message :param method: The method requested to be called by the incoming message. :param namespace: The namespace for the requested method. If None, the dispatcher will look fo...
def dispatch(self, ctxt, version, method, namespace, **kwargs):
if (not version): version = '1.0' had_compatible = False for proxyobj in self.callbacks: try: cb_namespace = proxyobj.RPC_API_NAMESPACE except AttributeError: cb_namespace = None if (namespace != cb_namespace): continue try: ...