Ejemplo n.º 1
0
    def _create_router(self, fmt, tenant_id, name=None,
                       admin_state_up=None, set_context=False,
                       arg_list=None, **kwargs):
        data = {'router': {'tenant_id': tenant_id}}
        if name:
            data['router']['name'] = name
        if admin_state_up:
            data['router']['admin_state_up'] = admin_state_up
        for arg in (('admin_state_up', 'tenant_id') + (arg_list or ())):
            # Arg must be present and not empty
            if arg in kwargs and kwargs[arg]:
                data['router'][arg] = kwargs[arg]
        data['router']['service_router'] = True
        router_req = self.new_create_request('routers', data, fmt)
        if set_context and tenant_id:
            # create a specific auth context for this request
            router_req.environ['neutron.context'] = context.Context(
                '', tenant_id)

        return router_req.get_response(self.ext_api)
Ejemplo n.º 2
0
 def _routes_update_prepare(self,
                            router_id,
                            subnet_id,
                            port_id,
                            routes,
                            skip_add=False,
                            tenant_id=None):
     if not skip_add:
         self._router_interface_action('add',
                                       router_id,
                                       subnet_id,
                                       port_id,
                                       tenant_id=None)
     ctxt = context.Context('', tenant_id) if tenant_id else None
     self._update('routers',
                  router_id, {'router': {
                      'routes': routes
                  }},
                  neutron_context=ctxt)
     return self._show('routers', router_id)
Ejemplo n.º 3
0
 def test_port_vnic_type(self):
     vnic_arg = {portbindings.VNIC_TYPE: self.vnic_type}
     with self.port(name='name',
                    arg_list=(portbindings.VNIC_TYPE, ),
                    **vnic_arg) as port:
         port_id = port['port']['id']
         # Check a response of create_port
         self._check_response_portbindings_vnic_type(port['port'])
         # Check a response of get_port
         ctx = context.get_admin_context()
         port = self._show('ports', port_id, neutron_context=ctx)['port']
         self._check_response_portbindings_vnic_type(port)
         # By default user is admin - now test non admin user
         ctx = context.Context(user_id=None,
                               tenant_id=self._tenant_id,
                               is_admin=False,
                               read_deleted="no")
         non_admin_port = self._show('ports', port_id,
                                     neutron_context=ctx)['port']
         self._check_response_portbindings_vnic_type(non_admin_port)
Ejemplo n.º 4
0
 def setUp(self):
     super(PolicyTestCase, self).setUp()
     # NOTE(vish): preload rules to circumvent reloading from file
     rules = {
         "true": '@',
         "example:allowed": '@',
         "example:denied": '!',
         "example:get_http": "http:http://www.example.com",
         "example:my_file": "role:compute_admin or tenant_id:%(tenant_id)s",
         "example:early_and_fail": "! and @",
         "example:early_or_success": "@ or !",
         "example:lowercase_admin": "role:admin or role:sysadmin",
         "example:uppercase_admin": "role:ADMIN or role:sysadmin",
     }
     policy.refresh()
     # NOTE(vish): then overload underlying rules
     policy.set_rules(
         dict((k, common_policy.parse_rule(v)) for k, v in rules.items()))
     self.context = context.Context('fake', 'fake', roles=['member'])
     self.target = {}
Ejemplo n.º 5
0
    def test_update_port_non_admin_does_not_show_queue_id(self):
        body = {'qos_queue': {'tenant_id': 'not_admin',
                              'name': 'foo', 'min': 20, 'max': 20}}
        res = self._create_qos_queue('json', body, tenant_id='not_admin')
        q1 = self.deserialize('json', res)
        res = self._create_network('json', 'net1', True,
                                   arg_list=(ext_qos.QUEUE,),
                                   tenant_id='not_admin',
                                   queue_id=q1['qos_queue']['id'])

        net1 = self.deserialize('json', res)
        res = self._create_port('json', net1['network']['id'],
                                tenant_id='not_admin', set_context=True)
        port = self.deserialize('json', res)
        device_id = "00fff4d0-e4a8-4a3a-8906-4c4cdafb59f1"
        data = {'port': {'device_id': device_id}}
        neutron_context = context.Context('', 'not_admin')
        port = self._update('ports', port['port']['id'], data,
                            neutron_context=neutron_context)
        self.assertNotIn(ext_qos.QUEUE, port['port'])
