Esempio n. 1
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'))
Esempio n. 2
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'))
Esempio n. 3
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'))
Esempio n. 4
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'))
Esempio n. 5
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'))
Esempio n. 6
0
    def delete(self, job_id):
        # delete a job from the database. If the job is running, the delete
        # operation will fail. In other cases, job will be deleted directly.
        context = t_context.extract_context_from_environ()

        if not policy.enforce(context, policy.ADMIN_API_JOB_DELETE):
            return utils.format_api_error(403,
                                          _('Unauthorized to delete a job'))

        try:
            db_api.get_job_from_log(context, job_id)
            return utils.format_api_error(
                400,
                _('Job %(job_id)s is from job log') % {'job_id': job_id})
        except Exception:
            try:
                job = db_api.get_job(context, job_id)
            except t_exc.ResourceNotFound:
                return utils.format_api_error(
                    404,
                    _('Job %(job_id)s not found') % {'job_id': job_id})
        try:
            # if job status = RUNNING, notify user this new one, delete
            # operation fails.
            if job['status'] == constants.JS_Running:
                return utils.format_api_error(
                    400, (_('Failed to delete the running job %(job_id)s') % {
                        "job_id": job_id
                    }))
            # if job status = SUCCESS, move the job entry to job log table,
            # then delete it from job table.
            elif job['status'] == constants.JS_Success:
                db_api.finish_job(context, job_id, True, timeutils.utcnow())
                pecan.response.status = 200
                return {}

            db_api.delete_job(context, job_id)
            pecan.response.status = 200
            return {}
        except Exception as e:
            LOG.exception('Failed to delete the job: '
                          '%(exception)s ', {'exception': e})
            return utils.format_api_error(500, _('Failed to delete the job'))
Esempio n. 7
0
    def get_one(self, id, **kwargs):
        """the return value may vary according to the value of id

        :param id: 1) if id = 'schemas', return job schemas
                   2) if id = 'detail', return all jobs
                   3) if id = $job_id, return detailed single job info
        :return: return value is decided by id parameter
        """
        context = t_context.extract_context_from_environ()
        job_resource_map = constants.job_resource_map

        if not policy.enforce(context, policy.ADMIN_API_JOB_SCHEMA_LIST):
            return utils.format_api_error(
                403, _('Unauthorized to show job information'))

        if id == 'schemas':
            job_schemas = []
            for job_type in job_resource_map.keys():
                job = {}
                resource = []
                for resource_type, resource_id in job_resource_map[job_type]:
                    resource.append(resource_id)

                job['resource'] = resource
                job['type'] = job_type
                job_schemas.append(job)

            return {'schemas': job_schemas}

        if id == 'detail':
            return self.get_all(**kwargs)

        try:
            job = db_api.get_job(context, id)
            return {'job': self._get_more_readable_job(job)}
        except Exception:
            try:
                job = db_api.get_job_from_log(context, id)
                return {'job': self._get_more_readable_job(job)}
            except t_exc.ResourceNotFound:
                return utils.format_api_error(
                    404, _('Resource not found'))
Esempio n. 8
0
    def get_all(self, **kwargs):
        context = t_context.extract_context_from_environ()

        if not policy.enforce(context, policy.ADMIN_API_ROUTINGS_LIST):
            return utils.format_api_error(
                403, _('Unauthorized to to show all resource routings'))

        filters = self._get_filters(kwargs)
        filters = [{'key': key,
                    'comparator': 'eq',
                    'value': value} for key, value in filters.iteritems()]

        try:
            return {'routings': db_api.list_resource_routings(context,
                                                              filters)}
        except Exception as e:
            LOG.exception(_LE('Failed to show all resource routings: '
                              '%(exception)s '), {'exception': e})
            return utils.format_api_error(
                500, _('Failed to show all resource routings'))
