Ejemplo n.º 1
0
    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)
Ejemplo n.º 2
0
 def get_one(self, _id):
     context = t_context.extract_context_from_environ()
     network = self.client.get_networks(context, _id)
     if not network:
         pecan.abort(404, 'Network not found')
         return
     return {'network': self._construct_network_entry(network)}
Ejemplo n.º 3
0
 def put(self, _id, **kw):
     context = t_context.extract_context_from_environ()
     dci = request.context['request_data']['dci']
     try:
         with context.session.begin():
             core.get_resource_object(context, models.DCI, _id)
             connection_updated = core.update_resource(
                 context, models.DCI, _id, dci)
             return_object = m.SuccessMessage(
                 result={'dci': connection_updated})
             return return_object.to_dict()
     except t_exceptions.ResourceNotFound as e:
         LOG.exception(
             'Failed to update dci: '
             'dci_id %(dci_id)s ,'
             '%(exception)s ', {
                 'dci_id': _id,
                 'exception': e
             })
         return m.DCINotFound(dci_id=_id).to_dict()
     except Exception as e:
         LOG.exception('Failed to update dci: '
                       '%(exception)s ', {'exception': e})
         return_object = m.FailureMessage()
         return return_object.to_dict()
Ejemplo n.º 4
0
    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)
Ejemplo n.º 5
0
    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}
Ejemplo n.º 6
0
 def get_one(self, _id):
     context = t_context.extract_context_from_environ()
     image = self.client.get_images(context, _id)
     if not image:
         pecan.abort(404, 'Image not found')
         return
     return {'image': image}
Ejemplo n.º 7
0
    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}
Ejemplo n.º 8
0
 def get_all(self):
     context = t_context.extract_context_from_environ()
     networks = self.client.list_networks(context)
     return {
         'networks':
         [self._construct_network_entry(network) for network in networks]
     }
Ejemplo n.º 9
0
 def get_one(self, _id):
     # NOTE(zhiyuan) this function handles two kinds of requests
     # GET /flavors/flavor_id
     # GET /flavors/detail
     context = t_context.extract_context_from_environ()
     if _id == 'detail':
         with context.session.begin():
             flavors = core.query_resource(context, models.InstanceTypes,
                                           [], [])
             for flavor in flavors:
                 flavor['id'] = flavor['flavorid']
                 del flavor['flavorid']
             return {'flavors': flavors}
     else:
         with context.session.begin():
             flavors = core.query_resource(context, models.InstanceTypes,
                                           [{'key': 'flavorid',
                                             'comparator': 'eq',
                                             'value': _id}], [])
             if not flavors:
                 pecan.abort(404, 'Flavor not found')
                 return
             flavor = flavors[0]
             flavor['id'] = flavor['flavorid']
             del flavor['flavorid']
             return {'flavor': flavor}
Ejemplo n.º 10
0
    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
Ejemplo n.º 11
0
    def put(self, _id, **kw):
        context = t_context.extract_context_from_environ()
        firewall_bypass = request.context['request_data']['firewall_bypass']
        try:
            with context.session.begin():
                core.get_resource_object(context, models.FirewallBypass, _id)
                firewall_bypass_updated = core.update_resource(
                    context, models.FirewallBypass, _id, firewall_bypass)
                return_object = m.SuccessMessage(
                    result={'firewall_bypass': firewall_bypass_updated})
                return return_object.to_dict()

        except t_exceptions.ResourceNotFound as e1:
            LOG.exception(
                'Failed to update firewall_bypass : '******'id%(id)s ,'
                '%(exception)s ', {
                    'id': _id,
                    'exception': e1
                })
            return m.FirewallBypassNotFound(id=_id).to_dict()
        except Exception as e2:
            LOG.exception(
                'Failed to update firewall_bypass: '******'id: %(id)s,'
                '%(exception)s ', {
                    'id': _id,
                    'exception': e2
                })
            return_object = m.FailureMessage()
            return return_object.to_dict()