Ejemplo n.º 6
0
    def test_get_tenant_quotas_arg(self):
        """Call neutron.db.quota_db.DbQuotaDriver._get_quotas."""

        driver = quota_db.DbQuotaDriver()
        ctx = context.Context('', 'bar')

        foo_quotas = {'network': 5}
        default_quotas = {'network': 10}
        target_tenant = 'foo'

        with mock.patch.object(quota_db.DbQuotaDriver,
                               'get_tenant_quotas',
                               return_value=foo_quotas) as get_tenant_quotas:

            quotas = driver._get_quotas(ctx, target_tenant, default_quotas,
                                        ['network'])

            self.assertEqual(quotas, foo_quotas)
            get_tenant_quotas.assert_called_once_with(ctx, default_quotas,
                                                      target_tenant)
 def test_get_hosting_device_resources_by_device_id(self):
     tenant_id = 'some_tenant_id'
     ctx = context.Context('', tenant_id, is_admin=True)
     plugging_driver = HwVLANTrunkingPlugDriver()
     mgmt_context = {'mgmt_nw_id': None}
     res = plugging_driver.create_hosting_device_resources(
         ctx, "some_id", tenant_id, mgmt_context, 1)
     # update attributes of created ports to fake what Nova updates
     hd_uuid = 'hd_uuid1'
     update_spec = {'port': {'device_id': hd_uuid, 'device_owner': 'nova'}}
     for hd_port in self._list('ports')['ports']:
         self._update('ports', hd_port['id'], update_spec)
     # ports that should not be returned
     with self.port(), self.port(device_id='uuid2'), self.port(
             tenant_id=tenant_id), self.port(tenant_id=tenant_id,
                                             device_owner='other_uuid'):
         res_get = plugging_driver.get_hosting_device_resources(
             ctx, hd_uuid, 'some_id', tenant_id, None)
         self.assertIsNone(res_get['mgmt_port'])
         self.assertEqual(len(res), 1)
Ejemplo n.º 8
0
 def _update_gateway_device(self, fmt, gateway_device_id,
                            connector_type=None, connector_ip=None,
                            client_certificate=None, name=None,
                            set_context=False, tenant_id=None):
     data = {self.dev_resource: {}}
     if connector_type:
         data[self.dev_resource]['connector_type'] = connector_type
     if connector_ip:
         data[self.dev_resource]['connector_ip'] = connector_ip
     if client_certificate:
         data[self.dev_resource]['client_certificate'] = client_certificate
     if name:
         data[self.dev_resource]['name'] = name
     gw_dev_req = self.new_update_request(networkgw.GATEWAY_DEVICES,
                                          data, gateway_device_id, fmt)
     if (set_context and tenant_id):
         # create a specific auth context for this request
         gw_dev_req.environ['neutron.context'] = context.Context(
             '', tenant_id)
     return gw_dev_req.get_response(self.ext_api)
Ejemplo n.º 9
0
 def _process_router_add(self, ri):
     """On router add, get fw with rules from plugin and update driver."""
     LOG.debug("Process router add, router_id: '%s'", ri.router['id'])
     routers = []
     routers.append(ri.router)
     router_info_list = self._get_router_info_list_for_tenant(
         routers,
         ri.router['tenant_id'])
     if router_info_list:
         # Get the firewall with rules
         # for the tenant the router is on.
         ctx = context.Context('', ri.router['tenant_id'])
         fw_list = self.fwplugin_rpc.get_firewalls_for_tenant(ctx)
         LOG.debug("Process router add, fw_list: '%s'",
                   [fw['id'] for fw in fw_list])
         for fw in fw_list:
             self._invoke_driver_for_sync_from_plugin(
                 ctx,
                 router_info_list,
                 fw)
