Example #1
0
    def get_trunks(self, context, filters=None, fields=None,
                   sorts=None, limit=None, marker=None, page_reverse=False):
        ret = []
        bottom_top_map = {}
        top_bottom_map = {}
        t_ctx = t_context.get_context_from_neutron_context(context)

        route_filters = [{'key': 'resource_type',
                          'comparator': 'eq',
                          'value': t_constants.RT_TRUNK}]
        routes = db_api.list_resource_routings(t_ctx, route_filters)
        for route in routes:
            bottom_top_map[route['bottom_id']] = route['top_id']
            top_bottom_map[route['top_id']] = route['bottom_id']

        if limit:
            if marker:
                mappings = db_api.get_bottom_mappings_by_top_id(
                    t_ctx, marker, t_constants.RT_TRUNK)
                # if mapping exists, we retrieve trunk information
                # from bottom, otherwise from top
                if mappings:
                    pod_id = mappings[0][0]['pod_id']
                    current_pod = db_api.get_pod(t_ctx, pod_id)
                    ret = self._get_trunks_from_pod_with_limit(
                        context, current_pod, bottom_top_map, top_bottom_map,
                        filters, limit, marker)
                else:
                    ret = self._get_trunks_from_top_with_limit(
                        context, top_bottom_map, filters, limit, marker)
            else:
                current_pod = db_api.get_next_bottom_pod(t_ctx)
                # if current_pod exists, we retrieve trunk information
                # from bottom, otherwise from top
                if current_pod:
                    ret = self._get_trunks_from_pod_with_limit(
                        context, current_pod, bottom_top_map, top_bottom_map,
                        filters, limit, None)
                else:
                    ret = self._get_trunks_from_top_with_limit(
                        context, top_bottom_map, filters, limit, None)
        else:
            pods = db_api.list_pods(t_ctx)
            _filters = self._transform_trunk_filters(filters, top_bottom_map)
            for pod in pods:
                if not pod['az_name']:
                    continue
                client = self._get_client(pod['region_name'])
                pod_trunks = client.list_trunks(t_ctx, filters=_filters)
                ret.extend(pod_trunks)
            ret = self._map_trunks_from_bottom_to_top(ret, bottom_top_map)
            top_trunks = self._get_trunks_from_top(context,
                                                   top_bottom_map, filters)
            ret.extend(top_trunks)

        return [super(TricircleTrunkPlugin, self)._fields(trunk, fields)
                for trunk in ret]
Example #2
0
    def test_delete(self, mock_context):
        mock_context.return_value = self.context

        # prepare the foreign key: pod_id
        kw_pod = {'pod': {'region_name': 'pod1', 'az_name': 'az1'}}
        pod_id = pod.PodsController().post(**kw_pod)['pod']['pod_id']

        # a variable used for later test
        project_id = uuidutils.generate_uuid()

        kw_routing = {
            'routing': {
                'top_id': '09fd7cc9-d169-4b5a-88e8-436ecf4d0bfe',
                'bottom_id': 'dc80f9de-abb7-4ec6-ab7a-94f8fd1e20ef',
                'pod_id': pod_id,
                'project_id': project_id,
                'resource_type': 'subnet'
            }
        }

        routing = self.controller.post(**kw_routing)
        id = routing['routing']['id']
        res = self.controller.delete(id)
        self.assertEqual(200, res.status)

        routings = db_api.list_resource_routings(
            self.context, [{
                'key': 'top_id',
                'comparator': 'eq',
                'value': '09fd7cc9-d'
                '169-4b5a-88e8-436ecf4d0bfe'
            }, {
                'key': 'pod_id',
                'comparator': 'eq',
                'value': pod_id
            }], [])
        self.assertEqual(0, len(routings))

        # failure case, only admin can delete resource routing
        self.context.is_admin = False
        res = self.controller.delete(id)
        self._validate_error_code(res, 403)

        self.context.is_admin = True

        # failure case, resource routing not found
        res = self.controller.delete(-123)
        self._validate_error_code(res, 404)
