desc stringlengths 3 26.7k | decl stringlengths 11 7.89k | bodies stringlengths 8 553k |
|---|---|---|
'Parse dictionary created by routes library.'
| def get_action_args(self, request_environment):
| if hasattr(self.controller, 'get_action_args'):
return self.controller.get_action_args(request_environment)
try:
args = request_environment['wsgiorg.routing_args'][1].copy()
except (KeyError, IndexError, AttributeError):
return {}
try:
del args['controller']
except Ke... |
'WSGI method that controls (de)serialization and method dispatch.'
| @webob.dec.wsgify(RequestClass=Request)
def __call__(self, request):
| LOG.info(('%(method)s %(url)s' % {'method': request.method, 'url': request.url}))
action_args = self.get_action_args(request.environ)
action = action_args.pop('action', None)
(content_type, body) = self.get_body(request)
accept = request.best_match_content_type()
return self._process_stack(re... |
'Implement the processing stack.'
| def _process_stack(self, request, action, action_args, content_type, body, accept):
| try:
(meth, extensions) = self.get_method(request, action, content_type, body)
except (AttributeError, TypeError):
return Fault(webob.exc.HTTPNotFound())
except KeyError as ex:
msg = (_('There is no such action: %s') % ex.args[0])
return Fault(webob.exc.HTTPBad... |
'Look up the action-specific method and its extensions.'
| def get_method(self, request, action, content_type, body):
| try:
if (not self.controller):
meth = getattr(self, action)
else:
meth = getattr(self.controller, action)
except AttributeError:
if ((not self.wsgi_actions) or (action not in ['action', 'create', 'delete'])):
raise
else:
return (meth, self.... |
'Dispatch a call to the action-specific method.'
| def dispatch(self, method, request, action_args):
| return method(req=request, **action_args)
|
'Adds the wsgi_actions dictionary to the class.'
| def __new__(mcs, name, bases, cls_dict):
| actions = {}
extensions = []
for base in bases:
actions.update(getattr(base, 'wsgi_actions', {}))
for (key, value) in cls_dict.items():
if (not callable(value)):
continue
if getattr(value, 'wsgi_action', None):
actions[value.wsgi_action] = key
elif... |
'Initialize controller with a view builder instance.'
| def __init__(self, view_builder=None):
| if view_builder:
self._view_builder = view_builder
elif self._view_builder_class:
self._view_builder = self._view_builder_class()
else:
self._view_builder = None
|
'Create a Fault for the given webob.exc.exception.'
| def __init__(self, exception):
| self.wrapped_exc = exception
self.status_int = exception.status_int
|
'Generate a WSGI response based on the exception passed to ctor.'
| @webob.dec.wsgify(RequestClass=Request)
def __call__(self, req):
| code = self.wrapped_exc.status_int
fault_name = self._fault_names.get(code, 'computeFault')
fault_data = {fault_name: {'code': code, 'message': self.wrapped_exc.explanation}}
if (code == 413):
retry = self.wrapped_exc.headers['Retry-After']
fault_data[fault_name]['retryAfter'] = retry
... |
'Initialize new `OverLimitFault` with relevant information.'
| def __init__(self, message, details, retry_time):
| hdrs = OverLimitFault._retry_after(retry_time)
self.wrapped_exc = webob.exc.HTTPRequestEntityTooLarge(headers=hdrs)
self.content = {'overLimitFault': {'code': self.wrapped_exc.status_int, 'message': message, 'details': details}}
|
'Return the wrapped exception with a serialized body conforming to our
error format.'
| @webob.dec.wsgify(RequestClass=Request)
def __call__(self, request):
| content_type = request.best_match_content_type()
metadata = {'attributes': {'overLimitFault': 'code'}}
xml_serializer = XMLDictSerializer(metadata, XMLNS_V1)
serializer = {'application/xml': xml_serializer, 'application/json': JSONDictSerializer()}[content_type]
content = serializer.serialize(self.c... |
'Returns the list of servicemanage types.'
| @wsgi.serializers(xml=ServiceManageTypesTemplate)
def index(self, req):
| context = req.environ['monitor.context']
vol_types = servicemanage_types.get_all_types(context).values()
return self._view_builder.index(req, vol_types)
|
'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 []
|
'Marshal the conductor attribute of a parsed request.'
| def _extract_conductor(self, node):
| conductor = {}
conductor_node = self.find_first_child_named(node, 'conductor')
attributes = ['display_name', 'display_description', 'size', 'conductor_type', 'availability_zone']
for attr in attributes:
if conductor_node.getAttribute(attr):
conductor[attr] = conductor_node.getAttribu... |
'Deserialize an xml-formatted conductor create request.'
| def default(self, string):
| dom = utils.safe_minidom_parse_string(string)
conductor = self._extract_conductor(dom)
return {'body': {'conductor': conductor}}
|
'Return data about the given conductor.'
| @wsgi.serializers(xml=ConductorTemplate)
def show(self, req, id):
| context = req.environ['monitor.context']
try:
vol = self.conductor_api.get(context, id)
except exception.NotFound:
raise exc.HTTPNotFound()
return {'conductor': _translate_conductor_detail_view(context, vol)}
|
'Delete a conductor.'
| def delete(self, req, id):
| context = req.environ['monitor.context']
LOG.audit(_('Delete conductor with id: %s'), id, context=context)
try:
conductor_item = self.conductor_api.get(context, id)
self.conductor_api.delete(context, conductor_item)
except exception.NotFound:
raise exc.HTTPNotFound()
... |
'Returns a detailed list of conductors.'
| @wsgi.serializers(xml=ConductorsTemplate)
def test_service(self, req):
| search_opts = {}
search_opts.update(req.GET)
context = req.environ['monitor.context']
remove_invalid_options(context, search_opts, self._get_conductor_search_options())
res = self.conductor_api.test_service(context)
return {'test': res}
|
'Returns a summary list of conductors.'
| @wsgi.serializers(xml=ConductorsTemplate)
def index(self, req):
| LOG.debug('JIYOU comes to index')
return self._items(req, entity_maker=_translate_conductor_summary_view)
|
'Returns a detailed list of conductors.'
| @wsgi.serializers(xml=ConductorsTemplate)
def detail(self, req):
| LOG.debug('JIYOU comes to detail')
return self._items(req, entity_maker=_translate_conductor_detail_view)
|
'Returns a list of conductors, transformed through entity_maker.'
| def _items(self, req, entity_maker):
| search_opts = {}
search_opts.update(req.GET)
context = req.environ['monitor.context']
remove_invalid_options(context, search_opts, self._get_conductor_search_options())
res = self.conductor_api.test_service(context)
return {'test': res}
|
'Return conductor search options allowed by non-admin.'
| def _get_conductor_search_options(self):
| return ('display_name', 'status')
|
'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... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.