Ejemplo n.º 10
0
    def setUp(self):
        plugin = 'neutron.tests.unit.test_l3_plugin.TestL3NatIntPlugin'
        service_plugins = {
            'metering_plugin_name': METERING_SERVICE_PLUGIN_KLASS
        }
        ext_mgr = MeteringTestExtensionManager()
        super(TestMeteringPlugin, self).setUp(plugin=plugin,
                                              ext_mgr=ext_mgr,
                                              service_plugins=service_plugins)

        self.uuid = '654f6b9d-0f36-4ae5-bd1b-01616794ca60'

        uuid = 'neutron.openstack.common.uuidutils.generate_uuid'
        self.uuid_patch = mock.patch(uuid, return_value=self.uuid)
        self.mock_uuid = self.uuid_patch.start()

        self.tenant_id = 'a7e61382-47b8-4d40-bae3-f95981b5637b'
        self.ctx = context.Context('', self.tenant_id, is_admin=True)
        self.context_patch = mock.patch('neutron.context.Context',
                                        return_value=self.ctx)
        self.mock_context = self.context_patch.start()

        self.topic = 'metering_agent'

        add = ('neutron.api.rpc.agentnotifiers.' +
               'metering_rpc_agent_api.MeteringAgentNotifyAPI' +
               '.add_metering_label')
        self.add_patch = mock.patch(add)
        self.mock_add = self.add_patch.start()

        remove = ('neutron.api.rpc.agentnotifiers.' +
                  'metering_rpc_agent_api.MeteringAgentNotifyAPI' +
                  '.remove_metering_label')
        self.remove_patch = mock.patch(remove)
        self.mock_remove = self.remove_patch.start()

        update = ('neutron.api.rpc.agentnotifiers.' +
                  'metering_rpc_agent_api.MeteringAgentNotifyAPI' +
                  '.update_metering_label_rules')
        self.update_patch = mock.patch(update)
        self.mock_update = self.update_patch.start()
Ejemplo n.º 11
0
    def test_update_port_add_remove_security_group(self):
        get_port_func = ('neutron.db.db_base_plugin_v2.'
                         'NeutronDbPluginV2.get_port')
        with mock.patch(get_port_func) as mock_get_port:
            mock_get_port.return_value = {
                ext_sg.SECURITYGROUPS: ["sg1", "sg2"],
                "admin_state_up": True,
                "fixed_ips": "fake_ip",
                "network_id": "fake_id"
            }

            update_port_func = ('neutron.db.db_base_plugin_v2.'
                                'NeutronDbPluginV2.update_port')
            with mock.patch(update_port_func) as mock_update_port:
                mock_update_port.return_value = {
                    ext_sg.SECURITYGROUPS: ["sg2", "sg3"],
                    "admin_state_up": True,
                    "fixed_ips": "fake_ip",
                    "network_id": "fake_id"
                }

                fake_func = ('neutron.plugins.openvswitch.'
                             'ovs_db_v2.get_network_binding')
                with mock.patch(fake_func) as mock_func:

                    class MockBinding:
                        network_type = "fake"
                        segmentation_id = "fake"
                        physical_network = "fake"

                    mock_func.return_value = MockBinding()

                    ctx = context.Context('', 'somebody')
                    self.update_port(
                        ctx, "id",
                        {"port": {
                            ext_sg.SECURITYGROUPS: ["sg2", "sg3"]
                        }})

                    sgmu = self.notifier.security_groups_member_updated
                    sgmu.assert_called_with(ctx, set(['sg1', 'sg3']))