Esempio n. 9
0
    def delete(self, job_id):
        # delete a job from the database. If the job is running, the delete
        # operation will fail. In other cases, job will be deleted directly.
        context = t_context.extract_context_from_environ()

        if not policy.enforce(context, policy.ADMIN_API_JOB_DELETE):
            return utils.format_api_error(
                403, _('Unauthorized to delete a job'))

        try:
            db_api.get_job_from_log(context, job_id)
            return utils.format_api_error(
                400, _('Job %(job_id)s is from job log') % {'job_id': job_id})
        except Exception:
            try:
                job = db_api.get_job(context, job_id)
            except t_exc.ResourceNotFound:
                return utils.format_api_error(
                    404, _('Job %(job_id)s not found') % {'job_id': job_id})
        try:
            # if job status = RUNNING, notify user this new one, delete
            # operation fails.
            if job['status'] == constants.JS_Running:
                return utils.format_api_error(
                    400, (_('Failed to delete the running job %(job_id)s') %
                          {"job_id": job_id}))
            # if job status = SUCCESS, move the job entry to job log table,
            # then delete it from job table.
            elif job['status'] == constants.JS_Success:
                db_api.finish_job(context, job_id, True, timeutils.utcnow())
                pecan.response.status = 200
                return {}

            db_api.delete_job(context, job_id)
            pecan.response.status = 200
            return {}
        except Exception as e:
            LOG.exception('Failed to delete the job: '
                          '%(exception)s ', {'exception': e})
            return utils.format_api_error(
                500, _('Failed to delete the job'))
Esempio n. 10
0
    def delete(self, _id):
        context = t_context.extract_context_from_environ()

        if not policy.enforce(context, policy.ADMIN_API_ROUTINGS_DELETE):
            return utils.format_api_error(
                403, _('Unauthorized to delete the resource routing'))

        try:
            db_api.get_resource_routing(context, _id)
        except t_exc.ResourceNotFound:
            return utils.format_api_error(404,
                                          _('Resource routing not found'))
        try:
            db_api.delete_resource_routing(context, _id)
            pecan.response.status = 200
            return pecan.response
        except Exception as e:
            LOG.exception(_LE('Failed to delete the resource routing: '
                              '%(exception)s '), {'exception': e})
            return utils.format_api_error(
                500, _('Failed to delete the resource routing'))
Esempio n. 11
0
    def delete(self, _id):
        context = t_context.extract_context_from_environ()

        if not policy.enforce(context, policy.ADMIN_API_ROUTINGS_DELETE):
            return utils.format_api_error(
                403, _('Unauthorized to delete the resource routing'))

        try:
            db_api.get_resource_routing(context, _id)
        except t_exc.ResourceNotFound:
            return utils.format_api_error(404, _('Resource routing not found'))
        try:
            db_api.delete_resource_routing(context, _id)
            pecan.response.status = 200
            return pecan.response
        except Exception as e:
            LOG.exception(
                _LE('Failed to delete the resource routing: '
                    '%(exception)s '), {'exception': e})
            return utils.format_api_error(
                500, _('Failed to delete the resource routing'))
Esempio n. 12
0
    def get_all(self, **kwargs):
        context = t_context.extract_context_from_environ()

        if not policy.enforce(context, policy.ADMIN_API_ROUTINGS_LIST):
            return utils.format_api_error(
                403, _('Unauthorized to show all resource routings'))

        filters = self._get_filters(kwargs)
        filters = [{
            'key': key,
            'comparator': 'eq',
            'value': value
        } for key, value in six.iteritems(filters)]

        try:
            return {
                'routings': db_api.list_resource_routings(context, filters)
            }
        except Exception as e:
            LOG.exception(
                _LE('Failed to show all resource routings: '
                    '%(exception)s '), {'exception': e})
            return utils.format_api_error(
                500, _('Failed to show all resource routings'))
Esempio n. 13
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}
Esempio n. 14
0
    def put(self, _id, **kw):
        context = t_context.extract_context_from_environ()

        tricircle_resource = request.context['request_data']['tricircle_resource']
        try:
            with context.session.begin():
                core.get_resource(context, models.TricircleResource, _id)
        except t_exceptions.ResourceNotFound:
            pecan.abort(404, _('Tricircle resource not found'))
            return
        try:
           tricircle_resource_updated= db_api.update_tricircle_resource(
                    context, _id, tricircle_resource)
           return {'tricircle_resource': tricircle_resource_updated}
        except t_exceptions.ResourceNotFound:
            pecan.abort(404, _('Tricircle resource not found'))
            return
        except Exception as e:
            LOG.exception('Failed to update tricircle resource : '
                          '%(exception)s ', {'exception': e})
            return utils.format_api_error(
                500, _('Failed to update tricircle resource '))
Esempio n. 15
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(
                _LE('Failed to create resource routing: '
                    '%(exception)s '), {'exception': e})
            return utils.format_api_error(
                500, _('Failed to create resource routing'))

        return {'routing': routing}
