def delete(self, _id): context = t_context.extract_context_from_environ() # TODO(joehuang): get the release of top and bottom t_release = cons.R_MITAKA b_release = cons.R_MITAKA s_ctx = hclient.get_res_routing_ref(context, _id, request.url, cons.ST_CINDER) if not s_ctx: return utils.format_cinder_error( 404, _('Volume %s could not be found.') % _id) if s_ctx['b_url'] == '': return utils.format_cinder_error( 404, _('Bottom Pod endpoint incorrect')) b_headers = hclient.convert_header(t_release, b_release, request.headers) resp = hclient.forward_req(context, 'DELETE', b_headers, s_ctx['b_url'], request.body) response.status = resp.status_code # don't remove the resource routing for delete is async. operation # remove the routing when query is executed but not find # No content in the resp actually return response
def delete(self, _id): context = t_context.extract_context_from_environ() if not t_context.is_admin_context(context): pecan.abort(400, _('Admin role required to delete pods')) return try: with context.session.begin(): pod = core.get_resource(context, models.Pod, _id) if pod is not None: ag_name = utils.get_ag_name(pod['pod_name']) ag = az_ag.get_ag_by_name(context, ag_name) if ag is not None: az_ag.delete_ag(context, ag['id']) core.delete_resource(context, models.Pod, _id) pecan.response.status = 200 except t_exc.ResourceNotFound: return Response(_('Pod not found'), 404) except Exception as e: LOG.exception( _LE('Failed to delete pod: %(pod_id)s,' '%(exception)s'), { 'pod_id': _id, 'exception': e }) return Response(_('Failed to delete pod'), 500)
def delete(self, _id): context = t_context.extract_context_from_environ() if not policy.enforce(context, policy.ADMIN_API_PODS_DELETE): pecan.abort(401, _('Unauthorized to delete dcs')) return try: with context.session.begin(): region_object = core.get_resource_object(context, models.DC, _id) if len(region_object.fabrics) >0: raise t_exceptions.InUse("Specified dc has fabric(s)") if len(region_object.core_routers) >0: raise t_exceptions.InUse("Specified dc has core_router(s)") core.delete_resource(context, models.DC, _id) pecan.response.status = 200 return {} except t_exceptions.InUse: return Response(_('Specified region has dcs/core_routers'), 400) except t_exceptions.ResourceNotFound: return Response(_('DC not found'), 404) except Exception as e: LOG.exception('Failed to delete dc: %(dc_id)s,' '%(exception)s', {'dc_id': _id, 'exception': e}) return Response(_('Failed to delete dc'), 500)
def delete(self, _id): context = t_context.extract_context_from_environ() if not policy.enforce(context, policy.ADMIN_API_PODS_DELETE): pecan.abort(401, _('Unauthorized to delete pods')) return try: with context.session.begin(): pod = core.get_resource(context, models.Pod, _id) if pod is not None: ag_name = utils.get_ag_name(pod['pod_name']) ag = az_ag.get_ag_by_name(context, ag_name) if ag is not None: az_ag.delete_ag(context, ag['id']) core.delete_resource(context, models.Pod, _id) pecan.response.status = 200 return {} except t_exc.ResourceNotFound: return Response(_('Pod not found'), 404) except Exception as e: LOG.exception(_LE('Failed to delete pod: %(pod_id)s,' '%(exception)s'), {'pod_id': _id, 'exception': e}) return Response(_('Failed to delete pod'), 500)
def delete(self, _id): """Marks volume types as deleted. :param _id: id of volume type to be deleted """ context = t_context.extract_context_from_environ() if not context.is_admin: return utils.format_cinder_error( 403, _("Policy doesn't allow volume_extension:types_manage " "to be performed.")) session = core.get_session() with session.begin(): try: db_api.volume_type_get(context, _id, session) except exceptions.VolumeTypeNotFound as e: return utils.format_cinder_error(404, e.message) try: db_api.volume_type_delete(context, _id, session) except Exception as e: LOG.exception( _LE('Fail to update volume type: %(id)s,' '%(exception)s'), { 'id': _id, 'exception': e }) return utils.format_cinder_error( 500, _('Fail to delete volume type.')) pecan.response.status = 202 return pecan.response
def check_string_length(value, name=None, min_len=0, max_len=None): """Check the length of specified string :param value: the value of the string :param name: the name of the string :param min_len: the minimum length of the string :param max_len: the maximum length of the string """ if not isinstance(value, six.string_types): if name is None: msg = _("The input is not a string or unicode") else: msg = _("%s is not a string or unicode") % name raise t_exceptions.InvalidInput(message=msg) if name is None: name = value if len(value) < min_len: msg = _("%(name)s has a minimum character requirement of " "%(min_length)s.") % {'name': name, 'min_length': min_len} raise t_exceptions.InvalidInput(message=msg) if max_len and len(value) > max_len: msg = _("%(name)s has more than %(max_length)s " "characters.") % {'name': name, 'max_length': max_len} raise t_exceptions.InvalidInput(message=msg)
def delete(self, _id): context = t_context.extract_context_from_environ() # TODO(joehuang): get the release of top and bottom t_release = cons.R_MITAKA b_release = cons.R_MITAKA s_ctx = self._get_res_routing_ref(context, _id, request.url) if not s_ctx: return Response(_('Failed to find resource'), 404) if s_ctx['b_url'] == '': return Response(_('bottom pod endpoint incorrect'), 404) b_headers = self._convert_header(t_release, b_release, request.headers) resp = hclient.forward_req(context, 'DELETE', b_headers, s_ctx['b_url'], request.body) response.status = resp.status_code # don't remove the resource routing for delete is async. operation # remove the routing when query is executed but not find # No content in the resp actually return response
def _check_metadata_properties_quota(self, context, metadata=None): """Enforce quota limits on metadata properties.""" if not metadata: metadata = {} if not isinstance(metadata, dict): msg = (_("Metadata type should be dict.")) raise t_exceptions.InvalidMetadata(reason=msg) num_metadata = len(metadata) try: QUOTAS.limit_check(context, metadata_items=num_metadata) except t_exceptions.OverQuota as exc: quota_metadata = exc.kwargs['quotas']['metadata_items'] raise t_exceptions.MetadataLimitExceeded(allowed=quota_metadata) # Because metadata is processed in the bottom pod, we just do # parameter validation here to ensure quota management for k, v in six.iteritems(metadata): try: utils.check_string_length(v) utils.check_string_length(k, min_len=1) except t_exceptions.InvalidInput as e: raise t_exceptions.InvalidMetadata(reason=str(e)) if len(k) > MAX_METADATA_KEY_LENGTH: msg = _("Metadata property key greater than 255 characters") raise t_exceptions.InvalidMetadataSize(reason=msg) if len(v) > MAX_METADATA_VALUE_LENGTH: msg = _("Metadata property value greater than 255 characters") raise t_exceptions.InvalidMetadataSize(reason=msg)
def check_string_length(value, name=None, min_len=0, max_len=None): """Check the length of specified string :param value: the value of the string :param name: the name of the string :param min_len: the minimum length of the string :param max_len: the maximum length of the string """ if not isinstance(value, six.string_types): if name is None: msg = _("The input is not a string or unicode") else: msg = _("%s is not a string or unicode") % name raise t_exceptions.InvalidInput(message=msg) if name is None: name = value if len(value) < min_len: msg = _("%(name)s has a minimum character requirement of " "%(min_length)s.") % { 'name': name, 'min_length': min_len } raise t_exceptions.InvalidInput(message=msg) if max_len and len(value) > max_len: msg = _("%(name)s has more than %(max_length)s " "characters.") % { 'name': name, 'max_length': max_len } raise t_exceptions.InvalidInput(message=msg)
def post(self, **kw): context = t_context.extract_context_from_environ() if 'region' not in kw: pecan.abort(400, _('Request body region not found')) return print 'MaXiao kw '+str(request.context['request_data']) region = request.context['request_data']['region'] region_name = region.get('region_name', '').strip() _uuid = uuidutils.generate_uuid() try: with context.session.begin(): new_region = core.create_resource( context, models.Region, {'id': _uuid, 'region_name': region_name}) except db_exc.DBDuplicateEntry as e1: LOG.exception('Record already exists on %(region_name)s: ' '%(exception)s', {'region_name': region_name, 'exception': e1}) return Response(_('Record already exists'), 409) except Exception as e2: LOG.exception('Failed to create region: %(region_name)s,' '%(exception)s ', {'region_name': region_name, 'exception': e2}) return Response(_('Failed to create region'), 500) return {'region': new_region}
def delete(self, _id): context = t_context.extract_context_from_environ() # TODO(joehuang): get the release of top and bottom t_release = 'MITATA' b_release = 'MITATA' s_ctx = self._get_res_routing_ref(context, _id, request.url) if not s_ctx: return Response(_('Failed to find resource'), 404) if s_ctx['b_url'] == '': return Response(_('bottom pod endpoint incorrect'), 404) b_headers = self._convert_header(t_release, b_release, request.headers) resp = hclient.forward_req(context, 'DELETE', b_headers, s_ctx['b_url'], request.body) response.status = resp.status_code # don't remove the resource routing for delete is async. operation # remove the routing when query is executed but not find # No content in the resp actually return {}
def get_all(self, **kwargs): """Get all the jobs. Using filters, only get a subset of jobs. :param kwargs: job filters :return: a list of jobs """ context = t_context.extract_context_from_environ() if not policy.enforce(context, policy.ADMIN_API_JOB_LIST): return utils.format_api_error( 403, _('Unauthorized to show all jobs')) is_valid_filter, filters = self._get_filters(kwargs) if not is_valid_filter: msg = (_('Unsupported filter type: %(filters)s') % { 'filters': ', '.join([filter_name for filter_name in filters]) }) return utils.format_api_error(400, msg) filters = [{'key': key, 'comparator': 'eq', 'value': value} for key, value in six.iteritems(filters)] try: jobs_in_job_table = db_api.list_jobs(context, filters) jobs_in_job_log_table = db_api.list_jobs_from_log(context, filters) jobs = jobs_in_job_table + jobs_in_job_log_table return {'jobs': [self._get_more_readable_job(job) for job in jobs]} except Exception as e: LOG.exception('Failed to show all asynchronous jobs: ' '%(exception)s ', {'exception': e}) return utils.format_api_error( 500, _('Failed to show all asynchronous jobs'))
def post(self, **kw): context = t_context.extract_context_from_environ() if not context.is_admin: return utils.format_nova_error( 403, _("Policy doesn't allow os_compute_api:os-aggregates:" "index to be performed.")) if 'aggregate' not in kw: return utils.format_nova_error( 400, _('aggregate is not set')) host_aggregate = kw['aggregate'] name = host_aggregate['name'].strip() avail_zone = host_aggregate.get('availability_zone') if avail_zone: avail_zone = avail_zone.strip() try: with context.session.begin(): aggregate = az_ag.create_ag_az(context, ag_name=name, az_name=avail_zone) except db_exc.DBDuplicateEntry: return utils.format_nova_error( 409, _('Aggregate %s already exists.') % name) except Exception: return utils.format_nova_error( 500, _('Fail to create aggregate')) return {'aggregate': aggregate}
def delete(self, _id): context = t_context.extract_context_from_environ() if not policy.enforce(context, policy.ADMIN_API_PODS_DELETE): pecan.abort(401, _('Unauthorized to delete regions')) return try: with context.session.begin(): print "MaXiao 111 delete region has dcs " region_object = core.get_resource_object(context, models.Region, _id) print "MaXiao delete region has dcs :"+str(region_result) if len(region_object.dcs)>0: raise t_exceptions.InUse("Specified region has dc(s)") core.delete_resource(context, models.Region, _id) pecan.response.status = 200 return {} except t_exceptions.InUse: return Response(_('Specified region has dcs'), 400) except t_exceptions.ResourceNotFound: return Response(_('Region not found'), 404) except Exception as e: LOG.exception('Failed to delete region: %(region_id)s,' '%(exception)s', {'region_id': _id, 'exception': e}) return Response(_('Failed to delete region'), 500)
def post(self, **kw): context = t_context.extract_context_from_environ() if not t_context.is_admin_context(context): pecan.abort(400, _('Admin role required to create bindings')) return if 'pod_binding' not in kw: pecan.abort(400, _('Request body not found')) return pod_b = kw['pod_binding'] tenant_id = pod_b.get('tenant_id', '').strip() pod_id = pod_b.get('pod_id', '').strip() _uuid = uuidutils.generate_uuid() if tenant_id == '' or pod_id == '': return Response(_('Tenant_id and pod_id can not be empty'), 422) # the az_pod_map_id should be exist for in the pod map table try: with context.session.begin(): pod = core.get_resource(context, models.Pod, pod_id) if pod.get('az_name') == '': return Response(_('Top region can not be bound'), 422) except t_exc.ResourceNotFound: return Response(_('pod_id not found in pod'), 422) except Exception as e: LOG.exception( _LE('Failed to get_resource for pod_id: ' '%(pod_id)s ,' '%(exception)s '), { 'pod_id': pod_id, 'exception': e }) pecan.abort(500, _('Failed to create pod binding')) return try: with context.session.begin(): pod_binding = core.create_resource(context, models.PodBinding, { 'id': _uuid, 'tenant_id': tenant_id, 'pod_id': pod_id }) except db_exc.DBDuplicateEntry: return Response(_('Pod binding already exists'), 409) except db_exc.DBConstraintError: return Response(_('pod_id not exists in pod'), 422) except db_exc.DBReferenceError: return Response(_('DB reference not exists in pod'), 422) except Exception as e: LOG.exception(_LE('Failed to create pod binding: %(exception)s '), {'exception': e}) pecan.abort(500, _('Failed to create pod binding')) return return {'pod_binding': pod_binding}
def get_one(self, _id): context = t_context.extract_context_from_environ() if _id == 'detail': return {'volumes': self._get_all(context)} # TODO(joehuang): get the release of top and bottom t_release = cons.R_MITAKA b_release = cons.R_MITAKA b_headers = hclient.convert_header(t_release, b_release, request.headers) s_ctx = hclient.get_res_routing_ref(context, _id, request.url, cons.ST_CINDER) if not s_ctx: return utils.format_cinder_error( 404, _('Volume %s could not be found.') % _id) if s_ctx['b_url'] == '': return utils.format_cinder_error( 404, _('Bottom Pod endpoint incorrect')) resp = hclient.forward_req(context, 'GET', b_headers, s_ctx['b_url'], request.body) b_ret_body = jsonutils.loads(resp.content) b_status = resp.status_code response.status = b_status if b_status == 200: if b_ret_body.get('volume') is not None: b_vol_ret = b_ret_body['volume'] ret_vol = hclient.convert_object(b_release, t_release, b_vol_ret, res_type=cons.RT_VOLUME) pod = utils.get_pod_by_top_id(context, _id) if pod: ret_vol['availability_zone'] = pod['az_name'] return {'volume': ret_vol} # resource not find but routing exist, remove the routing if b_status == 404: filters = [{ 'key': 'top_id', 'comparator': 'eq', 'value': _id }, { 'key': 'resource_type', 'comparator': 'eq', 'value': cons.RT_VOLUME }] with context.session.begin(): core.delete_resources(context, models.ResourceRouting, filters) return b_ret_body
def post(self, **kw): context = t_context.extract_context_from_environ() if not t_context.is_admin_context(context): pecan.abort(400, _('Admin role required to create bindings')) return if 'pod_binding' not in kw: pecan.abort(400, _('Request body not found')) return pod_b = kw['pod_binding'] tenant_id = pod_b.get('tenant_id', '').strip() pod_id = pod_b.get('pod_id', '').strip() _uuid = uuidutils.generate_uuid() if tenant_id == '' or pod_id == '': return Response( _('Tenant_id and pod_id can not be empty'), 422) # the az_pod_map_id should be exist for in the pod map table try: with context.session.begin(): pod = core.get_resource(context, models.Pod, pod_id) if pod.get('az_name') == '': return Response(_('Top region can not be bound'), 422) except t_exc.ResourceNotFound: return Response(_('pod_id not found in pod'), 422) except Exception as e: LOG.error(_LE('Fail to create pod binding: %(exception)s'), {'exception': e}) pecan.abort(500, _('Fail to create pod binding')) return try: with context.session.begin(): pod_binding = core.create_resource(context, models.PodBinding, {'id': _uuid, 'tenant_id': tenant_id, 'pod_id': pod_id}) except db_exc.DBDuplicateEntry: return Response(_('Pod binding already exists'), 409) except db_exc.DBConstraintError: return Response(_('pod_id not exists in pod'), 422) except db_exc.DBReferenceError: return Response(_('DB reference not exists in pod'), 422) except Exception as e: LOG.error(_LE('Fail to create pod binding: %(exception)s'), {'exception': e}) pecan.abort(500, _('Fail to create pod binding')) return return {'pod_binding': pod_binding}
def get_one(self, _id): context = t_context.extract_context_from_environ() if not policy.enforce(context, policy.ADMIN_API_ROUTINGS_SHOW): return utils.format_api_error( 403, _('Unauthorized to show the resource routing')) try: return {'routing': db_api.get_resource_routing(context, _id)} except t_exc.ResourceNotFound: return utils.format_api_error(404, _('Resource routing not found'))
def get_one(self, _id): context = t_context.extract_context_from_environ() if _id == 'detail': return {'volumes': self._get_all(context)} # TODO(joehuang): get the release of top and bottom t_release = 'MITATA' b_release = 'MITATA' b_headers = self._convert_header(t_release, b_release, request.headers) s_ctx = self._get_res_routing_ref(context, _id, request.url) if not s_ctx: return Response(_('Failed to find resource'), 404) if s_ctx['b_url'] == '': return Response(_('bottom pod endpoint incorrect'), 404) resp = hclient.forward_req(context, 'GET', b_headers, s_ctx['b_url'], request.body) b_ret_body = jsonutils.loads(resp.content) b_status = resp.status_code response.status = b_status if b_status == 200: if b_ret_body.get('volume') is not None: b_vol_ret = b_ret_body['volume'] ret_vol = self._convert_object(b_release, t_release, b_vol_ret, res_type=cons.RT_VOLUME) pod = self._get_pod_by_top_id(context, _id) if pod: ret_vol['availability_zone'] = pod['az_name'] return {'volume': ret_vol} # resource not find but routing exist, remove the routing if b_status == 404: filters = [{'key': 'top_id', 'comparator': 'eq', 'value': _id}, {'key': 'resource_type', 'comparator': 'eq', 'value': cons.RT_VOLUME}] with context.session.begin(): core.delete_resources(context, models.ResourceRouting, filters) return b_ret_body
def post(self, **kw): context = t_context.extract_context_from_environ() if not policy.enforce(context, policy.ADMIN_API_BINDINGS_CREATE): pecan.abort(401, _('Unauthorized to create bindings')) return if 'pod_binding' not in kw: pecan.abort(400, _('Request body not found')) return pod_b = kw['pod_binding'] tenant_id = pod_b.get('tenant_id', '').strip() pod_id = pod_b.get('pod_id', '').strip() if tenant_id == '' or pod_id == '': return Response( _('Tenant_id and pod_id can not be empty'), 422) # the az_pod_map_id should be exist for in the pod map table try: with context.session.begin(): pod = core.get_resource(context, models.Pod, pod_id) if pod.get('az_name') == '': return Response(_('Top region can not be bound'), 422) except t_exc.ResourceNotFound: return Response(_('pod_id not found in pod'), 422) except Exception as e: LOG.exception(_LE('Failed to get_resource for pod_id: ' '%(pod_id)s ,' '%(exception)s '), {'pod_id': pod_id, 'exception': e}) pecan.abort(500, _('Failed to create pod binding')) return try: pod_binding = db_api.create_pod_binding( context, tenant_id, pod_id) except db_exc.DBDuplicateEntry: return Response(_('Pod binding already exists'), 409) except db_exc.DBConstraintError: return Response(_('pod_id not exists in pod'), 422) except db_exc.DBReferenceError: return Response(_('DB reference not exists in pod'), 422) except Exception as e: LOG.exception(_LE('Failed to create pod binding: %(exception)s '), {'exception': e}) pecan.abort(500, _('Failed to create pod binding')) return return {'pod_binding': pod_binding}
def get_one(self, _id): context = t_context.extract_context_from_environ() if not policy.enforce(context, policy.ADMIN_API_PODS_SHOW): pecan.abort(401, _('Unauthorized to show tricircle resource')) return try: return {'tricircle_resource': db_api.get_tricircle_resource(context, _id)} except t_exceptions.ResourceNotFound: pecan.abort(404, _('Tricircle resource not found')) return
def get_one(self, _id): context = t_context.extract_context_from_environ() if not policy.enforce(context, policy.ADMIN_API_ROUTINGS_SHOW): return utils.format_api_error( 403, _('Unauthorized to show the resource routing')) try: return {'routing': db_api.get_resource_routing(context, _id)} except t_exc.ResourceNotFound: return utils.format_api_error( 404, _('Resource routing not found'))
def delete(self, _id): context = t_context.extract_context_from_environ() try: with context.session.begin(): az_ag.delete_ag(context, _id) pecan.response.status = 200 except t_exc.ResourceNotFound: return utils.format_nova_error( 404, _('Aggregate %s could not be found.') % _id) except Exception: return utils.format_nova_error( 500, _('Fail to delete aggregate %s') % _id)
def get_one(self, _id): context = t_context.extract_context_from_environ() try: with context.session.begin(): aggregate = az_ag.get_one_ag(context, _id) return {'aggregate': aggregate} except t_exc.ResourceNotFound: return utils.format_nova_error( 404, _('Aggregate %s could not be found.') % _id) except Exception: return utils.format_nova_error( 500, _('Fail to get aggregate %s') % _id)
def get_one(self, _id): context = t_context.extract_context_from_environ() if not policy.enforce(context, policy.ADMIN_API_PODS_SHOW): pecan.abort(401, _('Unauthorized to show pods')) return try: return {'pod': db_api.get_pod(context, _id)} except t_exc.ResourceNotFound: pecan.abort(404, _('Pod not found')) return
def get_one(self, _id): context = t_context.extract_context_from_environ() if not t_context.is_admin_context(context): pecan.abort(400, _('Admin role required to show pods')) return try: return {'pod': db_api.get_pod(context, _id)} except t_exc.ResourceNotFound: pecan.abort(404, _('Pod not found')) return
def get_one(self, _id): context = t_context.extract_context_from_environ() if not policy.enforce(context, policy.ADMIN_API_PODS_SHOW): pecan.abort(401, _('Unauthorized to show core routers')) return try: return {'dynamic_peering_connection': db_api.get_dynamic_peering_connection(context, _id)} except t_exceptions.ResourceNotFound: pecan.abort(404, _('Dynamic Peering Connection not found')) return
def delete(self, _id): context = t_context.extract_context_from_environ() if not t_context.is_admin_context(context): pecan.abort(400, _('Admin role required to delete bindings')) return try: with context.session.begin(): core.delete_resource(context, models.PodBinding, _id) pecan.response.status = 200 except t_exc.ResourceNotFound: pecan.abort(404, _('Pod binding not found')) return
def put(self, _id, **kw): context = t_context.extract_context_from_environ() if not policy.enforce(context, policy.ADMIN_API_ROUTINGS_PUT): return utils.format_api_error( 403, _('Unauthorized to update resource routing')) try: db_api.get_resource_routing(context, _id) except t_exceptions.ResourceNotFound: return utils.format_api_error(404, _('Resource routing not found')) if 'routing' not in kw: return utils.format_api_error(400, _('Request body not found')) update_dict = kw['routing'] # values to be updated should not be empty for field in update_dict: value = update_dict.get(field) if value is None or len(value.strip()) == 0: return utils.format_api_error( 400, _("Field %(field)s can not be empty") % {'field': field}) # the resource type should be properly provisioned. if 'resource_type' in update_dict: if not constants.is_valid_resource_type( update_dict['resource_type']): return utils.format_api_error( 400, _('There is no such resource type')) # the pod with new pod_id should exist in pod table if 'pod_id' in update_dict: new_pod_id = update_dict.get('pod_id') try: # find the pod through the pod_id and verify whether it exists db_api.get_pod(context, new_pod_id) except t_exceptions.ResourceNotFound: return utils.format_api_error( 400, _("The pod %(new_pod_id)s doesn't" " exist") % {'new_pod_id': new_pod_id}) except Exception as e: LOG.exception( 'Failed to update resource routing: ' '%(exception)s ', {'exception': e}) return utils.format_api_error( 500, _('Failed to update resource routing')) try: routing_updated = db_api.update_resource_routing( context, _id, update_dict) return {'routing': routing_updated} except Exception as e: LOG.exception( 'Failed to update resource routing: ' '%(exception)s ', {'exception': e}) return utils.format_api_error( 500, _('Failed to update resource routing'))
def get_all(self): context = t_context.extract_context_from_environ() if not t_context.is_admin_context(context): pecan.abort(400, _('Admin role required to list pods')) return try: return {'pods': db_api.list_pods(context)} except Exception as e: LOG.error(_LE('Fail to list pod: %(exception)s'), {'exception': e}) pecan.abort(500, _('Fail to list pod')) return
def put(self, _id, **kw): context = t_context.extract_context_from_environ() if not policy.enforce(context, policy.ADMIN_API_ROUTINGS_PUT): return utils.format_api_error( 403, _('Unauthorized to update resource routing')) try: db_api.get_resource_routing(context, _id) except t_exceptions.ResourceNotFound: return utils.format_api_error(404, _('Resource routing not found')) if 'routing' not in kw: return utils.format_api_error( 400, _('Request body not found')) update_dict = kw['routing'] # values to be updated should not be empty for field in update_dict: value = update_dict.get(field) if value is None or len(value.strip()) == 0: return utils.format_api_error( 400, _("Field %(field)s can not be empty") % { 'field': field}) # the resource type should be properly provisioned. if 'resource_type' in update_dict: if not constants.is_valid_resource_type( update_dict['resource_type']): return utils.format_api_error( 400, _('There is no such resource type')) # the pod with new pod_id should exist in pod table if 'pod_id' in update_dict: new_pod_id = update_dict.get('pod_id') try: # find the pod through the pod_id and verify whether it exists db_api.get_pod(context, new_pod_id) except t_exceptions.ResourceNotFound: return utils.format_api_error( 400, _("The pod %(new_pod_id)s doesn't" " exist") % {'new_pod_id': new_pod_id}) except Exception as e: LOG.exception('Failed to update resource routing: ' '%(exception)s ', {'exception': e}) return utils.format_api_error( 500, _('Failed to update resource routing')) try: routing_updated = db_api.update_resource_routing( context, _id, update_dict) return {'routing': routing_updated} except Exception as e: LOG.exception('Failed to update resource routing: ' '%(exception)s ', {'exception': e}) return utils.format_api_error( 500, _('Failed to update resource routing'))
def __init__(self, message=None, **kwargs): self.kwargs = kwargs self.kwargs['message'] = message if 'code' not in self.kwargs: self.kwargs['code'] = self.code for k, v in self.kwargs.items(): if isinstance(v, Exception): self.kwargs[k] = six.text_type(v) if self._should_format(): try: message = self.message % kwargs except Exception: # kwargs doesn't match a variable in the message # log the issue and the kwargs exc_info = _('Exception class %s in string ' 'format operation') % type(self).__name__ format_str = _('%(exception_info)s ; %(format_key)s : ' '%(format_value)s') for name, value in kwargs.items(): exc_info = format_str % { 'exception_info': exc_info, 'format_key': name, 'format_value': six.text_type(value) } exc_info = _('%(message)s ; %(exception_info)s') % { 'message': self.message, 'exception_info': exc_info } LOG.exception(exc_info) # no rerasie # exc_info = sys.exc_info() # if CONF.fatal_exception_format_errors: # six.reraise(*exc_info) # at least get the core message out if something happened message = self.message elif isinstance(message, Exception): message = six.text_type(message) self.msg = message super(TricircleException, self).__init__(message)
def post(self, **kw): context = t_context.extract_context_from_environ() if not policy.enforce(context, policy.ADMIN_API_PODS_CREATE): pecan.abort(401, _('Unauthorized to create tricircle resource')) return if 'tricircle_resource' not in kw: pecan.abort(400, _('Request body tricircle_resource not found')) return tricircle_resource = request.context['request_data']['tricircle_resource'] tricircle_resource_id= tricircle_resource.get('id', '').strip() tricircle_resource_name = tricircle_resource.get('name', '').strip() region_name= tricircle_resource.get('region_name', '').strip() project_id= tricircle_resource.get('project_id', '').strip() resource_type= tricircle_resource.get('resource_type', '').strip() admin_state_up = tricircle_resource.get('admin_state_up',True) status = tricircle_resource.get('status',"DOWN") try: with context.session.begin(): new_tricircle_resource= core.create_resource( context, models.TricircleResource, {'id': tricircle_resource_id, 'name':tricircle_resource_name, 'region_name':region_name, 'resource_type':resource_type, 'project_id': project_id, 'admin_state_up':admin_state_up, 'status':status}) except db_exc.DBDuplicateEntry as e1: LOG.exception('Record already exists on' 'tricircle_resource_id%(tricircle_resource_id)s: ' '%(exception)s', {'tricircle_resource_id':tricircle_resource_id, 'exception': e1}) return Response(_('Record already exists'), 409) except Exception as e2: LOG.exception('Failed to create tricircle_resource :' 'tricircle_resource_id: %(tricircle_resource_id)s,' '%(exception)s ', {'tricircle_resource_id': tricircle_resource_id, 'exception': e2}) return Response(_('Failed to create tricircle_resource'), 500) return {'tricircle_resource': new_tricircle_resource}
def delete(self, _id): context = t_context.extract_context_from_environ() if not policy.enforce(context, policy.ADMIN_API_BINDINGS_DELETE): pecan.abort(401, _('Unauthorized to delete bindings')) return try: with context.session.begin(): core.delete_resource(context, models.PodBinding, _id) pecan.response.status = 200 return {} except t_exc.ResourceNotFound: pecan.abort(404, _('Pod binding not found')) return
def get_one(self, _id): context = t_context.extract_context_from_environ() if not t_context.is_admin_context(context): pecan.abort(400, _('Admin role required to show bindings')) return try: with context.session.begin(): pod_binding = core.get_resource(context, models.PodBinding, _id) return {'pod_binding': pod_binding} except t_exc.ResourceNotFound: pecan.abort(404, _('Tenant pod binding not found')) return
def get_all(self): context = t_context.extract_context_from_environ() if not t_context.is_admin_context(context): pecan.abort(400, _('Admin role required to list pods')) return try: return {'pods': db_api.list_pods(context)} except Exception as e: LOG.exception(_LE('Failed to list all pods: %(exception)s '), {'exception': e}) pecan.abort(500, _('Failed to list pods')) return
def get_all(self): context = t_context.extract_context_from_environ() if not policy.enforce(context, policy.ADMIN_API_PODS_LIST): pecan.abort(401, _('Unauthorized to list dynamic peering connection')) return try: return {'dynamic_peering_connections': db_api.list_dynamic_peering_connections(context)} except Exception as e: LOG.exception('Failed to list all dynamic_peering_connections: %(exception)s ', {'exception': e}) pecan.abort(500, _('Failed to list dynamic_peering_connections')) return
def get_all(self): context = t_context.extract_context_from_environ() if not policy.enforce(context, policy.ADMIN_API_PODS_LIST): pecan.abort(401, _('Unauthorized to list tricircle_resources')) return try: return {'tricircle_resources': db_api.list_tricircle_resources(context)} except Exception as e: LOG.exception('Failed to list all tricircle_resources: %(exception)s ', {'exception': e}) pecan.abort(500, _('Failed to list tricircle_resources')) return
def get_all(self): context = t_context.extract_context_from_environ() if not policy.enforce(context, policy.ADMIN_API_PODS_LIST): pecan.abort(401, _('Unauthorized to list pods')) return try: return {'pods': db_api.list_pods(context)} except Exception as e: LOG.exception(_LE('Failed to list all pods: %(exception)s '), {'exception': e}) pecan.abort(500, _('Failed to list pods')) return
def bool_from_string(subject, strict=False, default=False): """Interpret a string as a boolean. A case-insensitive match is performed such that strings matching 't', 'true', 'on', 'y', 'yes', or '1' are considered True and, when `strict=False`, anything else returns the value specified by 'default'. Useful for JSON-decoded stuff and config file parsing. If `strict=True`, unrecognized values, including None, will raise a ValueError which is useful when parsing values passed in from an API call. Strings yielding False are 'f', 'false', 'off', 'n', 'no', or '0'. """ if not isinstance(subject, six.string_types): subject = six.text_type(subject) lowered = subject.strip().lower() if lowered in TRUE_STRINGS: return True elif lowered in FALSE_STRINGS: return False elif strict: acceptable = ', '.join( "'%s'" % s for s in sorted(TRUE_STRINGS + FALSE_STRINGS)) msg = _("Unrecognized value '%(val)s', acceptable values are:" " %(acceptable)s") % {'val': subject, 'acceptable': acceptable} raise ValueError(msg) else: return default
def load_paste_app(app_name): """Builds and returns a WSGI app from a paste config file. :param app_name: Name of the application to load :raises ConfigFilesNotFoundError when config file cannot be located :raises RuntimeError when application cannot be loaded from config file """ config_path = cfg.CONF.find_file(cfg.CONF.api_paste_config) if not config_path: raise cfg.ConfigFilesNotFoundError( config_files=[cfg.CONF.api_paste_config]) config_path = os.path.abspath(config_path) LOG.info(_LI("Config paste file: %s"), config_path) try: app = deploy.loadapp("config:%s" % config_path, name=app_name) except (LookupError, ImportError): msg = (_("Unable to load %(app_name)s from " "configuration file %(config_path)s.") % {'app_name': app_name, 'config_path': config_path}) LOG.exception(msg) raise RuntimeError(msg) return app
def serve(xservice, workers=1): global _launcher if _launcher: raise RuntimeError(_('serve() can only be called once')) _launcher = srv.ProcessLauncher(CONF, restart_method='mutate') _launcher.launch_service(xservice, workers=workers)
def bool_from_string(subject, strict=False, default=False): """Interpret a string as a boolean. A case-insensitive match is performed such that strings matching 't', 'true', 'on', 'y', 'yes', or '1' are considered True and, when `strict=False`, anything else returns the value specified by 'default'. Useful for JSON-decoded stuff and config file parsing. If `strict=True`, unrecognized values, including None, will raise a ValueError which is useful when parsing values passed in from an API call. Strings yielding False are 'f', 'false', 'off', 'n', 'no', or '0'. """ if not isinstance(subject, six.string_types): subject = six.text_type(subject) lowered = subject.strip().lower() if lowered in TRUE_STRINGS: return True elif lowered in FALSE_STRINGS: return False elif strict: acceptable = ', '.join("'%s'" % s for s in sorted(TRUE_STRINGS + FALSE_STRINGS)) msg = _("Unrecognized value '%(val)s', acceptable values are:" " %(acceptable)s") % { 'val': subject, 'acceptable': acceptable } raise ValueError(msg) else: return default
def get_one(self, _id): context = t_context.extract_context_from_environ() if not policy.enforce(context, policy.ADMIN_API_BINDINGS_SHOW): pecan.abort(401, _('Unauthorized to show bindings')) return try: with context.session.begin(): pod_binding = core.get_resource(context, models.PodBinding, _id) return {'pod_binding': pod_binding} except t_exc.ResourceNotFound: pecan.abort(404, _('Tenant pod binding not found')) return
def model_query(context, *args, **kwargs): """Query helper that accounts for context's `read_deleted` field. :param context: context to query under :param session: if present, the session to use :param read_deleted: if present, overrides context's read_deleted field. :param project_only: if present and context is user-type, then restrict query to match the context's project_id. """ session = kwargs.get('session') or context.session read_deleted = kwargs.get('read_deleted') or context.read_deleted project_only = kwargs.get('project_only') query = session.query(*args) if read_deleted == 'no': query = query.filter_by(deleted=False) elif read_deleted == 'yes': pass # omit the filter to include deleted and active elif read_deleted == 'only': query = query.filter_by(deleted=True) elif read_deleted == 'int_no': query = query.filter_by(deleted=0) else: raise Exception( _("Unrecognized read_deleted value '%s'") % read_deleted) if project_only and _is_user_context(context): query = query.filter_by(project_id=context.project_id) return query
def start(self): ver_str = version.version_info LOG.info(_LI('Starting %(topic)s node (version %(version)s)'), {'topic': self.topic, 'version': ver_str}) self.basic_config_check() self.manager.init_host() self.manager.pre_start_hook() LOG.debug(_("Creating RPC server for service %s"), self.topic) target = messaging.Target(topic=self.topic, server=self.host) endpoints = [ self.manager, baserpc.BaseServerRPCAPI(self.manager.service_name) ] endpoints.extend(self.manager.additional_endpoints) self.rpc_server = rpc.get_server(target, endpoints, self.serializer) self.rpc_server.start() self.manager.post_start_hook() if self.periodic_enable: if self.periodic_fuzzy_delay: initial_delay = random.randint(0, self.periodic_fuzzy_delay) else: initial_delay = None self.tg.add_dynamic_timer(self.periodic_tasks, initial_delay=initial_delay, periodic_interval_max=self.interval_max)
def get_all(self): context = t_context.extract_context_from_environ() if not policy.enforce(context, policy.ADMIN_API_BINDINGS_LIST): pecan.abort(401, _('Unauthorized to list bindings')) return try: with context.session.begin(): pod_bindings = core.query_resource(context, models.PodBinding, [], []) except Exception: pecan.abort(500, _('Fail to list tenant pod bindings')) return return {'pod_bindings': pod_bindings}
def get_all(self): context = t_context.extract_context_from_environ() if not t_context.is_admin_context(context): pecan.abort(400, _('Admin role required to list bindings')) return try: with context.session.begin(): pod_bindings = core.query_resource(context, models.PodBinding, [], []) except Exception: pecan.abort(500, _('Fail to list tenant pod bindings')) return return {'pod_bindings': pod_bindings}
def _process_metadata_quota(self, context, t_server_dict): try: ctx = context.elevated() metadata = t_server_dict.get('metadata', None) self._check_metadata_properties_quota(ctx, metadata) except t_exceptions.InvalidMetadata as e1: LOG.exception(_LE('Invalid metadata %(exception)s'), {'exception': str(e1)}) pecan.abort(400, _('Invalid metadata')) except t_exceptions.InvalidMetadataSize as e2: LOG.exception(_LE('Invalid metadata size %(exception)s'), {'exception': str(e2)}) pecan.abort(400, _('Invalid metadata size')) except t_exceptions.MetadataLimitExceeded as e3: LOG.exception(_LE('Quota exceeded %(exception)s'), {'exception': str(e3)}) pecan.abort(400, _('Quota exceeded in metadata'))
def _allocate_network_async(self, context, instance, requested_networks, macs, security_groups, is_vpn, dhcp_options): """Method used to allocate networks in the background. Broken out for testing. """ LOG.debug("Allocating IP information in the background.", instance=instance) retries = CONF.network_allocate_retries if retries < 0: LOG.warn(_("Treating negative config value (%(retries)s) for " "'network_allocate_retries' as 0."), {'retries': retries}) attempts = retries > 1 and retries + 1 or 1 retry_time = 1 for attempt in range(1, attempts + 1): try: nwinfo = self.network_api.allocate_for_instance( context, instance, vpn=is_vpn, requested_networks=requested_networks, macs=macs, security_groups=security_groups, dhcp_options=dhcp_options) LOG.debug('Instance network_info: |%s|', nwinfo, instance=instance) instance.system_metadata['network_allocated'] = 'True' # NOTE(JoshNang) do not save the instance here, as it can cause # races. The caller shares a reference to instance and waits # for this async greenthread to finish before calling # instance.save(). return nwinfo except Exception: exc_info = sys.exc_info() log_info = {'attempt': attempt, 'attempts': attempts} if attempt == attempts: LOG.exception(_LE('Instance failed network setup ' 'after %(attempts)d attempt(s)'), log_info) raise exc_info[0], exc_info[1], exc_info[2] LOG.warn(_('Instance failed network setup ' '(attempt %(attempt)d of %(attempts)d)'), log_info, instance=instance) time.sleep(retry_time) retry_time *= 2 if retry_time > 30: retry_time = 30
def __init__(self, message=None, **kwargs): self.kwargs = kwargs self.kwargs['message'] = message if 'code' not in self.kwargs: self.kwargs['code'] = self.code for k, v in self.kwargs.items(): if isinstance(v, Exception): self.kwargs[k] = six.text_type(v) if self._should_format(): try: message = self.message % kwargs except Exception: # kwargs doesn't match a variable in the message # log the issue and the kwargs exc_info = _('Exception class %s in string ' 'format operation') % type(self).__name__ format_str = _('%(exception_info)s ; %(format_key)s : ' '%(format_value)s') for name, value in kwargs.items(): exc_info = format_str % { 'exception_info': exc_info, 'format_key': name, 'format_value': six.text_type(value)} exc_info = _('%(message)s ; %(exception_info)s') % { 'message': self.message, 'exception_info': exc_info} LOG.exception(exc_info) # no rerasie # exc_info = sys.exc_info() # if CONF.fatal_exception_format_errors: # six.reraise(*exc_info) # at least get the core message out if something happened message = self.message elif isinstance(message, Exception): message = six.text_type(message) self.msg = message super(TricircleException, self).__init__(message)
def put(self, **kw): context = t_context.extract_context_from_environ() if not context.is_admin: # TODO(joahuang): changed to policy control later # to support reseller admin mode return Response(_('Admin role required to update quota'), 409) return self._quota_action('put', **kw)
def delete(self, _id): context = t_context.extract_context_from_environ() mappings = db_api.get_bottom_mappings_by_top_id(context, _id, constants.RT_SERVER) if not mappings: pecan.response.status = 404 return {'Error': {'message': _('Server not found'), 'code': 404}} pod, bottom_id = mappings[0] client = self._get_client(pod['pod_name']) top_client = self._get_client() try: server_ports = top_client.list_ports( context, filters=[{'key': 'device_id', 'comparator': 'eq', 'value': _id}]) ret = client.delete_servers(context, bottom_id) # none return value indicates server not found if ret is None: self._remove_stale_mapping(context, _id) pecan.response.status = 404 return {'Error': {'message': _('Server not found'), 'code': 404}} for server_port in server_ports: self.xjob_handler.delete_server_port(context, server_port['id']) except Exception as e: code = 500 message = _('Delete server %(server_id)s fails') % { 'server_id': _id} if hasattr(e, 'code'): code = e.code ex_message = str(e) if ex_message: message = ex_message LOG.error(message) pecan.response.status = code return {'Error': {'message': message, 'code': code}} # NOTE(zhiyuan) Security group rules for default security group are # also kept until subnet is deleted. pecan.response.status = 204 return pecan.response
def wrapper(*args, **kwargs): try: return f(*args, **kwargs) except db_exc.DBDataError: msg = _('Error writing field to database') LOG.exception(msg) raise exceptions.Invalid(msg) except Exception as e: LOG.exception(str(e)) raise