Ejemplo n.º 12
0
 def process_services_sync(self, ctx):
     """On RPC issues sync with plugin and apply the sync data."""
     # avoid msg to plugin when fwaas is not configured
     if not self.fwaas_enabled:
         return
     try:
         # get the list of tenants with firewalls configured
         # from the plugin
         tenant_ids = self.fwplugin_rpc.get_tenants_with_firewalls(ctx)
         LOG.debug(_("Tenants with Firewalls: '%s'"), tenant_ids)
         for tenant_id in tenant_ids:
             ctx = context.Context('', tenant_id)
             fw_list = self.fwplugin_rpc.get_firewalls_for_tenant(ctx)
             # if fw present on tenant
             if fw_list:
                 for fw in fw_list:
                     # no need to apply sync data for ACTIVE fw
                     if fw['status'] != constants.ACTIVE:
                         info_list = self._get_router_info_list_for_tenant(
                             [r for r in fw['router_ids']],
                             tenant_id)
                         if info_list:
                             LOG.debug(_("Router List: '%s'"),
                                       [ri.router['id'] for ri in
                                           info_list])
                             LOG.debug(_("fw_list: '%s'"),
                                       [fw['id'] for fw in fw_list])
                             # apply sync data on fw for this tenant
                             # fw, routers present on this host for tenant
                             # install
                             LOG.debug(_("Apply fw on Router List: '%s'"),
                                       [ri.router['id']
                                           for ri in info_list])
                             self._invoke_driver_for_sync_from_plugin(
                                 ctx,
                                 info_list,
                                 fw)
         self.services_sync = False
     except Exception:
         LOG.exception(_("Failed fwaas process services sync"))
         self.services_sync = True
Ejemplo n.º 13
0
    def _test_router_remove_from_agent_on_vm_port_deletion(
            self, non_admin_port=False):
        # register l3 agent in dvr mode in addition to existing dvr_snat agent
        HOST = 'host1'
        non_admin_tenant = 'tenant1'
        dvr_agent = helpers.register_l3_agent(
            host=HOST, agent_mode=constants.L3_AGENT_MODE_DVR)
        router = self._create_router()
        with self.network(shared=True) as net,\
                self.subnet(network=net) as subnet,\
                self.port(subnet=subnet,
                          device_owner=DEVICE_OWNER_COMPUTE,
                          tenant_id=non_admin_tenant,
                          set_context=non_admin_port) as port:
            self.core_plugin.update_port(
                self.context, port['port']['id'],
                {'port': {
                    portbindings.HOST_ID: HOST
                }})
            self.l3_plugin.add_router_interface(
                self.context, router['id'],
                {'subnet_id': subnet['subnet']['id']})

            # router should be scheduled to agent on HOST
            agents = self.l3_plugin.list_l3_agents_hosting_router(
                self.context, router['id'])
            self.assertEqual(1, len(agents['agents']))
            self.assertEqual(dvr_agent['id'], agents['agents'][0]['id'])

            notifier = self.l3_plugin.agent_notifiers[constants.AGENT_TYPE_L3]
            with mock.patch.object(notifier,
                                   'router_removed_from_agent') as remove_mock:
                ctx = context.Context(
                    '', non_admin_tenant) if non_admin_port else self.context
                self._delete('ports', port['port']['id'], neutron_context=ctx)
                # now when port is deleted the router should be unscheduled
                agents = self.l3_plugin.list_l3_agents_hosting_router(
                    self.context, router['id'])
                self.assertEqual(0, len(agents['agents']))
                remove_mock.assert_called_once_with(mock.ANY, router['id'],
                                                    HOST)
Ejemplo n.º 14
0
    def __call__(self, req):
        # Determine the user ID
        user_id = req.headers.get('X_USER_ID')
        if not user_id:
            LOG.debug(_("X_USER_ID is not found in request"))
            return webob.exc.HTTPUnauthorized()

        # Determine the tenant
        tenant_id = req.headers.get('X_PROJECT_ID')

        # Suck out the roles
        roles = [r.strip() for r in req.headers.get('X_ROLES', '').split(',')]

        # Human-friendly names
        tenant_name = req.headers.get('X_PROJECT_NAME')
        user_name = req.headers.get('X_USER_NAME')

        # Use request_id if already set
        req_id = req.environ.get(request_id.ENV_REQUEST_ID)

        # Get the auth token
        auth_token = req.headers.get('X_AUTH_TOKEN',
                                     req.headers.get('X_STORAGE_TOKEN'))

        ### add by xm at 2015.9.22
        gc_resource_type = req.headers.get('G_AUTH_RESOURCETYPE', 1)

        # Create a context with the authentication data
        ctx = context.Context(user_id,
                              tenant_id,
                              roles=roles,
                              user_name=user_name,
                              tenant_name=tenant_name,
                              request_id=req_id,
                              auth_token=auth_token,
                              gc_resource_type=gc_resource_type)

        # Inject the context...
        req.environ['neutron.context'] = ctx

        return self.application