Esempio n. 16
0
    def put(self, job_id):
        # we use HTTP/HTTPS PUT method to redo a job. Regularly PUT method
        # requires a request body, but considering the job redo operation
        # doesn't need more information other than job id, we will issue
        # this request without a request body.
        context = t_context.extract_context_from_environ()

        if not policy.enforce(context, policy.ADMIN_API_JOB_REDO):
            return utils.format_api_error(403, _('Unauthorized to redo a job'))

        try:
            db_api.get_job_from_log(context, job_id)
            return utils.format_api_error(
                400,
                _('Job %(job_id)s is from job log') % {'job_id': job_id})
        except Exception:
            try:
                job = db_api.get_job(context, job_id)
            except t_exc.ResourceNotFound:
                return utils.format_api_error(
                    404,
                    _('Job %(job_id)s not found') % {'job_id': job_id})

        try:
            # if status = RUNNING, notify user this new one and then exit
            if job['status'] == constants.JS_Running:
                return utils.format_api_error(
                    400, (_("Can't redo job %(job_id)s which is running") % {
                        'job_id': job['id']
                    }))
            # if status = SUCCESS, notify user this new one and then exit
            elif job['status'] == constants.JS_Success:
                msg = (
                    _("Can't redo job %(job_id)s which had run successfully") %
                    {
                        'job_id': job['id']
                    })
                return utils.format_api_error(400, msg)
            # if job status =  FAIL or job status = NEW, redo it immediately
            self.xjob_handler.invoke_method(context, job['project_id'],
                                            constants.job_handles[job['type']],
                                            job['type'], job['resource_id'])
        except Exception as e:
            LOG.exception('Failed to redo the job: '
                          '%(exception)s ', {'exception': e})
            return utils.format_api_error(500, _('Failed to redo the job'))
    def put(self, _id, **kw):
        context = t_context.extract_context_from_environ()

        print 'MaXiao put '+str(request.context['request_data'])
        dynamic_peering_connection = request.context['request_data']['dynamic_peering_connection']
        try:
            with context.session.begin():
                core.get_resource(context, models.DynamicPeeringConnection, _id)
        except t_exceptions.ResourceNotFound:
            pecan.abort(404, _('Core Router not found'))
            return
        try:
           connection_updated= db_api.update_dynamic_peering_connection(
                    context, _id, dynamic_peering_connection)
           return {'dynamic_peering_connection': connection_updated}
        except t_exceptions.ResourceNotFound:
            pecan.abort(404, _('Dynamic Peering Connection not found'))
            return
        except Exception as e:
            LOG.exception('Failed to update dynamic peering connection : '
                          '%(exception)s ', {'exception': e})
            return utils.format_api_error(
                500, _('Failed to update dynamic peering connection '))
Esempio n. 18
0
    def put(self, job_id):
        # we use HTTP/HTTPS PUT method to redo a job. Regularly PUT method
        # requires a request body, but considering the job redo operation
        # doesn't need more information other than job id, we will issue
        # this request without a request body.
        context = t_context.extract_context_from_environ()

        if not policy.enforce(context, policy.ADMIN_API_JOB_REDO):
            return utils.format_api_error(
                403, _('Unauthorized to redo a job'))

        try:
            db_api.get_job_from_log(context, job_id)
            return utils.format_api_error(
                400, _('Job %(job_id)s is from job log') % {'job_id': job_id})
        except Exception:
            try:
                job = db_api.get_job(context, job_id)
            except t_exc.ResourceNotFound:
                return utils.format_api_error(
                    404, _('Job %(job_id)s not found') % {'job_id': job_id})

        try:
            # if status = RUNNING, notify user this new one and then exit
            if job['status'] == constants.JS_Running:
                return utils.format_api_error(
                    400, (_("Can't redo job %(job_id)s which is running") %
                          {'job_id': job['id']}))
            # if status = SUCCESS, notify user this new one and then exit
            elif job['status'] == constants.JS_Success:
                msg = (_("Can't redo job %(job_id)s which had run successfully"
                         ) % {'job_id': job['id']})
                return utils.format_api_error(400, msg)
            # if job status =  FAIL or job status = NEW, redo it immediately
            self.xjob_handler.invoke_method(context, job['project_id'],
                                            constants.job_handles[job['type']],
                                            job['type'], job['resource_id'])
        except Exception as e:
            LOG.exception('Failed to redo the job: '
                          '%(exception)s ', {'exception': e})
            return utils.format_api_error(
                500, _('Failed to redo the job'))