Example #3
0
    def test_delete(self, mock_context):
        mock_context.return_value = self.context

        # prepare the foreign key: pod_id, project_id
        kw_pod = {'pod': {'pod_name': 'pod1', 'az_name': 'az1'}}
        pod_id = pod.PodsController().post(**kw_pod)['pod']['pod_id']

        kw_binding = {'pod_binding': {'tenant_id': '01', 'pod_id': pod_id}}
        project_id = pod.BindingsController().post(**kw_binding)[
            'pod_binding']['tenant_id']

        kw_routing = {'routing':
                      {'top_id': '09fd7cc9-d169-4b5a-88e8-436ecf4d0bfe',
                       'bottom_id': 'dc80f9de-abb7-4ec6-ab7a-94f8fd1e20ef',
                       'pod_id': pod_id,
                       'project_id': project_id,
                       'resource_type': 'subnet'
                       }}

        routing = self.controller.post(**kw_routing)
        id = routing['routing']['id']
        res = self.controller.delete(id)
        self.assertEqual(res.status, 200)

        routings = db_api.list_resource_routings(self.context,
                                                 [{'key': 'top_id',
                                                  'comparator': 'eq',
                                                   'value': '09fd7cc9-d'
                                                   '169-4b5a-88e8-436ecf4d0bfe'
                                                   },
                                                  {'key': 'pod_id',
                                                   'comparator': 'eq',
                                                   'value': pod_id
                                                   }], [])
        self.assertEqual(len(routings), 0)

        # failure case, only admin can delete resource routing
        self.context.is_admin = False
        res = self.controller.delete(id)
        self._validate_error_code(res, 403)

        self.context.is_admin = True

        # failure case, resource routing not found
        res = self.controller.delete(-123)
        self._validate_error_code(res, 404)
Example #4
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'))
Example #5
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'))
    def test_action_subports(self):
        project_id = TEST_TENANT_ID
        q_ctx = FakeNeutronContext()
        t_ctx = context.get_db_context()
        self._basic_pod_setup()
        fake_plugin = FakePlugin()

        t_trunk, b_trunk = self._prepare_trunk_test(project_id, t_ctx, 'pod_1',
                                                    1, True)

        add_subport_id1 = self._prepare_port_test(project_id,
                                                  t_ctx,
                                                  'pod_1',
                                                  1,
                                                  create_bottom=False)
        add_subport_id2 = self._prepare_port_test(project_id,
                                                  t_ctx,
                                                  'pod_1',
                                                  2,
                                                  create_bottom=False)
        add_subport_id3 = self._prepare_port_test(project_id,
                                                  t_ctx,
                                                  'pod_1',
                                                  3,
                                                  create_bottom=False)
        add_subport_id4 = self._prepare_port_test(project_id,
                                                  t_ctx,
                                                  'pod_1',
                                                  4,
                                                  create_bottom=False)
        add_subport_id5 = self._prepare_port_test(project_id,
                                                  t_ctx,
                                                  'pod_1',
                                                  5,
                                                  create_bottom=False)
        add_subport_id6 = self._prepare_port_test(project_id,
                                                  t_ctx,
                                                  'pod_1',
                                                  6,
                                                  create_bottom=True)
        add_subport_id7 = self._prepare_port_test(project_id,
                                                  t_ctx,
                                                  'pod_1',
                                                  7,
                                                  create_bottom=True)
        add_subport_id8 = self._prepare_port_test(project_id,
                                                  t_ctx,
                                                  'pod_1',
                                                  8,
                                                  create_bottom=False)
        add_subport_id9 = self._prepare_port_test(project_id,
                                                  t_ctx,
                                                  'pod_1',
                                                  9,
                                                  create_bottom=False)

        # Avoid warning: assigned to but never used
        ids = [
            add_subport_id1, add_subport_id2, add_subport_id3, add_subport_id4,
            add_subport_id5, add_subport_id6, add_subport_id7, add_subport_id8,
            add_subport_id9
        ]
        ids.sort()

        remove_subports = {
            'segmentation_type': 'vlan',
            'port_id': uuidutils.generate_uuid(),
            'segmentation_id': 165
        }
        b_trunk['sub_ports'].append(remove_subports)

        add_subports = []
        for _id in xrange(1, 10):
            port_id = eval("add_subport_id%d" % _id)
            subport = {
                'segmentation_type': 'vlan',
                'port_id': port_id,
                'segmentation_id': _id
            }
            add_subports.append(subport)

        fake_plugin.add_subports(q_ctx, t_trunk['id'],
                                 {'sub_ports': add_subports})

        top_subports = TOP_TRUNKS[0]['sub_ports']
        btm_subports = BOTTOM1_TRUNKS[0]['sub_ports']

        except_btm_subports = []
        for subport in b_trunk['sub_ports']:
            if subport['segmentation_id'] == 164:
                except_btm_subports.extend([subport])
        for subport in add_subports:
            subport['trunk_id'] = b_trunk['id']
        except_btm_subports.extend(add_subports)
        six.assertCountEqual(self, btm_subports, except_btm_subports)

        except_top_subports = []
        for subport in t_trunk['sub_ports']:
            if subport['segmentation_id'] == 164:
                except_top_subports.extend([subport])
        for subport in add_subports:
            subport['trunk_id'] = t_trunk['id']
        except_top_subports.extend(add_subports)
        except_btm_subports.extend(add_subports)
        six.assertCountEqual(self, top_subports, except_top_subports)

        self.assertEqual(len(BOTTOM1_PORTS), 10)
        map_filters = [{
            'key': 'resource_type',
            'comparator': 'eq',
            'value': constants.RT_PORT
        }, {
            'key': 'project_id',
            'comparator': 'eq',
            'value': project_id
        }]

        port_mappings = db_api.list_resource_routings(t_ctx, map_filters)
        self.assertEqual(len(port_mappings), 10)