Ejemplo n.º 15
0
    def setUp(self):
        ml2_config.cfg.CONF.set_override('mechanism_drivers',
                                         ['logger', 'test', 'fake_agent'],
                                         'ml2')

        super(TestBagpipeServiceDriverCallbacks, self).setUp(self._plugin_name)

        self.port_create_status = 'DOWN'
        self.plugin = manager.NeutronManager.get_plugin()
        self.plugin.start_rpc_listeners()

        self.bagpipe_driver = self.bgpvpn_plugin.driver

        mock.patch.object(self.bgpvpn_plugin.driver,
                          '_retrieve_bgpvpn_network_info_for_port',
                          return_value=BGPVPN_INFO).start()

        self.mock_attach_rpc = self.mocked_bagpipeAPI.attach_port_on_bgpvpn
        self.mock_detach_rpc = self.mocked_bagpipeAPI.detach_port_from_bgpvpn

        self.ctxt = n_context.Context('fake_user', 'fake_project')
Ejemplo n.º 16
0
 def test_show_routertype_non_admin(self):
     with self.hosting_device_template() as hdt:
         hdt_id = hdt['hosting_device_template']['id']
         tenant_id = hdt['hosting_device_template']['tenant_id']
         with self.routertype(hdt_id) as rt:
             rt_id = rt['routertype']['id']
             non_admin_ctx = n_context.Context('', tenant_id)
             req = self._req('GET',
                             'routertypes',
                             None,
                             self.fmt,
                             id=rt_id,
                             context=non_admin_ctx)
             res = self.deserialize(self.fmt,
                                    req.get_response(self.ext_api))
             attrs = self._get_non_admin_routertype_attr(hdt_id)
             attrs['id'] = rt_id
             attrs['tenant_id'] = tenant_id
             self.assertEqual(len(res['routertype']), len(attrs))
             for k, v in six.iteritems(attrs):
                 self.assertEqual(res['routertype'][k], v)
Ejemplo n.º 17
0
    def __call__(self, req):
        user_id = req.headers.get('X_USER_ID', '')

        # Determine the tenant
        tenant_id = req.headers.get('X_PROJECT_ID')

        # Suck out the roles
        roles = [r.strip() for r in req.headers.get('X_ROLES', '').split(',')]

        # Human-friendly names
        tenant_name = req.headers.get('X_PROJECT_NAME')
        user_name = req.headers.get('X_USER_NAME')

        # Create a context with the authentication data
        ctx = context.Context(user_id,
                              tenant_id,
                              roles=roles,
                              user_name=user_name,
                              tenant_name=tenant_name)
        req.environ['neutron.context'] = ctx
        return self.application
Ejemplo n.º 18
0
    def setUp(self, plugin=None):
        self.mocked_bagpipeAPI = mock.patch(
            'networking_bagpipe.agent.bgpvpn.rpc_client'
            '.BGPVPNAgentNotifyApi').start().return_value

        provider = ('networking_bgpvpn.neutron.services.service_drivers.'
                    'bagpipe.bagpipe.BaGPipeBGPVPNDriver')
        super(TestBagpipeCommon, self).setUp(service_provider=provider,
                                             core_plugin=plugin)

        self.ctxt = n_context.Context('fake_user', 'fake_project')

        n_dict = {"name": "netfoo",
                  "tenant_id": "fake_project",
                  "admin_state_up": True,
                  "router:external": True,
                  "shared": True}

        self.external_net = {'network':
                             self.plugin.create_network(self.ctxt,
                                                        {'network': n_dict})}