Esempio n. 19
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'))

        # check limit and marker, default value -1 means no pagination
        _limit = kwargs.pop('limit', -1)

        try:
            limit = int(_limit)
            limit = utils.get_pagination_limit(limit)
        except ValueError as e:
            LOG.exception('Failed to convert pagination limit to an integer: '
                          '%(exception)s ', {'exception': e})
            msg = (_("Limit should be an integer or a valid literal "
                     "for int() rather than '%s'") % _limit)
            return utils.format_api_error(400, msg)

        marker = kwargs.pop('marker', None)

        sorts = [('timestamp', 'desc'), ('id', 'desc')]
        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)

        # project ID from client should be equal to the one from
        # context, since only the project ID in which the user
        # is authorized will be used as the filter.
        filters['project_id'] = context.project_id
        filters = [{'key': key, 'comparator': 'eq', 'value': value}
                   for key, value in six.iteritems(filters)]

        try:
            if marker is not None:
                try:
                    # verify whether the marker is effective
                    db_api.get_job(context, marker)
                    jobs = db_api.list_jobs(context, filters,
                                            sorts, limit, marker)
                    jobs_from_log = []
                    if len(jobs) < limit:
                        jobs_from_log = db_api.list_jobs_from_log(
                            context, filters, sorts, limit - len(jobs), None)
                    job_collection = jobs + jobs_from_log
                except t_exc.ResourceNotFound:
                    try:
                        db_api.get_job_from_log(context, marker)
                        jobs_from_log = db_api.list_jobs_from_log(
                            context, filters, sorts, limit, marker)
                        job_collection = jobs_from_log
                    except t_exc.ResourceNotFound:
                        msg = (_('Invalid marker: %(marker)s')
                               % {'marker': marker})
                        return utils.format_api_error(400, msg)
            else:
                jobs = db_api.list_jobs(context, filters,
                                        sorts, limit, marker)
                jobs_from_log = []
                if len(jobs) < limit:
                    jobs_from_log = db_api.list_jobs_from_log(
                        context, filters, sorts, limit - len(jobs), None)
                job_collection = jobs + jobs_from_log
            # add link
            links = []
            if len(job_collection) >= limit:
                marker = job_collection[-1]['id']
                base = constants.JOB_PATH
                link = "%s?limit=%s&marker=%s" % (base, limit, marker)
                links.append({"rel": "next",
                              "href": link})

            result = {'jobs': [self._get_more_readable_job(job)
                               for job in job_collection]}
            if links:
                result['jobs_links'] = links
            return result
        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'))
Esempio n. 20
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:
            routing = db_api.get_resource_routing(context, _id)
        except t_exc.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'))

        # verify the integrity: the pod_id and project_id should be bound
        if 'pod_id' in update_dict or 'project_id' in update_dict:
            if 'pod_id' in update_dict:
                pod_id = update_dict['pod_id']
            else:
                pod_id = routing['pod_id']

            if 'project_id' in update_dict:
                project_id = update_dict['project_id']
            else:
                project_id = routing['project_id']

            bindings = db_api.list_pod_bindings(context,
                                                [{'key': 'pod_id',
                                                  'comparator': 'eq',
                                                  'value': pod_id
                                                  },
                                                 {'key': 'tenant_id',
                                                  'comparator': 'eq',
                                                  'value': project_id}
                                                 ], [])
            if len(bindings) == 0:
                return utils.format_api_error(
                    400, _('The pod_id and project_id have not been '
                           'bound'))

        try:
            routing_updated = db_api.update_resource_routing(
                context, _id, update_dict)
            return {'routing': routing_updated}
        except Exception as e:
            LOG.exception(_LE('Failed to update resource routing: '
                              '%(exception)s '), {'exception': e})
            return utils.format_api_error(
                500, _('Failed to update resource routing'))