Example #7
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)}
Example #8
0
    def test_post(self, mock_context):
        mock_context.return_value = self.context

        kw_routing = self._prepare_routing_element('subnet')
        id = self.controller.post(**kw_routing)['routing']['id']
        routing = db_api.get_resource_routing(self.context, id)

        self.assertEqual('subnet', routing['resource_type'])

        routings = db_api.list_resource_routings(self.context,
                                                 [{'key': 'resource_type',
                                                   'comparator': 'eq',
                                                   'value':
                                                   'subnet'
                                                   },
                                                  ])
        self.assertEqual(1, len(routings))

        # failure case, only admin can create resource routing
        self.context.is_admin = False
        kw_routing = self._prepare_routing_element('subnet')
        res = self.controller.post(**kw_routing)
        self._validate_error_code(res, 403)

        self.context.is_admin = True

        # failure case, request body not found
        kw_routing1 = {'route':
                       {'top_id': uuidutils.generate_uuid(),
                        'bottom_id': uuidutils.generate_uuid(),
                        }}
        res = self.controller.post(**kw_routing1)
        self._validate_error_code(res, 400)

        # failure case, top_id is not given
        kw_routing2 = self._prepare_routing_element('router')
        kw_routing2['routing'].pop('top_id')
        res = self.controller.post(**kw_routing2)
        self._validate_error_code(res, 400)

        # failure case, top_id is empty
        kw_routing3 = self._prepare_routing_element('router')
        kw_routing3['routing'].update({'top_id': ''})
        res = self.controller.post(**kw_routing3)
        self._validate_error_code(res, 400)

        # failure case, top_id is given value 'None'
        kw_routing4 = self._prepare_routing_element('security_group')
        kw_routing4['routing'].update({'top_id': None})
        res = self.controller.post(**kw_routing4)
        self._validate_error_code(res, 400)

        # failure case, wrong resource type
        kw_routing6 = self._prepare_routing_element('server')
        self.controller.post(**kw_routing6)
        self._validate_error_code(res, 400)

        # failure case, the resource routing already exists
        kw_routing7 = self._prepare_routing_element('router')
        self.controller.post(**kw_routing7)
        res = self.controller.post(**kw_routing7)
        self._validate_error_code(res, 409)