Ejemplo n.º 19
0
 def test_update_firewall_shared_fails_for_non_admin(self):
     ctx = context.get_admin_context()
     with self.router(name='router1', admin_state_up=True,
         tenant_id=self._tenant_id) as router1:
         with self.firewall_policy() as fwp:
             fwp_id = fwp['firewall_policy']['id']
             with self.firewall(
                 firewall_policy_id=fwp_id,
                 admin_state_up=test_db_firewall.ADMIN_STATE_UP,
                 tenant_id='noadmin',
                 router_ids=[router1['router']['id']]
             ) as firewall:
                 fw_id = firewall['firewall']['id']
                 self.callbacks.set_firewall_status(ctx, fw_id,
                                                const.ACTIVE)
                 data = {'firewall': {'shared': True}}
                 req = self.new_update_request(
                     'firewalls', data, fw_id,
                     context=context.Context('', 'noadmin'))
                 res = req.get_response(self.ext_api)
                 self.assertEqual(exc.HTTPForbidden.code, res.status_int)
Ejemplo n.º 20
0
 def test_policy_404(self):
     with self.subnet(cidr='12.0.0.0/24') as public_sub:
         self._set_net_external(public_sub['subnet']['network_id'])
         fip = self._make_floatingip(self.fmt,
                                     public_sub['subnet']['network_id'])
         policy.reset()
         policy.init()
         rules = {"delete_floatingip": "role:admin_only"}
         common_policy.set_rules(
             common_policy.Rules(
                 dict((k, common_policy.parse_rule(v))
                      for k, v in rules.items())))
         fip_id = fip['floatingip']['id']
         self.context = context.Context('fake', 'fake', roles=['member'])
         req = self.new_delete_request('floatingips', fip_id)
         req.environ['neutron.context'] = self.context
         res = req.get_response(self._api_for_resource('floatingips'))
         self.assertEqual(404, res.status_int)
         policy.reset()
         policy.init()
         self._delete('floatingips', fip_id)
Ejemplo n.º 21
0
    def setUp(self, plugin=PLUGIN_NAME, ext_mgr=None, service_plugins=None):
        driver_mgr.QosServiceNotificationDriverManager = mock.Mock()
        super(TestQosOvnPlugin, self).setUp(plugin=plugin,
                                            ext_mgr=ext_mgr,
                                            service_plugins={"qos": "qos"})

        self.qos_policy_id1 = uuidutils.generate_uuid()
        self.tenant_id = "tenant_id"
        self.ctxt = context.Context("", self.tenant_id)
        self.policy1 = self._create_qos_policy(self.ctxt, self.qos_policy_id1)
        qos_policy.QosPolicy.get_object = mock.MagicMock(
            return_value=self.policy1)
        qos_api.create_policy_network_binding = mock.Mock()
        qos_api.delete_policy_network_binding = mock.Mock()
        qos_api.create_policy_port_binding = mock.Mock()
        qos_api.delete_policy_port_binding = mock.Mock()
        QosCoreResourceExtension.extract_fields = mock.MagicMock(
            side_effect=lambda resource_type, resource:
            {qos_consts.QOS_POLICY_ID: self.policy1.id})

        qos_rule.get_rules = mock.MagicMock(side_effect=self._rules_of_policy)
Ejemplo n.º 22
0
 def _process_router_add(self, ri):
     """On router add, get opt with rules from plugin and update driver."""
     LOG.debug("Process router add, router_id: '%s'", ri.router['id'])
     router_ids = ri.router['id']
     router_info_list = self._get_router_info_list_for_tenant(
         [router_ids], ri.router['tenant_id'])
     if router_info_list:
         # Get the optimizer with rules
         # for the tenant the router is on.
         ctx = context.Context('', ri.router['tenant_id'])
         opt_list = self.optplugin_rpc.get_optimizers_for_tenant(ctx)
         for opt in opt_list:
             if self._has_router_insertion_fields(opt):
                 # if router extension present apply only if router in opt
                 if (not (router_ids in opt['add-router-ids'])
                         and not (router_ids in opt['del-router-ids'])):
                     continue
             self._invoke_driver_for_sync_from_plugin(
                 ctx, router_info_list, opt)
             # router can be present only on one opt
             return