Ejemplo n.º 12
0
    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
Ejemplo n.º 13
0
    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 firewall_bypass'))
            return

        try:
            with context.session.begin():
                core.delete_resource(context, models.FirewallBypass, _id)
            return_object = m.SuccessMessage(result={})
            return return_object.to_dict()
        except t_exceptions.ResourceNotFound as e1:
            LOG.exception(
                'Failed to delete firewall_bypass : '******'id%(id)s ,'
                '%(exception)s ', {
                    'id': _id,
                    'exception': e1
                })
            return m.FirewallBypassNotFound(id=_id).to_dict()
        except Exception as e2:
            LOG.exception(
                'Failed to delete firewall_bypass: '******'id: %(id)s,'
                '%(exception)s ', {
                    'id': _id,
                    'exception': e2
                })
            return_object = m.FailureMessage()
            return return_object.to_dict()
Ejemplo n.º 14
0
    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 firewall_bypass'))
            return

        try:
            return_object = m.SuccessMessage(result={
                'firewall_bypass':
                db_api.get_firewall_bypass(context, _id)
            })
            return return_object.to_dict()

        except t_exceptions.ResourceNotFound as e1:
            LOG.exception(
                'Failed to show firewall_bypass : '******'id%(id)s ,'
                '%(exception)s ', {
                    'id': _id,
                    'exception': e1
                })
            return m.FirewallBypassNotFound(id=_id).to_dict()
        except Exception as e2:
            LOG.exception(
                'Failed to show firewall_bypass: '******'id: %(id)s,'
                '%(exception)s ', {
                    'id': _id,
                    'exception': e2
                })
            return_object = m.FailureMessage()
            return return_object.to_dict()
Ejemplo n.º 15
0
    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)
Ejemplo n.º 16
0
    def put(self, _id, **kw):
        context = t_context.extract_context_from_environ()

        if not policy.enforce(context, policy.ADMIN_API_PODS_CREATE):
            pecan.abort(401, _('Unauthorized to put core_router'))
            return

        core_router = request.context['request_data']['core_router']
        try:
            with context.session.begin():
                core.get_resource(context, models.CoreRouter, _id)
                if 'routes' in core_router:
                    self._update_core_router_routes(context, _id, core_router)
                router_updated = core.update_resource(context,
                                                      models.CoreRouter, _id,
                                                      core_router)
            return_object = m.SuccessMessage(
                result={'core_router': router_updated})
            return return_object.to_dict()
        except t_exceptions.ResourceNotFound as e:
            LOG.exception(
                'Failed to update core_router : '
                'core_router_id %(core_router_id)s ,'
                '%(exception)s ', {
                    'core_router_id': _id,
                    'exception': e
                })
            return m.CoreRouterNotFound(core_router_id=_id).to_dict()
        except Exception as e:
            LOG.exception('Failed to update core_router : '
                          '%(exception)s ', {'exception': e})
            return_object = m.FailureMessage()
            return return_object.to_dict()
Ejemplo n.º 17
0
    def post(self, **kw):
        context = t_context.extract_context_from_environ()
        if not context.is_admin:
            pecan.abort(400, 'Admin role required to create aggregates')
            return
        if 'aggregate' not in kw:
            pecan.abort(400, 'Request body not found')
            return

        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:
            pecan.abort(409, 'Aggregate already exists')
            return
        except Exception:
            pecan.abort(500, 'Fail to create host aggregate')
            return

        return {'aggregate': aggregate}
Ejemplo n.º 18
0
    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'))
Ejemplo n.º 19
0
    def get_all(self):

        # TODO(joehuang): here should return link instead,
        # now combined with 'detail'

        context = t_context.extract_context_from_environ()
        return {'volumes': self._get_all(context)}