Example #9
0
    def test_post(self, mock_context):
        mock_context.return_value = self.context

        # prepare the foreign key: pod_id
        kw_pod = {'pod': {'region_name': 'pod1', 'az_name': 'az1'}}
        pod_id = pod.PodsController().post(**kw_pod)['pod']['pod_id']

        # a variable used for later test
        project_id = uuidutils.generate_uuid()

        kw_routing = {
            'routing': {
                'top_id': '09fd7cc9-d169-4b5a-88e8-436ecf4d0bfe',
                'bottom_id': 'dc80f9de-abb7-4ec6-ab7a-94f8fd1e20ef',
                'pod_id': pod_id,
                'project_id': project_id,
                'resource_type': 'subnet'
            }
        }
        id = self.controller.post(**kw_routing)['routing']['id']
        routing = db_api.get_resource_routing(self.context, id)
        self.assertEqual('09fd7cc9-d169-4b5a-88e8-436ecf4d0bfe',
                         routing['top_id'])
        self.assertEqual('dc80f9de-abb7-4ec6-ab7a-94f8fd1e20ef',
                         routing['bottom_id'])
        self.assertEqual(pod_id, routing['pod_id'])
        self.assertEqual(project_id, routing['project_id'])
        self.assertEqual('subnet', routing['resource_type'])

        routings = db_api.list_resource_routings(
            self.context, [{
                'key': 'top_id',
                'comparator': 'eq',
                'value': '09fd7cc9-d169-4b5a-'
                '88e8-436ecf4d0bfe'
            }, {
                'key': 'pod_id',
                'comparator': 'eq',
                'value': pod_id
            }], [])
        self.assertEqual(1, len(routings))

        # failure case, only admin can create resource routing
        self.context.is_admin = False
        res = self.controller.post(**kw_routing)
        self._validate_error_code(res, 403)

        self.context.is_admin = True

        # failure case, request body not found
        kw_routing1 = {
            'route': {
                'top_id': '109fd7cc9-d169-4b5a-88e8-436ecf4d0bfe',
                'bottom_id': '2dc80f9de-abb7-4ec6-ab7a-94f8fd1e20ef',
                'pod_id': pod_id,
                'project_id': project_id,
                'resource_type': 'subnet'
            }
        }
        res = self.controller.post(**kw_routing1)
        self._validate_error_code(res, 400)

        # failure case, top_id is not given
        kw_routing2 = {
            'routing': {
                'bottom_id': '2dc80f9de-abb7-4ec6-ab7a-94f8fd1e20ef',
                'pod_id': pod_id,
                'project_id': project_id,
                'resource_type': 'subnet'
            }
        }
        res = self.controller.post(**kw_routing2)
        self._validate_error_code(res, 400)

        # failure case, top_id is empty
        kw_routing3 = {
            'routing': {
                'top_id': '',
                'bottom_id': '2dc80f9de-abb7-4ec6-ab7a-94f8fd1e20ef',
                'pod_id': pod_id,
                'project_id': project_id,
                'resource_type': 'subnet'
            }
        }
        res = self.controller.post(**kw_routing3)
        self._validate_error_code(res, 400)

        # failure case, top_id is given value 'None'
        kw_routing4 = {
            'routing': {
                'top_id': None,
                'bottom_id': '2dc80f9de-abb7-4ec6-ab7a-94f8fd1e20ef',
                'pod_id': pod_id,
                'project_id': project_id,
                'resource_type': 'subnet'
            }
        }
        res = self.controller.post(**kw_routing4)
        self._validate_error_code(res, 400)

        # failure case, wrong resource type
        kw_routing6 = {
            'routing': {
                'top_id': '09fd7cc9-d169-4b5a-88e8-436ecf4d0b09',
                'bottom_id': 'dc80f9de-abb7-4ec6-ab7a-94f8fd1e2031f',
                'pod_id': pod_id,
                'project_id': project_id,
                'resource_type': 'server'
            }
        }
        res = self.controller.post(**kw_routing6)
        self._validate_error_code(res, 400)

        # failure case, the resource routing already exists
        res = self.controller.post(**kw_routing)
        self._validate_error_code(res, 409)
    def test_action_subports(self):
        project_id = TEST_TENANT_ID
        q_ctx = FakeNeutronContext()
        t_ctx = context.get_db_context()
        self._basic_pod_setup()
        fake_plugin = FakePlugin()

        t_trunk, b_trunk = self._prepare_trunk_test(project_id, t_ctx,
                                                    'pod_1', 1, True)

        add_subport_id1 = self._prepare_port_test(project_id, t_ctx, 'pod_1',
                                                  1, create_bottom=False)
        add_subport_id2 = self._prepare_port_test(project_id, t_ctx, 'pod_1',
                                                  2, create_bottom=False)
        add_subport_id3 = self._prepare_port_test(project_id, t_ctx, 'pod_1',
                                                  3, create_bottom=False)
        add_subport_id4 = self._prepare_port_test(project_id, t_ctx, 'pod_1',
                                                  4, create_bottom=False)
        add_subport_id5 = self._prepare_port_test(project_id, t_ctx, 'pod_1',
                                                  5, create_bottom=False)
        add_subport_id6 = self._prepare_port_test(project_id, t_ctx, 'pod_1',
                                                  6, create_bottom=True)
        add_subport_id7 = self._prepare_port_test(project_id, t_ctx, 'pod_1',
                                                  7, create_bottom=True)
        add_subport_id8 = self._prepare_port_test(project_id, t_ctx, 'pod_1',
                                                  8, create_bottom=False)
        add_subport_id9 = self._prepare_port_test(project_id, t_ctx, 'pod_1',
                                                  9, create_bottom=False)

        # Avoid warning: assigned to but never used
        ids = [add_subport_id1, add_subport_id2, add_subport_id3,
               add_subport_id4, add_subport_id5, add_subport_id6,
               add_subport_id7, add_subport_id8, add_subport_id9]
        ids.sort()

        remove_subports = {'segmentation_type': 'vlan',
                           'port_id': uuidutils.generate_uuid(),
                           'segmentation_id': 165}
        b_trunk['sub_ports'].append(remove_subports)

        add_subports = []
        for _id in xrange(1, 10):
            port_id = eval("add_subport_id%d" % _id)
            subport = {
                'segmentation_type': 'vlan',
                'port_id': port_id,
                'segmentation_id': _id}
            add_subports.append(subport)

        fake_plugin.add_subports(q_ctx, t_trunk['id'],
                                 {'sub_ports': add_subports})

        top_subports = TOP_TRUNKS[0]['sub_ports']
        btm_subports = BOTTOM1_TRUNKS[0]['sub_ports']

        except_btm_subports = []
        for subport in b_trunk['sub_ports']:
            if subport['segmentation_id'] == 164:
                except_btm_subports.extend([subport])
        for subport in add_subports:
            subport['trunk_id'] = b_trunk['id']
        except_btm_subports.extend(add_subports)
        six.assertCountEqual(self, btm_subports, except_btm_subports)

        except_top_subports = []
        for subport in t_trunk['sub_ports']:
            if subport['segmentation_id'] == 164:
                except_top_subports.extend([subport])
        for subport in add_subports:
            subport['trunk_id'] = t_trunk['id']
        except_top_subports.extend(add_subports)
        except_btm_subports.extend(add_subports)
        six.assertCountEqual(self, top_subports, except_top_subports)

        self.assertEqual(len(BOTTOM1_PORTS), 10)
        map_filters = [{'key': 'resource_type',
                        'comparator': 'eq',
                        'value': constants.RT_PORT},
                       {'key': 'project_id',
                        'comparator': 'eq',
                        'value': project_id}]

        port_mappings = db_api.list_resource_routings(t_ctx, map_filters)
        self.assertEqual(len(port_mappings), 10)