Ejemplo n.º 23
0
 def _process_router_add(self, router):
     """On router add, get fw with rules from plugin and update driver."""
     LOG.debug("Process router add, router_id: '%s'", router['id'])
     router_ids = router['id']
     router_info_list = self._get_router_info_list_for_tenant(
         [router_ids], router['tenant_id'])
     if router_info_list:
         # Get the firewall with rules
         # for the tenant the router is on.
         ctx = context.Context('', router['tenant_id'])
         fw_list = self.fwplugin_rpc.get_firewalls_for_tenant(ctx)
         for fw in fw_list:
             if self._has_router_insertion_fields(fw):
                 # if router extension present apply only if router in fw
                 if (not (router_ids in fw['add-router-ids'])
                         and not (router_ids in fw['del-router-ids'])):
                     continue
             self._invoke_driver_for_sync_from_plugin(
                 ctx, router_info_list, fw)
             # router can be present only on one fw
             return
Ejemplo n.º 24
0
    def _create_address_scope(self,
                              fmt,
                              expected_res_status=None,
                              admin=False,
                              **kwargs):
        address_scope = {'address_scope': {}}
        for k, v in kwargs.items():
            address_scope['address_scope'][k] = str(v)

        address_scope_req = self.new_create_request('address-scopes',
                                                    address_scope, fmt)

        if not admin:
            neutron_context = context.Context(
                '', kwargs.get('tenant_id', self._tenant_id))
            address_scope_req.environ['neutron.context'] = neutron_context

        address_scope_res = address_scope_req.get_response(self.ext_api)
        if expected_res_status:
            self.assertEqual(address_scope_res.status_int, expected_res_status)
        return address_scope_res
Ejemplo n.º 25
0
 def _create_network_gateway(self,
                             fmt,
                             tenant_id,
                             name=None,
                             devices=None,
                             arg_list=None,
                             **kwargs):
     data = {self.resource: {'tenant_id': tenant_id, 'devices': devices}}
     if name:
         data[self.resource]['name'] = name
     for arg in arg_list or ():
         # Arg must be present and not empty
         if arg in kwargs and kwargs[arg]:
             data[self.resource][arg] = kwargs[arg]
     nw_gw_req = self.new_create_request(networkgw.COLLECTION_NAME, data,
                                         fmt)
     if (kwargs.get('set_context') and tenant_id):
         # create a specific auth context for this request
         nw_gw_req.environ['neutron.context'] = context.Context(
             '', tenant_id)
     return nw_gw_req.get_response(self.ext_api)
 def test_update_port_security_off_shared_network(self):
     with self.network(shared=True) as net:
         with self.subnet(network=net):
             res = self._create_port('json',
                                     net['network']['id'],
                                     tenant_id='not_network_owner',
                                     set_context=True)
             port = self.deserialize('json', res)
             # remove security group on port
             update_port = {
                 'port': {
                     ext_sg.SECURITYGROUPS: None,
                     psec.PORTSECURITY: False
                 }
             }
             req = self.new_update_request('ports', update_port,
                                           port['port']['id'])
             req.environ['neutron.context'] = context.Context(
                 '', 'not_network_owner')
             res = req.get_response(self.api)
             self.assertEqual(res.status_int, exc.HTTPForbidden.code)
Ejemplo n.º 27
0
 def test_update_port_security_off_shared_network(self):
     with self.network(shared=True, do_delete=False) as net:
         with self.subnet(network=net, do_delete=False):
             res = self._create_port('json', net['network']['id'],
                                     tenant_id='not_network_owner',
                                     set_context=True)
             port = self.deserialize('json', res)
             # remove security group on port
             update_port = {'port': {ext_sg.SECURITYGROUPS: None,
                                     psec.PORTSECURITY: False}}
             req = self.new_update_request('ports', update_port,
                                           port['port']['id'])
             req.environ['neutron.context'] = context.Context(
                 '', 'not_network_owner')
             res = req.get_response(self.api)
             # TODO(salvatore-orlando): Expected error is 404 because
             # the current API controller always returns this error
             # code for any policy check failures on update.
             # It should be 404 when the caller cannot access the whole
             # resource, and 403 when it cannot access a single attribute
             self.assertEqual(res.status_int, 404)