Ejemplo n.º 20
0
    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 firewall_gateway'))
            return

        firewall_gateway = request.context['request_data']['firewall_gateway']

        fabric = firewall_gateway.get('fabric', '').strip()
        firewall_id = firewall_gateway.get('firewall_id', '').strip()
        router_id = firewall_gateway.get('router_id', '').strip()
        project_id = firewall_gateway.get('project_id', '').strip()
        admin_state_up = firewall_gateway.get('admin_state_up', True)
        status = firewall_gateway.get('status', "DOWN")
        description = firewall_gateway.get('description', '').strip()

        _uuid = uuidutils.generate_uuid()

        try:
            with context.session.begin():
                new_firewall_gateway = core.create_resource(
                    context, models.FirewallGateway, {
                        'id': _uuid,
                        'fabric': fabric,
                        'firewall_id': firewall_id,
                        'router_id': router_id,
                        'project_id': project_id,
                        'admin_state_up': admin_state_up,
                        'status': status,
                        'description': description
                    })
            return_object = m.SuccessMessage(
                result={'firewall_gateway': new_firewall_gateway})
            return return_object.to_dict()
        except db_exc.DBDuplicateEntry as e1:
            LOG.exception(
                'Record firewall_gateway already exists for '
                'router_id %(router_id)s: '
                'firewall_id%(firewall_id)s: '
                '%(exception)s', {
                    'router_id': router_id,
                    'firewall_id': firewall_id,
                    'exception': e1
                })
            return_object = m.FirewallGatewayExists(router_id=router_id,
                                                    firewall_id=firewall_id)
            return return_object.to_dict()
        except Exception as e2:
            LOG.exception(
                'Failed to create firewall_gateway: '
                'router_id: %(router_id)s,'
                'firewall_id %(firewall_id)s: '
                '%(exception)s ', {
                    'router_id': router_id,
                    'firewall_id': firewall_id,
                    'exception': e2
                })
            return_object = m.FailureMessage()
            return return_object.to_dict()
Ejemplo n.º 21
0
    def post(self, **kw):
        context = t_context.extract_context_from_environ()
        if not context.is_admin:
            pecan.abort(400, 'Admin role required to create aggregates')
            return
        if 'aggregate' not in kw:
            pecan.abort(400, 'Request body not found')
            return

        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:
            pecan.abort(409, 'Aggregate already exists')
            return
        except Exception:
            pecan.abort(500, 'Fail to create host aggregate')
            return

        return {'aggregate': aggregate}
Ejemplo n.º 22
0
    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
Ejemplo n.º 23
0
    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 {}
Ejemplo n.º 24
0
    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)
Ejemplo n.º 25
0
    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'))
Ejemplo n.º 26
0
 def get_one(self, _id):
     context = t_context.extract_context_from_environ()
     network = self.client.get_networks(context, _id)
     if not network:
         pecan.abort(404, 'Network not found')
         return
     return {'network': self._construct_network_entry(network)}
Ejemplo n.º 27
0
    def get_all(self):

        # TODO(joehuang): here should return link instead,
        # now combined with 'detail'

        context = t_context.extract_context_from_environ()
        return {'volumes': self._get_all(context)}
Ejemplo n.º 28
0
    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 dci'))
            return

        try:
            dci = db_api.get_dci(context, _id)
            return_object = m.SuccessMessage(result={'dci': dci})
            return return_object.to_dict()
        except t_exceptions.ResourceNotFound as e:
            LOG.exception(
                'Failed to get dci: '
                'dci_id %(dci_id)s ,'
                '%(exception)s ', {
                    'dci_id': _id,
                    'exception': e
                })
            return m.DCINotFound(dci_id=_id).to_dict()
        except Exception as e:
            LOG.exception('Failed to get dci: %(dci_id)s,'
                          '%(exception)s', {
                              'dci_id': _id,
                              'exception': e
                          })
            return_object = m.FailureMessage()
            return return_object.to_dict()
Ejemplo n.º 29
0
 def get_one(self, _id):
     context = t_context.extract_context_from_environ()
     image = self.client.get_images(context, _id)
     if not image:
         pecan.abort(404, 'Image not found')
         return
     return {'image': self._construct_show_image_entry(context, image)}