Example #11
0
    def test_post(self, mock_context):
        mock_context.return_value = self.context

        kw_routing = self._prepare_routing_element('subnet')
        id = self.controller.post(**kw_routing)['routing']['id']
        routing = db_api.get_resource_routing(self.context, id)

        self.assertEqual('subnet', routing['resource_type'])

        routings = db_api.list_resource_routings(self.context,
                                                 [{'key': 'resource_type',
                                                   'comparator': 'eq',
                                                   'value':
                                                   'subnet'
                                                   },
                                                  ])
        self.assertEqual(1, len(routings))

        # failure case, only admin can create resource routing
        self.context.is_admin = False
        kw_routing = self._prepare_routing_element('subnet')
        res = self.controller.post(**kw_routing)
        self._validate_error_code(res, 403)

        self.context.is_admin = True

        # failure case, request body not found
        kw_routing1 = {'route':
                       {'top_id': uuidutils.generate_uuid(),
                        'bottom_id': uuidutils.generate_uuid(),
                        }}
        res = self.controller.post(**kw_routing1)
        self._validate_error_code(res, 400)

        # failure case, top_id is not given
        kw_routing2 = self._prepare_routing_element('router')
        kw_routing2['routing'].pop('top_id')
        res = self.controller.post(**kw_routing2)
        self._validate_error_code(res, 400)

        # failure case, top_id is empty
        kw_routing3 = self._prepare_routing_element('router')
        kw_routing3['routing'].update({'top_id': ''})
        res = self.controller.post(**kw_routing3)
        self._validate_error_code(res, 400)

        # failure case, top_id is given value 'None'
        kw_routing4 = self._prepare_routing_element('security_group')
        kw_routing4['routing'].update({'top_id': None})
        res = self.controller.post(**kw_routing4)
        self._validate_error_code(res, 400)

        # failure case, wrong resource type
        kw_routing6 = self._prepare_routing_element('server')
        self.controller.post(**kw_routing6)
        self._validate_error_code(res, 400)

        # failure case, the resource routing already exists
        kw_routing7 = self._prepare_routing_element('router')
        self.controller.post(**kw_routing7)
        res = self.controller.post(**kw_routing7)
        self._validate_error_code(res, 409)