Ejemplo n.º 28
0
    def setUp(self, plugin_str=None, service_plugins=None, scheduler=None):
        if not plugin_str:
            plugin_str = ('neutron.tests.unit.test_l3_plugin.'
                          'TestL3NatIntAgentSchedulingPlugin')

        if not service_plugins:
            service_plugins = {
                'metering_plugin_name': METERING_SERVICE_PLUGIN_KLASS
            }

        if not scheduler:
            scheduler = plugin_str

        ext_mgr = MeteringTestExtensionManager()
        super(TestMeteringPluginL3AgentScheduler,
              self).setUp(plugin=plugin_str,
                          ext_mgr=ext_mgr,
                          service_plugins=service_plugins)

        self.uuid = '654f6b9d-0f36-4ae5-bd1b-01616794ca60'

        uuid = 'neutron.openstack.common.uuidutils.generate_uuid'
        self.uuid_patch = mock.patch(uuid, return_value=self.uuid)
        self.mock_uuid = self.uuid_patch.start()

        cast = 'neutron.common.rpc.RpcProxy.cast'
        self.cast_patch = mock.patch(cast)
        self.mock_cast = self.cast_patch.start()

        self.tenant_id = 'a7e61382-47b8-4d40-bae3-f95981b5637b'
        self.ctx = context.Context('', self.tenant_id, is_admin=True)
        self.context_patch = mock.patch('neutron.context.Context',
                                        return_value=self.ctx)
        self.mock_context = self.context_patch.start()

        self.l3routers_patch = mock.patch(scheduler +
                                          '.get_l3_agents_hosting_routers')
        self.l3routers_mock = self.l3routers_patch.start()

        self.topic = 'metering_agent'
Ejemplo n.º 29
0
    def setUp(self):
        super(NeutronPolicyTestCase, self).setUp()
        policy.refresh()
        # Add Fake resources to RESOURCE_ATTRIBUTE_MAP
        attributes.RESOURCE_ATTRIBUTE_MAP.update(FAKE_RESOURCES)
        self._set_rules()

        def remove_fake_resource():
            del attributes.RESOURCE_ATTRIBUTE_MAP["%ss" % FAKE_RESOURCE_NAME]

        self.patcher = mock.patch.object(neutron.policy,
                                         'init',
                                         new=self.fakepolicyinit)
        self.patcher.start()
        self.addCleanup(remove_fake_resource)
        self.context = context.Context('fake', 'fake', roles=['user'])
        plugin_klass = importutils.import_class(
            "neutron.db.db_base_plugin_v2.NeutronDbPluginV2")
        self.manager_patcher = mock.patch('neutron.manager.NeutronManager')
        fake_manager = self.manager_patcher.start()
        fake_manager_instance = fake_manager.return_value
        fake_manager_instance.plugin = plugin_klass()
    def _update_resource(self,
                         id,
                         type,
                         expected_res_status=None,
                         is_admin_context=False,
                         api=None,
                         **kwargs):
        plural = get_resource_plural(type)
        data = {type: kwargs}
        tenant_id = kwargs.pop('tenant_id', self._tenant_id)
        # Create PT with bound port
        req = self.new_update_request(plural, data, id, self.fmt)
        req.environ['neutron.context'] = context.Context(
            '', tenant_id if not is_admin_context else self._tenant_id,
            is_admin_context)
        res = req.get_response(api or self.api)

        if expected_res_status:
            self.assertEqual(res.status_int, expected_res_status)
        elif res.status_int >= webob.exc.HTTPClientError.code:
            raise webob.exc.HTTPClientError(code=res.status_int)
        return self.deserialize(self.fmt, res)