Ejemplo n.º 30
0
    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
Ejemplo n.º 31
0
    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'))
Ejemplo n.º 32
0
    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}
Ejemplo n.º 33
0
 def get_one(self, _id):
     context = t_context.extract_context_from_environ()
     if _id == 'detail':
         return self.get_all()
     image = self.client.get_images(context, _id)
     if not image:
         return utils.format_nova_error(404, _('Image not found'))
     return {'image': self._construct_show_image_entry(context, image)}
Ejemplo n.º 34
0
 def get_all(self):
     context = t_context.extract_context_from_environ()
     images = self.client.list_images(context)
     ret_images = [
         self._construct_list_image_entry(context, image)
         for image in images
     ]
     return {'images': ret_images}
Ejemplo n.º 35
0
 def get_all(self):
     context = t_context.extract_context_from_environ()
     with context.session.begin():
         flavors = core.query_resource(context, models.InstanceTypes,
                                       [], [])
         return {'flavors': [dict(
             [('id', flavor['flavorid']),
              ('name', flavor['name'])]) for flavor in flavors]}
Ejemplo n.º 36
0
 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:
         pecan.abort(404, 'Aggregate not found')
         return
Ejemplo n.º 37
0
 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:
         pecan.abort(404, 'Aggregate not found')
         return
Ejemplo n.º 38
0
 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:
         pecan.abort(404, 'Aggregate not found')
         return
Ejemplo n.º 39
0
    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)
Ejemplo n.º 40
0
    def index(self):
        if pecan.request.method != 'GET':
            pecan.abort(405)

        context = ctx.extract_context_from_environ()

        payload = '#result from xjob rpc'

        return self.xjobapi.test_rpc(context, payload)
Ejemplo n.º 41
0
    def get_all(self):
        context = t_context.extract_context_from_environ()

        try:
            with context.session.begin():
                aggregates = az_ag.get_all_ag(context)
        except Exception:
            pecan.abort(500, 'Fail to get all host aggregates')
            return
        return {'aggregates': aggregates}
Ejemplo n.º 42
0
    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}
Ejemplo n.º 43
0
    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
Ejemplo n.º 44
0
    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}
Ejemplo n.º 45
0
    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
Ejemplo n.º 46
0
    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
Ejemplo n.º 47
0
    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'))
Ejemplo n.º 48
0
    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
Ejemplo n.º 49
0
    def post(self, **kw):
        context = t_context.extract_context_from_environ()

        if 'volumeAttachment' not in kw:
            pecan.abort(400, 'Request body not found')
            return
        body = kw['volumeAttachment']
        if 'volumeId' not in body:
            pecan.abort(400, 'Volume not set')
            return

        server_mappings = db_api.get_bottom_mappings_by_top_id(
            context, self.server_id, constants.RT_SERVER)
        if not server_mappings:
            pecan.abort(404, 'Server not found')
            return
        volume_mappings = db_api.get_bottom_mappings_by_top_id(
            context, body['volumeId'], constants.RT_VOLUME)
        if not volume_mappings:
            pecan.abort(404, 'Volume not found')
            return

        server_pod_name = server_mappings[0][0]['pod_name']
        volume_pod_name = volume_mappings[0][0]['pod_name']
        if server_pod_name != volume_pod_name:
            LOG.error(_LE('Server %(server)s is in pod %(server_pod)s and '
                          'volume %(volume)s is in pod %(volume_pod)s, which '
                          'are not the same.'),
                      {'server': self.server_id,
                       'server_pod': server_pod_name,
                       'volume': body['volumeId'],
                       'volume_pod': volume_pod_name})
            pecan.abort(400, 'Server and volume not in the same pod')
            return

        device = None
        if 'device' in body:
            device = body['device']
            # this regular expression is copied from nova/block_device.py
            match = re.match('(^/dev/x{0,1}[a-z]{0,1}d{0,1})([a-z]+)[0-9]*$',
                             device)
            if not match:
                pecan.abort(400, 'Invalid device path')
                return

        client = self._get_client(server_pod_name)
        volume = client.action_server_volumes(
            context, 'create_server_volume',
            server_mappings[0][1], volume_mappings[0][1], device)
        return {'volumeAttachment': volume.to_dict()}