Esempio n. 21
0
    def get_all(self, **kwargs):
        context = t_context.extract_context_from_environ()

        if not policy.enforce(context, policy.ADMIN_API_ROUTINGS_LIST):
            return utils.format_api_error(
                403, _('Unauthorized to show all resource routings'))

        # default value -1 means no pagination, then maximum pagination
        # limit from configuration will be used.
        _limit = kwargs.pop('limit', -1)

        try:
            limit = int(_limit)
            limit = utils.get_pagination_limit(limit)
        except ValueError as e:
            LOG.exception(
                'Failed to convert pagination limit to an integer: '
                '%(exception)s ', {'exception': e})
            msg = (_("Limit should be an integer or a valid literal "
                     "for int() rather than '%s'") % _limit)
            return utils.format_api_error(400, msg)

        marker = kwargs.pop('marker', None)
        if marker is not None:
            try:
                marker = int(marker)
                try:
                    # we throw an exception if a marker with
                    # invalid ID is specified.
                    db_api.get_resource_routing(context, marker)
                except t_exceptions.ResourceNotFound:
                    return utils.format_api_error(
                        400,
                        _('Marker %s is an invalid ID') % marker)
            except ValueError as e:
                LOG.exception(
                    'Failed to convert page marker to an integer: '
                    '%(exception)s ', {'exception': e})
                msg = (_("Marker should be an integer or a valid literal "
                         "for int() rather than '%s'") % marker)
                return utils.format_api_error(400, msg)

        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)

        if 'id' in filters:
            try:
                # resource routing id is an integer.
                filters['id'] = int(filters['id'])
            except ValueError as e:
                LOG.exception(
                    'Failed to convert routing id to an integer:'
                    ' %(exception)s ', {'exception': e})
                msg = (_("Id should be an integer or a valid literal "
                         "for int() rather than '%s'") % filters['id'])
                return utils.format_api_error(400, msg)

        # project ID from client should be equal to the one from
        # context, since only the project ID in which the user
        # is authorized will be used as the filter.
        filters['project_id'] = context.project_id
        expand_filters = [{
            'key': filter_name,
            'comparator': 'eq',
            'value': filters[filter_name]
        } for filter_name in filters]
        try:
            routings = db_api.list_resource_routings(context,
                                                     expand_filters,
                                                     limit,
                                                     marker,
                                                     sorts=[('id', 'desc')])
            links = []
            if len(routings) >= limit:
                marker = routings[-1]['id']
                # if we reach the first element, then no elements in next page,
                # so link to next page won't be provided.
                if marker != 1:
                    base = constants.ROUTING_PATH
                    link = "%s?limit=%s&marker=%s" % (base, limit, marker)

                    links.append({"rel": "next", "href": link})

            result = {}
            result["routings"] = routings
            if links:
                result["routings_links"] = links
            return result
        except Exception as e:
            LOG.exception(
                'Failed to show all resource routings: '
                '%(exception)s ', {'exception': e})
            return utils.format_api_error(
                500, _('Failed to show all resource routings'))
Esempio n. 22
0
 def test_format_api_error(self, mock_format_error):
     output = utils.format_api_error(400, 'this is error')
     self.assertEqual(mock_format_error.return_value, output)
Esempio n. 23
0
    def post(self, **kw):
        context = t_context.extract_context_from_environ()
        job_resource_map = constants.job_resource_map

        if not policy.enforce(context, policy.ADMIN_API_JOB_CREATE):
            return utils.format_api_error(
                403, _("Unauthorized to create a job"))

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

        job = kw['job']

        for field in ('type', 'project_id'):
            value = job.get(field)
            if value is None:
                return utils.format_api_error(
                    400, _("%(field)s isn't provided in request body") % {
                        'field': field})
            elif len(value.strip()) == 0:
                return utils.format_api_error(
                    400, _("%(field)s can't be empty") % {'field': field})

        if job['type'] not in job_resource_map.keys():
            return utils.format_api_error(
                400, _('There is no such job type: %(job_type)s') % {
                    'job_type': job['type']})

        job_type = job['type']
        project_id = job['project_id']

        if 'resource' not in job:
            return utils.format_api_error(
                400, _('Failed to create job, because the resource is not'
                       ' specified'))

        # verify that all given resources are exactly needed
        request_fields = set(job['resource'].keys())
        require_fields = set([resource_id
                              for resource_type, resource_id in
                              job_resource_map[job_type]])
        missing_fields = require_fields - request_fields
        redundant_fields = request_fields - require_fields

        if missing_fields:
                return utils.format_api_error(
                    400, _('Some required fields are not specified:'
                           ' %(field)s') % {'field': missing_fields})
        if redundant_fields:
                return utils.format_api_error(
                    400, _('Some fields are redundant: %(field)s') % {
                        'field': redundant_fields})

        # validate whether the project id is legal
        resource_type_1, resource_id_1 = (
            constants.job_primary_resource_map[job_type])
        if resource_type_1 is not None:
            filter = [{'key': 'project_id', 'comparator': 'eq',
                       'value': project_id},
                      {'key': 'resource_type', 'comparator': 'eq',
                       'value': resource_type_1},
                      {'key': 'top_id', 'comparator': 'eq',
                       'value': job['resource'][resource_id_1]}]

            routings = db_api.list_resource_routings(context, filter)
            if not routings:
                msg = (_("%(resource)s %(resource_id)s doesn't belong to the"
                         " project %(project_id)s") %
                       {'resource': resource_type_1,
                        'resource_id': job['resource'][resource_id_1],
                        'project_id': project_id})
                return utils.format_api_error(400, msg)

        # if job_type = seg_rule_setup, we should ensure the project id
        # is equal to the one from resource.
        if job_type in (constants.JT_SEG_RULE_SETUP,
                        constants.JT_RESOURCE_RECYCLE):
            if job['project_id'] != job['resource']['project_id']:
                msg = (_("Specified project_id %(project_id_1)s and resource's"
                         " project_id %(project_id_2)s are different") %
                       {'project_id_1': job['project_id'],
                        'project_id_2': job['resource']['project_id']})
                return utils.format_api_error(400, msg)

        # combine uuid into target resource id
        resource_id = '#'.join([job['resource'][resource_id]
                                for resource_type, resource_id
                                in job_resource_map[job_type]])

        try:
            # create a job and put it into execution immediately
            self.xjob_handler.invoke_method(context, project_id,
                                            constants.job_handles[job_type],
                                            job_type, resource_id)
        except Exception as e:
            LOG.exception('Failed to create job: '
                          '%(exception)s ', {'exception': e})
            return utils.format_api_error(
                500, _('Failed to create a job'))

        new_job = db_api.get_latest_job(context, constants.JS_New, job_type,
                                        resource_id)
        return {'job': self._get_more_readable_job(new_job)}