Example #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'))

        # 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'))
Example #13
0
    def test_post(self, mock_context):
        mock_context.return_value = self.context

        # prepare the foreign key: pod_id, project_id
        kw_pod = {'pod': {'pod_name': 'pod1', 'az_name': 'az1'}}
        pod_id = pod.PodsController().post(**kw_pod)['pod']['pod_id']

        kw_binding = {'pod_binding': {'tenant_id': '01', 'pod_id': pod_id}}
        project_id = pod.BindingsController().post(**kw_binding)[
            'pod_binding']['tenant_id']

        kw_routing = {'routing':
                      {'top_id': '09fd7cc9-d169-4b5a-88e8-436ecf4d0bfe',
                       'bottom_id': 'dc80f9de-abb7-4ec6-ab7a-94f8fd1e20ef',
                       'pod_id': pod_id,
                       'project_id': project_id,
                       'resource_type': 'subnet'
                       }}
        id = self.controller.post(**kw_routing)['routing']['id']
        routing = db_api.get_resource_routing(self.context, id)
        self.assertEqual(routing['top_id'],
                         '09fd7cc9-d169-4b5a-88e8-436ecf4d0bfe')
        self.assertEqual(routing['bottom_id'],
                         'dc80f9de-abb7-4ec6-ab7a-94f8fd1e20ef')
        self.assertEqual(routing['pod_id'], pod_id)
        self.assertEqual(routing['project_id'], project_id)
        self.assertEqual(routing['resource_type'], 'subnet')

        routings = db_api.list_resource_routings(self.context,
                                                 [{'key': 'top_id',
                                                   'comparator': 'eq',
                                                   'value':
                                                   '09fd7cc9-d169-4b5a-'
                                                   '88e8-436ecf4d0bfe'
                                                   },
                                                  {'key': 'pod_id',
                                                   'comparator': 'eq',
                                                   'value': pod_id}
                                                  ], [])
        self.assertEqual(len(routings), 1)

        # failure case, only admin can create resource routing
        self.context.is_admin = False
        res = self.controller.post(**kw_routing)
        self._validate_error_code(res, 403)

        self.context.is_admin = True

        # failure case, request body not found
        kw_routing1 = {'route':
                       {'top_id': '109fd7cc9-d169-4b5a-88e8-436ecf4d0bfe',
                        'bottom_id': '2dc80f9de-abb7-4ec6-ab7a-94f8fd1e20ef',
                        'pod_id': pod_id,
                        'project_id': project_id,
                        'resource_type': 'subnet'
                        }}
        res = self.controller.post(**kw_routing1)
        self._validate_error_code(res, 400)

        # failure case, top_id is not given
        kw_routing2 = {'routing':
                       {'bottom_id': '2dc80f9de-abb7-4ec6-ab7a-94f8fd1e20ef',
                        'pod_id': pod_id,
                        'project_id': project_id,
                        'resource_type': 'subnet'
                        }}
        res = self.controller.post(**kw_routing2)
        self._validate_error_code(res, 400)

        # failure case, top_id is empty
        kw_routing3 = {'routing':
                       {'top_id': '',
                        'bottom_id': '2dc80f9de-abb7-4ec6-ab7a-94f8fd1e20ef',
                        'pod_id': pod_id,
                        'project_id': project_id,
                        'resource_type': 'subnet'
                        }}
        res = self.controller.post(**kw_routing3)
        self._validate_error_code(res, 400)

        # failure case, top_id is given value 'None'
        kw_routing4 = {'routing':
                       {'top_id': None,
                        'bottom_id': '2dc80f9de-abb7-4ec6-ab7a-94f8fd1e20ef',
                        'pod_id': pod_id,
                        'project_id': project_id,
                        'resource_type': 'subnet'
                        }}
        res = self.controller.post(**kw_routing4)
        self._validate_error_code(res, 400)

        # failure case, the pod_id and the project_id should be bound
        kw_pod2 = {'pod': {'pod_name': 'pod2', 'az_name': 'az1'}}
        pod_id2 = pod.PodsController().post(**kw_pod2)['pod']['pod_id']

        # the tenant_id binds with pod_id rather than pod_id2
        kw_binding2 = {'pod_binding': {'tenant_id': '02', 'pod_id': pod_id}}
        project_id2 = pod.BindingsController().post(**kw_binding2)[
            'pod_binding']['tenant_id']

        kw_routing5 = {'routing':
                       {'top_id': '09fd7cc9-d169-4b5a-88e8-436ecf4d0bfe',
                        'bottom_id': 'dc80f9de-abb7-4ec6-ab7a-94f8fd1e20ef',
                        'pod_id': pod_id2,
                        'project_id': project_id2,
                        'resource_type': 'subnet'
                        }}
        res = self.controller.post(**kw_routing5)
        self._validate_error_code(res, 400)

        # failure case, wrong resource type
        kw_routing6 = {'routing':
                       {'top_id': '09fd7cc9-d169-4b5a-88e8-436ecf4d0b09',
                        'bottom_id': 'dc80f9de-abb7-4ec6-ab7a-94f8fd1e2031f',
                        'pod_id': pod_id,
                        'project_id': project_id,
                        'resource_type': 'server'
                        }}
        res = self.controller.post(**kw_routing6)
        self._validate_error_code(res, 400)

        # failure case, the resource routing already exists
        res = self.controller.post(**kw_routing)
        self._validate_error_code(res, 409)
Example #14
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'))