Ejemplo n.º 50
0
    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
Ejemplo n.º 51
0
 def delete(self, _id):
     context = t_context.extract_context_from_environ()
     with context.session.begin():
         flavors = core.query_resource(context, models.InstanceTypes,
                                       [{'key': 'flavorid',
                                         'comparator': 'eq',
                                         'value': _id}], [])
         if not flavors:
             pecan.abort(404, 'Flavor not found')
             return
         core.delete_resource(context,
                              models.InstanceTypes, flavors[0]['id'])
     pecan.response.status = 202
     return
Ejemplo n.º 52
0
    def _quota_action(self, action, **kw):

        context = t_context.extract_context_from_environ()
        context.project_id = self.owner_tenant_id
        target_tenant_id = self.target_tenant_id
        target_user_id = request.params.get('user_id', None)
        if target_user_id:
            target_user_id.strip()

        qs = quota.QuotaSetOperation(target_tenant_id,
                                     target_user_id)
        quotas = {}
        try:
            if action == 'put':
                quotas = qs.update(context, **kw)
            elif action == 'delete':
                qs.delete(context)
                response.status = 202
                return
            elif action == 'defaults':
                quotas = qs.show_default_quota(context)
            elif action == 'detail':
                quotas = qs.show_detail_quota(context, show_usage=True)

                # remove the allocated field which is not visible in Nova
                for k, v in quotas['quota_set'].iteritems():
                    if k != 'id':
                        v.pop('allocated', None)

            elif action == 'quota-show':
                quotas = qs.show_detail_quota(context, show_usage=False)
            else:
                return Response('Resource not found', 404)
        except t_exceptions.NotFound as e:
            msg = str(e)
            LOG.exception(msg=msg)
            return Response(msg, 404)
        except (t_exceptions.AdminRequired,
                t_exceptions.NotAuthorized,
                t_exceptions.HTTPForbiddenError) as e:
            msg = str(e)
            LOG.exception(msg=msg)
            return Response(msg, 403)
        except Exception as e:
            msg = str(e)
            LOG.exception(msg=msg)
            return Response(msg, 400)

        return {'quota_set': self._build_visible_quota(quotas['quota_set'])}
Ejemplo n.º 53
0
    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
Ejemplo n.º 54
0
    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
Ejemplo n.º 55
0
    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
Ejemplo n.º 56
0
    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
Ejemplo n.º 57
0
    def post(self, **kw):
        context = t_context.extract_context_from_environ()

        if not policy.enforce(context, policy.ADMIN_API_ROUTINGS_CREATE):
            return utils.format_api_error(
                403, _("Unauthorized to create resource routing"))

        if 'routing' not in kw:
            return utils.format_api_error(
                400, _("Request body not found"))

        routing = kw['routing']

        for field in ('top_id', 'bottom_id', 'pod_id',
                      'project_id', 'resource_type'):
            value = routing.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.
        resource_type = routing.get('resource_type').strip()
        if not constants.is_valid_resource_type(resource_type):
            return utils.format_api_error(
                400, _('There is no such resource type'))

        try:
            top_id = routing.get('top_id').strip()
            bottom_id = routing.get('bottom_id').strip()
            pod_id = routing.get('pod_id').strip()
            project_id = routing.get('project_id').strip()

            routing = db_api.create_resource_mapping(context, top_id,
                                                     bottom_id, pod_id,
                                                     project_id,
                                                     resource_type)
            if not routing:
                return utils.format_api_error(
                    409, _('Resource routing already exists'))
        except Exception as e:
            LOG.exception('Failed to create resource routing: '
                          '%(exception)s ', {'exception': e})
            return utils.format_api_error(
                500, _('Failed to create resource routing'))

        return {'routing': routing}