Esempio n. 24
0
    def get_all(self, **kwargs):
        context = t_context.extract_context_from_environ()

        if not policy.enforce(context, policy.ADMIN_API_ROUTINGS_LIST):
            return utils.format_api_error(
                403, _('Unauthorized to show all resource routings'))

        # default value -1 means no pagination, then maximum pagination
        # limit from configuration will be used.
        _limit = kwargs.pop('limit', -1)

        try:
            limit = int(_limit)
            limit = utils.get_pagination_limit(limit)
        except ValueError as e:
            LOG.exception('Failed to convert pagination limit to an integer: '
                          '%(exception)s ', {'exception': e})
            msg = (_("Limit should be an integer or a valid literal "
                     "for int() rather than '%s'") % _limit)
            return utils.format_api_error(400, msg)

        marker = kwargs.pop('marker', None)
        if marker is not None:
            try:
                marker = int(marker)
                try:
                    # we throw an exception if a marker with
                    # invalid ID is specified.
                    db_api.get_resource_routing(context, marker)
                except t_exceptions.ResourceNotFound:
                    return utils.format_api_error(
                        400, _('Marker %s is an invalid ID') % marker)
            except ValueError as e:
                LOG.exception('Failed to convert page marker to an integer: '
                              '%(exception)s ', {'exception': e})
                msg = (_("Marker should be an integer or a valid literal "
                         "for int() rather than '%s'") % marker)
                return utils.format_api_error(400, msg)

        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)

        if 'id' in filters:
            try:
                # resource routing id is an integer.
                filters['id'] = int(filters['id'])
            except ValueError as e:
                LOG.exception('Failed to convert routing id to an integer:'
                              ' %(exception)s ', {'exception': e})
                msg = (_("Id should be an integer or a valid literal "
                         "for int() rather than '%s'") % filters['id'])
                return utils.format_api_error(400, msg)

        # project ID from client should be equal to the one from
        # context, since only the project ID in which the user
        # is authorized will be used as the filter.
        filters['project_id'] = context.project_id
        expand_filters = [{'key': filter_name, 'comparator': 'eq',
                           'value': filters[filter_name]}
                          for filter_name in filters]
        try:
            routings = db_api.list_resource_routings(context, expand_filters,
                                                     limit, marker,
                                                     sorts=[('id', 'desc')])
            links = []
            if len(routings) >= limit:
                marker = routings[-1]['id']
                # if we reach the first element, then no elements in next page,
                # so link to next page won't be provided.
                if marker != 1:
                    base = constants.ROUTING_PATH
                    link = "%s?limit=%s&marker=%s" % (base, limit, marker)

                    links.append({"rel": "next",
                                  "href": link})

            result = {}
            result["routings"] = routings
            if links:
                result["routings_links"] = links
            return result
        except Exception as e:
            LOG.exception('Failed to show all resource routings: '
                          '%(exception)s ', {'exception': e})
            return utils.format_api_error(
                500, _('Failed to show all resource routings'))