コード例 #1
0
    def _get_subnets_from_port(self, context, port):
        """Return the subnets for a given port."""

        fixed_ips = port['fixed_ips']
        # No fixed_ips for the port means there is no subnet associated
        # with the network the port is created on.
        # Since list_subnets(id=[]) returns all subnets visible for the
        # current tenant, returned subnets may contain subnets which is not
        # related to the port. To avoid this, the method returns here.
        if not fixed_ips:
            return []
        search_opts = {'id': [ip['subnet_id'] for ip in fixed_ips]}
        data = quantumv2.get_client(context).list_subnets(**search_opts)
        ipam_subnets = data.get('subnets', [])
        subnets = []

        for subnet in ipam_subnets:
            subnet_dict = {'cidr': subnet['cidr'],
                           'gateway': network_model.IP(
                                address=subnet['gateway_ip'],
                                type='gateway'),
            }

            # attempt to populate DHCP server field
            search_opts = {'network_id': subnet['network_id'],
                           'device_owner': 'network:dhcp'}
            data = quantumv2.get_client(context).list_ports(**search_opts)
            dhcp_ports = data.get('ports', [])
            for p in dhcp_ports:
                for ip_pair in p['fixed_ips']:
                    if ip_pair['subnet_id'] == subnet['id']:
                        subnet_dict['dhcp_server'] = ip_pair['ip_address']
                        break

            subnet_object = network_model.Subnet(**subnet_dict)
            for dns in subnet.get('dns_nameservers', []):
                subnet_object.add_dns(
                    network_model.IP(address=dns, type='dns'))

            # TODO(gongysh) get the routes for this subnet
            subnets.append(subnet_object)
        return subnets
コード例 #2
0
ファイル: utils.py プロジェクト: fp314/for_openstack
    def current():
        subnet_4 = network_model.Subnet(
            cidr=FAKE_NETWORK_IP4_CIDR,
            dns=[
                network_model.IP(FAKE_NETWORK_DNS_IP4_ADDR1),
                network_model.IP(FAKE_NETWORK_DNS_IP4_ADDR2)
            ],
            gateway=network_model.IP(FAKE_NETWORK_IP4_GATEWAY),
            ips=[
                network_model.IP(FAKE_NETWORK_IP4_ADDR1),
                network_model.IP(FAKE_NETWORK_IP4_ADDR2)
            ],
            routes=None,
            dhcp_server=FAKE_NETWORK_DHCP_IP4_ADDR)
        subnet_6 = network_model.Subnet(
            cidr=FAKE_NETWORK_IP6_CIDR,
            gateway=network_model.IP(FAKE_NETWORK_IP6_GATEWAY),
            ips=[
                network_model.IP(FAKE_NETWORK_IP6_ADDR1),
                network_model.IP(FAKE_NETWORK_IP6_ADDR2),
                network_model.IP(FAKE_NETWORK_IP6_ADDR3)
            ],
            routes=None,
            version=6)
        subnets = [subnet_4]
        if ipv6:
            subnets.append(subnet_6)
        network = network_model.Network(
            id=FAKE_NETWORK_UUID,
            bridge=FAKE_NETWORK_BRIDGE,
            label=None,
            subnets=subnets,
            vlan=FAKE_NETWORK_VLAN,
            bridge_interface=FAKE_NETWORK_INTERFACE,
            injected=False)
        if CONF.use_neutron:
            vif_type = network_model.VIF_TYPE_OVS
        else:
            vif_type = network_model.VIF_TYPE_BRIDGE
        vif = network_model.VIF(id=FAKE_VIF_UUID,
                                address=FAKE_VIF_MAC,
                                network=network,
                                type=vif_type,
                                devname=None,
                                ovs_interfaceid=None)

        return vif
コード例 #3
0
    def test_nova_to_osvif_routes(self):
        routes = [
            model.Route(cidr="192.168.1.0/24",
                        gateway=model.IP(address="192.168.1.254",
                                         type='gateway'),
                        interface="eth0"),
            model.Route(cidr="10.0.0.0/8",
                        gateway=model.IP(address="10.0.0.1", type='gateway')),
        ]

        expect = osv_objects.route.RouteList(objects=[
            osv_objects.route.Route(cidr="192.168.1.0/24",
                                    gateway="192.168.1.254",
                                    interface="eth0"),
            osv_objects.route.Route(cidr="10.0.0.0/8", gateway="10.0.0.1"),
        ])

        actual = os_vif_util._nova_to_osvif_routes(routes)

        self.assertObjEqual(expect, actual)
コード例 #4
0
 def _nw_info_get_ips(self, client, port):
     network_IPs = []
     for fixed_ip in port['fixed_ips']:
         fixed = network_model.FixedIP(address=fixed_ip['ip_address'])
         floats = self._get_floating_ips_by_fixed_and_port(
             client, fixed_ip['ip_address'], port['id'])
         for ip in floats:
             fip = network_model.IP(address=ip['floating_ip_address'],
                                    type='floating')
             fixed.add_floating_ip(fip)
         network_IPs.append(fixed)
     return network_IPs
コード例 #5
0
    def test_nova_to_osvif_network_labeled_no_vlan(self):
        network = model.Network(id="b82c1929-051e-481d-8110-4669916c7915",
                                label="Demo Net",
                                should_create_vlan=True,
                                subnets=[
                                    model.Subnet(cidr="192.168.1.0/24",
                                                 gateway=model.IP(
                                                     address="192.168.1.254",
                                                     type='gateway')),
                                ])

        self.assertRaises(exception.NovaException,
                          os_vif_util._nova_to_osvif_network, network)
コード例 #6
0
    def current():
        fake_ip = '0.0.0.0'
        subnet_4 = network_model.Subnet(
            cidr=fake_ip,
            dns=[network_model.IP(fake_ip),
                 network_model.IP(fake_ip)],
            gateway=network_model.IP(fake_ip),
            ips=[network_model.IP(fake_ip),
                 network_model.IP(fake_ip)],
            routes=None,
            dhcp_server=network_model.IP(fake_ip))
        subnet_6 = network_model.Subnet(cidr=fake_ip,
                                        gateway=network_model.IP(fake_ip),
                                        ips=[
                                            network_model.IP(fake_ip),
                                            network_model.IP(fake_ip),
                                            network_model.IP(fake_ip)
                                        ],
                                        routes=None,
                                        version=6)
        subnets = [subnet_4]
        if ipv6:
            subnets.append(subnet_6)
        network = network_model.Network(id=None,
                                        bridge=fake,
                                        label=None,
                                        subnets=subnets,
                                        vlan=fake_vlan,
                                        bridge_interface=fake_bridge_interface,
                                        injected=False)
        vif = network_model.VIF(id='vif-xxx-yyy-zzz',
                                address=fake,
                                network=network,
                                type=network_model.VIF_TYPE_BRIDGE,
                                devname=None,
                                ovs_interfaceid=None)

        return vif
コード例 #7
0
ファイル: api.py プロジェクト: linets/nova
    def _get_subnets_from_port(self, context, port):
        """Return the subnets for a given port."""

        fixed_ips = port['fixed_ips']
        search_opts = {'id': [ip['subnet_id'] for ip in fixed_ips]}
        data = quantumv2.get_client(context).list_subnets(**search_opts)
        ipam_subnets = data.get('subnets', [])
        subnets = []

        for subnet in ipam_subnets:
            subnet_dict = {
                'cidr':
                subnet['cidr'],
                'gateway':
                network_model.IP(address=subnet['gateway_ip'], type='gateway'),
            }

            # attempt to populate DHCP server field
            search_opts = {
                'network_id': subnet['network_id'],
                'device_owner': 'network:dhcp'
            }
            data = quantumv2.get_client(context).list_ports(**search_opts)
            dhcp_ports = data.get('ports', [])
            for p in dhcp_ports:
                for ip_pair in p['fixed_ips']:
                    if ip_pair['subnet_id'] == subnet['id']:
                        subnet_dict['dhcp_server'] = ip_pair['ip_address']
                        break

            subnet_object = network_model.Subnet(**subnet_dict)
            for dns in subnet.get('dns_nameservers', []):
                subnet_object.add_dns(network_model.IP(address=dns,
                                                       type='dns'))

            # TODO(gongysh) get the routes for this subnet
            subnets.append(subnet_object)
        return subnets
コード例 #8
0
 def _verify_nw_info(self, nw_inf, index=0):
     id_suffix = index + 1
     self.assertEquals('10.0.%s.2' % id_suffix,
                       nw_inf.fixed_ips()[index]['address'])
     self.assertEquals('my_netname%s' % id_suffix,
                       nw_inf[index]['network']['label'])
     self.assertEquals('my_portid%s' % id_suffix, nw_inf[index]['id'])
     self.assertEquals('my_mac%s' % id_suffix, nw_inf[index]['address'])
     self.assertEquals('10.0.%s.0/24' % id_suffix,
                       nw_inf[index]['network']['subnets'][0]['cidr'])
     self.assertTrue(
         model.IP(
             address='8.8.%s.1' %
             id_suffix) in nw_inf[index]['network']['subnets'][0]['dns'])
コード例 #9
0
    def test_nova_to_osvif_ips(self):
        ips = [
            model.FixedIP(
                address="192.168.122.24",
                floating_ips=[
                    model.IP(address="192.168.122.100",
                             type="floating"),
                    model.IP(address="192.168.122.101",
                             type="floating"),
                    model.IP(address="192.168.122.102",
                             type="floating"),
                ],
                version=4),
            model.FixedIP(
                address="2001::beef",
                version=6),
        ]

        actual = os_vif_util._nova_to_osvif_ips(ips)

        expect = osv_objects.fixed_ip.FixedIPList(
            objects=[
                osv_objects.fixed_ip.FixedIP(
                    address="192.168.122.24",
                    floating_ips=[
                        "192.168.122.100",
                        "192.168.122.101",
                        "192.168.122.102",
                        ]),
                osv_objects.fixed_ip.FixedIP(
                    address="2001::beef",
                    floating_ips=[]),
                ],
            )

        self.assertObjEqual(expect, actual)
コード例 #10
0
    def test_ip_not_equal(self):
        ip1 = model.IP(address='127.0.0.1')
        ip2 = model.IP(address='172.0.0.3')
        self.assertNotEqual(ip1, ip2)

        ip1 = model.IP(address='127.0.0.1', type=1)
        ip2 = model.IP(address='172.0.0.1', type=2)
        self.assertNotEqual(ip1, ip2)

        ip1 = model.IP(address='127.0.0.1', version=4)
        ip2 = model.IP(address='172.0.0.1', version=6)
        self.assertNotEqual(ip1, ip2)
コード例 #11
0
    def test_nova_to_osvif_network_extra(self):
        network = model.Network(
            id="b82c1929-051e-481d-8110-4669916c7915",
            bridge="br0",
            multi_host=True,
            should_create_bridge=True,
            should_create_vlan=True,
            bridge_interface="eth0",
            vlan=1729,
            subnets=[
                model.Subnet(cidr="192.168.1.0/24",
                             gateway=model.IP(
                                 address="192.168.1.254",
                                 type='gateway')),
            ])

        expect = osv_objects.network.Network(
            id="b82c1929-051e-481d-8110-4669916c7915",
            bridge="br0",
            multi_host=True,
            should_provide_bridge=True,
            should_provide_vlan=True,
            bridge_interface="eth0",
            vlan=1729,
            subnets=osv_objects.subnet.SubnetList(
                objects=[
                    osv_objects.subnet.Subnet(
                        cidr="192.168.1.0/24",
                        dns=[],
                        gateway="192.168.1.254",
                        ips=osv_objects.fixed_ip.FixedIPList(
                            objects=[]),
                        routes=osv_objects.route.RouteList(
                            objects=[]),
                    )
                ]))

        actual = os_vif_util._nova_to_osvif_network(network)

        self.assertObjEqual(expect, actual)
コード例 #12
0
 def test_ip_equal(self):
     ip1 = model.IP(address='127.0.0.1')
     ip2 = model.IP(address='127.0.0.1')
     self.assertEqual(ip1, ip2)
コード例 #13
0
ファイル: test_vifs.py プロジェクト: mangalaman93/nova-docker
class DockerGenericVIFDriverTestCase(test.TestCase):

    REQUIRES_LOCKING = True
    gateway_bridge_4 = network_model.IP(address='10.11.12.1', type='gateway')
    dns_bridge_4 = network_model.IP(address='8.8.8.8', type=None)
    ips_bridge_4 = [
        network_model.IP(address='101.168.1.9', type='fixed', version=4)
    ]

    subnet_bridge_4 = network_model.Subnet(cidr='10.11.1.0/24',
                                           dns=[dns_bridge_4],
                                           gateway=gateway_bridge_4,
                                           ips=ips_bridge_4,
                                           routes=None)

    network_bridge = network_model.Network(id='network-id-xxx-yyy-zzz',
                                           bridge='br100',
                                           label=None,
                                           subnets=[subnet_bridge_4],
                                           bridge_interface='eth0')

    vif_bridge = network_model.VIF(id='920be2f4-2b98-411e-890a-69bcabb2a5a0',
                                   address='00:11:22:33:44:55',
                                   network=network_bridge,
                                   type=network_model.VIF_TYPE_BRIDGE)

    network_iovisor = network_model.Network(id='network-id-xxx-yyy-zzz',
                                            bridge='br100',
                                            label='net1',
                                            subnets=[subnet_bridge_4],
                                            bridge_interface='eth0')

    vif_iovisor = network_model.VIF(id='920be2f4-2b98-411e-890a-69bcabb2a5a0',
                                    address='00:11:22:33:44:55',
                                    network=network_iovisor,
                                    type=network_model.VIF_TYPE_IOVISOR)

    def setUp(self):
        super(DockerGenericVIFDriverTestCase, self).setUp()

        def fake_fe_random_mac(self):
            return 'fe:16:3e:ff:ff:ff'

        self.stubs.Set(vifs.DockerGenericVIFDriver, '_fe_random_mac',
                       fake_fe_random_mac)

    def test_plug_vifs_bridge(self):
        calls = [
            mock.call('ip',
                      'link',
                      'add',
                      'name',
                      'tap920be2f4-2b',
                      'type',
                      'veth',
                      'peer',
                      'name',
                      'ns920be2f4-2b',
                      run_as_root=True),
            mock.call('ip',
                      'link',
                      'set',
                      'tap920be2f4-2b',
                      'address',
                      'fe:16:3e:ff:ff:ff',
                      run_as_root=True),
            mock.call('brctl',
                      'addif',
                      'br100',
                      'tap920be2f4-2b',
                      run_as_root=True),
            mock.call('ip',
                      'link',
                      'set',
                      'tap920be2f4-2b',
                      'up',
                      run_as_root=True)
        ]
        network_info = [self.vif_bridge]
        with mock.patch('nova.utils.execute') as ex:
            driver = docker_driver.DockerDriver(object)
            driver.plug_vifs({'name': 'fake_instance'}, network_info)
            ex.assert_has_calls(calls)

    def test_plug_vifs_bridge_two_interfaces(self):
        calls = [
            # interface 1
            mock.call('ip',
                      'link',
                      'add',
                      'name',
                      'tap920be2f4-2b',
                      'type',
                      'veth',
                      'peer',
                      'name',
                      'ns920be2f4-2b',
                      run_as_root=True),
            mock.call('ip',
                      'link',
                      'set',
                      'tap920be2f4-2b',
                      'address',
                      'fe:16:3e:ff:ff:ff',
                      run_as_root=True),
            mock.call('brctl',
                      'addif',
                      'br100',
                      'tap920be2f4-2b',
                      run_as_root=True),
            mock.call('ip',
                      'link',
                      'set',
                      'tap920be2f4-2b',
                      'up',
                      run_as_root=True),
            # interface 2
            mock.call('ip',
                      'link',
                      'add',
                      'name',
                      'tap920be2f4-2b',
                      'type',
                      'veth',
                      'peer',
                      'name',
                      'ns920be2f4-2b',
                      run_as_root=True),
            mock.call('ip',
                      'link',
                      'set',
                      'tap920be2f4-2b',
                      'address',
                      'fe:16:3e:ff:ff:ff',
                      run_as_root=True),
            mock.call('brctl',
                      'addif',
                      'br100',
                      'tap920be2f4-2b',
                      run_as_root=True),
            mock.call('ip',
                      'link',
                      'set',
                      'tap920be2f4-2b',
                      'up',
                      run_as_root=True),
        ]
        network_info = [self.vif_bridge, self.vif_bridge]
        with mock.patch('nova.utils.execute') as ex:
            driver = docker_driver.DockerDriver(object)
            driver.plug_vifs({'name': 'fake_instance'}, network_info)
            ex.assert_has_calls(calls)

    def test_plug_vifs_ovs(self):
        iface_id = '920be2f4-2b98-411e-890a-69bcabb2a5a0'
        calls = [
            mock.call('ip',
                      'link',
                      'add',
                      'name',
                      'tap920be2f4-2b',
                      'type',
                      'veth',
                      'peer',
                      'name',
                      'ns920be2f4-2b',
                      run_as_root=True),
            mock.call('ovs-vsctl',
                      '--timeout=120',
                      '--',
                      '--if-exists',
                      'del-port',
                      'tap920be2f4-2b',
                      '--',
                      'add-port',
                      'br-int',
                      'tap920be2f4-2b',
                      '--',
                      'set',
                      'Interface',
                      'tap920be2f4-2b',
                      'external-ids:iface-id=%s' % iface_id,
                      'external-ids:iface-status=active',
                      'external-ids:attached-mac=00:11:22:33:44:55',
                      'external-ids:vm-uuid=instance_uuid',
                      run_as_root=True),
            mock.call('ip',
                      'link',
                      'set',
                      'tap920be2f4-2b',
                      'up',
                      run_as_root=True),
        ]
        network_info = [{
            'network': {
                'bridge':
                'br-int',
                'subnets': [{
                    'gateway': {
                        'address': '10.11.12.1'
                    },
                    'cidr':
                    '10.11.12.0/24',
                    'ips': [{
                        'address': '10.11.12.3',
                        'type': 'fixed',
                        'version': 4
                    }]
                }]
            },
            'address': '00:11:22:33:44:55',
            'id': iface_id,
            'type': network_model.VIF_TYPE_OVS
        }]
        with mock.patch('nova.utils.execute') as ex:
            driver = docker_driver.DockerDriver(object)
            driver.plug_vifs({
                'name': 'fake_instance',
                'uuid': 'instance_uuid'
            }, network_info)
            ex.assert_has_calls(calls)

    def test_plug_vifs_ovs_hybrid(self):
        iface_id = '920be2f4-2b98-411e-890a-69bcabb2a5a0'
        calls = [
            mock.call('brctl', 'addbr', 'qbr920be2f4-2b', run_as_root=True),
            mock.call('brctl', 'setfd', 'qbr920be2f4-2b', 0, run_as_root=True),
            mock.call('brctl',
                      'stp',
                      'qbr920be2f4-2b',
                      'off',
                      run_as_root=True),
            mock.call('tee', "/sys/class/net/qbr920be2f4-2b/bridge/multicast_"
                      "snooping",
                      run_as_root=True,
                      process_input='0',
                      check_exit_code=[0, 1]),
            mock.call('ip',
                      'link',
                      'add',
                      'qvb920be2f4-2b',
                      'type',
                      'veth',
                      'peer',
                      'name',
                      'qvo920be2f4-2b',
                      run_as_root=True),
            mock.call('ip',
                      'link',
                      'set',
                      'qvb920be2f4-2b',
                      'up',
                      run_as_root=True),
            mock.call('ip',
                      'link',
                      'set',
                      'qvb920be2f4-2b',
                      'promisc',
                      'on',
                      run_as_root=True),
            mock.call('ip',
                      'link',
                      'set',
                      'qvo920be2f4-2b',
                      'up',
                      run_as_root=True),
            mock.call('ip',
                      'link',
                      'set',
                      'qvo920be2f4-2b',
                      'promisc',
                      'on',
                      run_as_root=True),
            mock.call('ip',
                      'link',
                      'set',
                      'qbr920be2f4-2b',
                      'up',
                      run_as_root=True),
            mock.call('brctl',
                      'addif',
                      'qbr920be2f4-2b',
                      'qvb920be2f4-2b',
                      run_as_root=True),
            mock.call('ovs-vsctl',
                      '--timeout=120',
                      '--',
                      '--if-exists',
                      'del-port',
                      'qvo920be2f4-2b',
                      '--',
                      'add-port',
                      'br-int',
                      'qvo920be2f4-2b',
                      '--',
                      'set',
                      'Interface',
                      'qvo920be2f4-2b', "external-ids:iface-id=920be2f4-2b98-"
                      "411e-890a-69bcabb2a5a0",
                      'external-ids:iface-status=active',
                      'external-ids:attached-mac=00:11:22:33:44:55',
                      'external-ids:vm-uuid=instance_uuid',
                      run_as_root=True),
            mock.call('ip',
                      'link',
                      'add',
                      'name',
                      'tap920be2f4-2b',
                      'type',
                      'veth',
                      'peer',
                      'name',
                      'ns920be2f4-2b',
                      run_as_root=True),
            mock.call('brctl',
                      'addif',
                      'qbr920be2f4-2b',
                      'tap920be2f4-2b',
                      run_as_root=True),
            mock.call('ip',
                      'link',
                      'set',
                      'tap920be2f4-2b',
                      'up',
                      run_as_root=True),
        ]
        network_info = [{
            'network': {
                'bridge':
                'br-int',
                'subnets': [{
                    'gateway': {
                        'address': '10.11.12.1'
                    },
                    'cidr':
                    '10.11.12.0/24',
                    'ips': [{
                        'address': '10.11.12.3',
                        'type': 'fixed',
                        'version': 4
                    }]
                }]
            },
            'address': '00:11:22:33:44:55',
            'id': iface_id,
            'details': {
                'port_filter': True,
                'ovs_hybrid_plug': True
            },
            'type': network_model.VIF_TYPE_OVS
        }]
        with mock.patch('nova.utils.execute') as ex:
            driver = docker_driver.DockerDriver(object)
            driver.plug_vifs({
                'name': 'fake_instance',
                'uuid': 'instance_uuid'
            }, network_info)
            ex.assert_has_calls(calls)

    def test_unplug_vifs_ovs(self):
        iface_id = '920be2f4-2b98-411e-890a-69bcabb2a5a0'
        calls = [
            mock.call('ovs-vsctl',
                      '--timeout=120',
                      '--',
                      '--if-exists',
                      'del-port',
                      'br-int',
                      'tap920be2f4-2b',
                      run_as_root=True)
        ]
        network_info = [{
            'network': {
                'bridge':
                'br-int',
                'subnets': [{
                    'gateway': {
                        'address': '10.11.12.1'
                    },
                    'cidr':
                    '10.11.12.0/24',
                    'ips': [{
                        'address': '10.11.12.3',
                        'type': 'fixed',
                        'version': 4
                    }]
                }]
            },
            'devname': 'tap920be2f4-2b',
            'address': '00:11:22:33:44:55',
            'id': iface_id,
            'type': network_model.VIF_TYPE_OVS
        }]
        with mock.patch('nova.utils.execute') as ex:
            driver = docker_driver.DockerDriver(object)
            driver.unplug_vifs(
                {
                    'name': 'fake_instance',
                    'uuid': 'instance_uuid'
                }, network_info)
            ex.assert_has_calls(calls)

    def test_plug_vifs_midonet(self):
        iface_id = '920be2f4-2b98-411e-890a-69bcabb2a5a0'
        host_side_veth = 'tap920be2f4-2b'
        calls = [
            mock.call('ip',
                      'link',
                      'add',
                      'name',
                      host_side_veth,
                      'type',
                      'veth',
                      'peer',
                      'name',
                      'ns920be2f4-2b',
                      run_as_root=True),
            mock.call('ip',
                      'link',
                      'set',
                      host_side_veth,
                      'up',
                      run_as_root=True),
            mock.call('mm-ctl',
                      '--bind-port',
                      iface_id,
                      host_side_veth,
                      run_as_root=True),
        ]

        network_info = [{
            'id': iface_id,
            'type': network_model.VIF_TYPE_MIDONET
        }]

        with mock.patch('nova.utils.execute') as ex:
            driver = docker_driver.DockerDriver(object)
            driver.plug_vifs({
                'name': 'fake_instance',
                'uuid': 'instance_uuid'
            }, network_info)
            ex.assert_has_calls(calls)

    def test_unplug_vifs_midonet(self):
        iface_id = '920be2f4-2b98-411e-890a-69bcabb2a5a0'
        calls = [
            mock.call('mm-ctl', '--unbind-port', iface_id, run_as_root=True)
        ]
        network_info = [{
            'id': iface_id,
            'type': network_model.VIF_TYPE_MIDONET
        }]
        with mock.patch('nova.utils.execute') as ex:
            driver = docker_driver.DockerDriver(object)
            driver.unplug_vifs(
                {
                    'name': 'fake_instance',
                    'uuid': 'instance_uuid'
                }, network_info)
            ex.assert_has_calls(calls)

    def test_plug_vifs_iovisor(self):
        iface_id = '920be2f4-2b98-411e-890a-69bcabb2a5a0'
        tenant_id = 'tenant1'
        calls = [
            mock.call('ip',
                      'link',
                      'add',
                      'name',
                      'tap920be2f4-2b',
                      'type',
                      'veth',
                      'peer',
                      'name',
                      'ns920be2f4-2b',
                      run_as_root=True),
            mock.call('ifc_ctl',
                      'gateway',
                      'add_port',
                      'tap920be2f4-2b',
                      run_as_root=True),
            mock.call('ifc_ctl',
                      'gateway',
                      'ifup',
                      'tap920be2f4-2b',
                      'access_vm',
                      "net1_" + iface_id,
                      '00:11:22:33:44:55',
                      'pgtag2=network-id-xxx-yyy-zzz',
                      'pgtag1=%s' % tenant_id,
                      run_as_root=True),
            mock.call('ip',
                      'link',
                      'set',
                      'tap920be2f4-2b',
                      'up',
                      run_as_root=True),
        ]

        network_info = [self.vif_iovisor]

        with mock.patch('nova.utils.execute') as ex:
            driver = docker_driver.DockerDriver(object)
            driver.plug_vifs(
                {
                    'name': 'fake_instance',
                    'uuid': 'instance_uuid',
                    'project_id': tenant_id
                }, network_info)
            ex.assert_has_calls(calls)

    def test_unplug_vifs_iovisor(self):
        iface_id = '920be2f4-2b98-411e-890a-69bcabb2a5a0'
        tenant_id = 'tenant1'
        calls = [
            mock.call('ifc_ctl',
                      'gateway',
                      'ifdown',
                      'tap920be2f4-2b',
                      'access_vm',
                      'net1_' + iface_id,
                      '00:11:22:33:44:55',
                      run_as_root=True),
            mock.call('ifc_ctl',
                      'gateway',
                      'del_port',
                      'tap920be2f4-2b',
                      run_as_root=True)
        ]
        network_info = [self.vif_iovisor]
        with mock.patch('nova.utils.execute') as ex:
            driver = docker_driver.DockerDriver(object)
            driver.unplug_vifs(
                {
                    'name': 'fake_instance',
                    'uuid': 'instance_uuid',
                    'project_id': tenant_id
                }, network_info)
            ex.assert_has_calls(calls)

    def test_unplug_vifs_ovs_hybrid(self):
        iface_id = '920be2f4-2b98-411e-890a-69bcabb2a5a0'
        calls = [
            mock.call('ovs-vsctl',
                      '--timeout=120',
                      '--',
                      '--if-exists',
                      'del-port',
                      'br-int',
                      'qvo920be2f4-2b',
                      run_as_root=True)
        ]
        network_info = [{
            'network': {
                'bridge':
                'br-int',
                'subnets': [{
                    'gateway': {
                        'address': '10.11.12.1'
                    },
                    'cidr':
                    '10.11.12.0/24',
                    'ips': [{
                        'address': '10.11.12.3',
                        'type': 'fixed',
                        'version': 4
                    }]
                }]
            },
            'devname': 'tap920be2f4-2b',
            'address': '00:11:22:33:44:55',
            'id': iface_id,
            'details': {
                'port_filter': True,
                'ovs_hybrid_plug': True
            },
            'type': network_model.VIF_TYPE_OVS
        }]
        with mock.patch('nova.utils.execute') as ex:
            driver = docker_driver.DockerDriver(object)
            driver.unplug_vifs(
                {
                    'name': 'fake_instance',
                    'uuid': 'instance_uuid'
                }, network_info)
            ex.assert_has_calls(calls)

    @mock.patch.object(docker_driver.DockerDriver,
                       '_find_container_by_name',
                       return_value={'id': 'fake_id'})
    @mock.patch.object(docker_driver.DockerDriver,
                       '_find_container_pid',
                       return_value=1234)
    def test_attach_vifs(self, mock_find_by_name, mock_find_pid):
        calls = [
            mock.call('ln',
                      '-sf',
                      '/proc/1234/ns/net',
                      '/var/run/netns/fake_id',
                      run_as_root=True),
            mock.call('ip',
                      'netns',
                      'exec',
                      'fake_id',
                      'ip',
                      'link',
                      'set',
                      'lo',
                      'up',
                      run_as_root=True),
            mock.call('ip',
                      'link',
                      'set',
                      'ns920be2f4-2b',
                      'netns',
                      'fake_id',
                      run_as_root=True),
            mock.call('ip',
                      'netns',
                      'exec',
                      'fake_id',
                      'ip',
                      'link',
                      'set',
                      'ns920be2f4-2b',
                      'address',
                      '00:11:22:33:44:55',
                      run_as_root=True),
            mock.call('ip',
                      'netns',
                      'exec',
                      'fake_id',
                      'ip',
                      'addr',
                      'add',
                      '10.11.12.3/24',
                      'dev',
                      'ns920be2f4-2b',
                      run_as_root=True),
            mock.call('ip',
                      'netns',
                      'exec',
                      'fake_id',
                      'ip',
                      'link',
                      'set',
                      'ns920be2f4-2b',
                      'up',
                      run_as_root=True),
            mock.call('ip',
                      'netns',
                      'exec',
                      'fake_id',
                      'ip',
                      'route',
                      'replace',
                      'default',
                      'via',
                      '10.11.12.1',
                      'dev',
                      'ns920be2f4-2b',
                      run_as_root=True)
        ]
        network_info = [{
            'network': {
                'bridge':
                'br100',
                'subnets': [{
                    'gateway': {
                        'address': '10.11.12.1'
                    },
                    'cidr':
                    '10.11.12.0/24',
                    'ips': [{
                        'address': '10.11.12.3',
                        'type': 'fixed',
                        'version': 4
                    }]
                }]
            },
            'address': '00:11:22:33:44:55',
            'id': '920be2f4-2b98-411e-890a-69bcabb2a5a0',
            'type': network_model.VIF_TYPE_BRIDGE
        }]
        with mock.patch('nova.utils.execute') as ex:
            driver = docker_driver.DockerDriver(object)
            driver._attach_vifs({'name': 'fake_instance'}, network_info)
            ex.assert_has_calls(calls)

    @mock.patch.object(docker_driver.DockerDriver,
                       '_find_container_by_name',
                       return_value={'id': 'fake_id'})
    @mock.patch.object(docker_driver.DockerDriver,
                       '_find_container_pid',
                       return_value=1234)
    def test_attach_vifs_two_interfaces(self, mock_find_by_name,
                                        mock_find_pid):
        calls = [
            mock.call('ln',
                      '-sf',
                      '/proc/1234/ns/net',
                      '/var/run/netns/fake_id',
                      run_as_root=True),
            mock.call('ip',
                      'netns',
                      'exec',
                      'fake_id',
                      'ip',
                      'link',
                      'set',
                      'lo',
                      'up',
                      run_as_root=True),
            # interface 1
            mock.call('ip',
                      'link',
                      'set',
                      'ns920be2f4-2b',
                      'netns',
                      'fake_id',
                      run_as_root=True),
            mock.call('ip',
                      'netns',
                      'exec',
                      'fake_id',
                      'ip',
                      'link',
                      'set',
                      'ns920be2f4-2b',
                      'address',
                      '00:11:22:33:44:55',
                      run_as_root=True),
            mock.call('ip',
                      'netns',
                      'exec',
                      'fake_id',
                      'ip',
                      'addr',
                      'add',
                      '10.11.12.3/24',
                      'dev',
                      'ns920be2f4-2b',
                      run_as_root=True),
            mock.call('ip',
                      'netns',
                      'exec',
                      'fake_id',
                      'ip',
                      'link',
                      'set',
                      'ns920be2f4-2b',
                      'up',
                      run_as_root=True),
            mock.call('ip',
                      'netns',
                      'exec',
                      'fake_id',
                      'ip',
                      'route',
                      'replace',
                      'default',
                      'via',
                      '10.11.12.1',
                      'dev',
                      'ns920be2f4-2b',
                      run_as_root=True),
            # interface 2
            mock.call('ip',
                      'link',
                      'set',
                      'ns920be2f4-2b',
                      'netns',
                      'fake_id',
                      run_as_root=True),
            mock.call('ip',
                      'netns',
                      'exec',
                      'fake_id',
                      'ip',
                      'link',
                      'set',
                      'ns920be2f4-2b',
                      'address',
                      '00:11:22:33:44:66',
                      run_as_root=True),
            mock.call('ip',
                      'netns',
                      'exec',
                      'fake_id',
                      'ip',
                      'addr',
                      'add',
                      '10.13.12.3/24',
                      'dev',
                      'ns920be2f4-2b',
                      run_as_root=True),
            mock.call('ip',
                      'netns',
                      'exec',
                      'fake_id',
                      'ip',
                      'link',
                      'set',
                      'ns920be2f4-2b',
                      'up',
                      run_as_root=True),
            mock.call('ip',
                      'netns',
                      'exec',
                      'fake_id',
                      'ip',
                      'route',
                      'replace',
                      'default',
                      'via',
                      '10.13.12.1',
                      'dev',
                      'ns920be2f4-2b',
                      run_as_root=True)
        ]
        network_info = [{
            'network': {
                'bridge':
                'br100',
                'subnets': [{
                    'gateway': {
                        'address': '10.11.12.1'
                    },
                    'cidr':
                    '10.11.12.0/24',
                    'ips': [{
                        'address': '10.11.12.3',
                        'type': 'fixed',
                        'version': 4
                    }],
                }]
            },
            'address': '00:11:22:33:44:55',
            'type': network_model.VIF_TYPE_BRIDGE,
            'id': '920be2f4-2b98-411e-890a-69bcabb2a5a0'
        }, {
            'network': {
                'bridge':
                'br100',
                'subnets': [{
                    'gateway': {
                        'address': '10.13.12.1'
                    },
                    'cidr':
                    '10.13.12.0/24',
                    'ips': [{
                        'address': '10.13.12.3',
                        'type': 'fixed',
                        'version': 4
                    }]
                }]
            },
            'address': '00:11:22:33:44:66',
            'type': network_model.VIF_TYPE_BRIDGE,
            'id': '920be2f4-2b98-411e-890a-69bcabb2a5a0'
        }]
        with mock.patch('nova.utils.execute') as ex:
            driver = docker_driver.DockerDriver(object)
            driver._attach_vifs({'name': 'fake_instance'}, network_info)
            ex.assert_has_calls(calls)
コード例 #14
0
    def setUp(self):
        super(VMwareVMOpsTestCase, self).setUp()
        vmwareapi_fake.reset()
        stubs.set_stubs(self.stubs)
        self._session = driver.VMwareAPISession()

        self._vmops = vmops.VMwareVMOps(self._session, None, None)
        self._image_id = nova.tests.image.fake.get_valid_image_id()
        values = {
            'name': 'fake_name',
            'uuid': 'fake_uuid',
            'vcpus': 1,
            'memory_mb': 512,
            'image_ref': self._image_id,
            'root_gb': 1,
            'node': 'respool-1001(MyResPoolName)',
        }
        self._context = context.RequestContext('fake_user', 'fake_project')
        self._instance = fake_instance.fake_instance_obj(
            self._context, **values)

        subnet_4 = network_model.Subnet(
            cidr='192.168.0.1/24',
            dns=[network_model.IP('192.168.0.1')],
            gateway=network_model.IP('192.168.0.1'),
            ips=[network_model.IP('192.168.0.100')],
            routes=None)
        subnet_6 = network_model.Subnet(
            cidr='dead:beef::1/64',
            dns=None,
            gateway=network_model.IP('dead:beef::1'),
            ips=[network_model.IP('dead:beef::dcad:beff:feef:0')],
            routes=None)
        network = network_model.Network(id=0,
                                        bridge='fa0',
                                        label='fake',
                                        subnets=[subnet_4, subnet_6],
                                        vlan=None,
                                        bridge_interface=None,
                                        injected=True)
        self.network_info = network_model.NetworkInfo([
            network_model.VIF(id=None,
                              address='DE:AD:BE:EF:00:00',
                              network=network,
                              type=None,
                              devname=None,
                              ovs_interfaceid=None,
                              rxtx_cap=3)
        ])
        pure_IPv6_network = network_model.Network(id=0,
                                                  bridge='fa0',
                                                  label='fake',
                                                  subnets=[subnet_6],
                                                  vlan=None,
                                                  bridge_interface=None,
                                                  injected=True)
        self.pure_IPv6_network_info = network_model.NetworkInfo([
            network_model.VIF(id=None,
                              address='DE:AD:BE:EF:00:00',
                              network=pure_IPv6_network,
                              type=None,
                              devname=None,
                              ovs_interfaceid=None,
                              rxtx_cap=3)
        ])
        utils.reset_is_neutron()
コード例 #15
0
class DockerFirewallDriverTestCase(test.TestCase):

    REQUIRES_LOCKING = True
    gateway_bridge_4 = network_model.IP(address='10.11.12.1', type='gateway')
    dns_bridge_4 = network_model.IP(address='8.8.8.8', type=None)
    ips_bridge_4 = [
        network_model.IP(address='101.168.1.9', type='fixed', version=4)
    ]

    subnet_bridge_4 = network_model.Subnet(cidr='10.11.1.0/24',
                                           dns=[dns_bridge_4],
                                           gateway=gateway_bridge_4,
                                           ips=ips_bridge_4,
                                           routes=None)

    network_bridge = network_model.Network(id='network-id-xxx-yyy-zzz',
                                           bridge='br100',
                                           label=None,
                                           subnets=[subnet_bridge_4],
                                           bridge_interface='eth0')

    vif_bridge = network_model.VIF(id='920be2f4-2b98-411e-890a-69bcabb2a5a0',
                                   address='00:11:22:33:44:55',
                                   network=network_bridge,
                                   type=network_model.VIF_TYPE_BRIDGE)

    def setUp(self):
        super(DockerFirewallDriverTestCase, self).setUp()
        self.driver = driver.DockerDriver(None)

    @mock.patch.object(firewall.NoopFirewallDriver,
                       'prepare_instance_filter',
                       create=True)
    @mock.patch.object(firewall.NoopFirewallDriver,
                       'setup_basic_filtering',
                       create=True)
    @mock.patch.object(firewall.NoopFirewallDriver,
                       'apply_instance_filter',
                       create=True)
    def test_start_firewall(self, mock_aif, mock_sbf, mock_pif):
        fake_inst = 'fake-inst'
        fake_net_info = mock.ANY
        self.driver._start_firewall(fake_inst, fake_net_info)

        mock_aif.assert_called_once_with(fake_inst, fake_net_info)
        mock_sbf.assert_called_once_with(fake_inst, fake_net_info)
        mock_pif.assert_called_once_with(fake_inst, fake_net_info)

    @mock.patch.object(firewall.NoopFirewallDriver,
                       'unfilter_instance',
                       create=True)
    def test_stop_firewall(self, mock_ui):
        fake_inst = 'fake-inst'
        fake_net_info = mock.ANY
        self.driver._stop_firewall(fake_inst, fake_net_info)
        mock_ui.assert_called_once_with(fake_inst, fake_net_info)

    @mock.patch.object(firewall.NoopFirewallDriver,
                       'prepare_instance_filter',
                       create=True)
    @mock.patch.object(firewall.NoopFirewallDriver,
                       'setup_basic_filtering',
                       create=True)
    @mock.patch.object(firewall.NoopFirewallDriver,
                       'apply_instance_filter',
                       create=True)
    def test_plug_vifs_bridge(self, mock_aif, mock_sbf, mock_pif):
        fake_net_info = [self.vif_bridge]
        with mock.patch('nova.utils.execute'):
            d = driver.DockerDriver(object)
            fake_inst = {'name': 'fake_instance'}
            d.plug_vifs(fake_inst, fake_net_info)
            mock_aif.assert_called_once_with(fake_inst, fake_net_info)
            mock_sbf.assert_called_once_with(fake_inst, fake_net_info)
            mock_pif.assert_called_once_with(fake_inst, fake_net_info)

    @mock.patch.object(firewall.NoopFirewallDriver,
                       'unfilter_instance',
                       create=True)
    def test_unplug_vifs_ovs(self, mock_ui):
        iface_id = '920be2f4-2b98-411e-890a-69bcabb2a5a0'
        fake_net_info = [{
            'network': {
                'bridge':
                'br-int',
                'subnets': [{
                    'gateway': {
                        'address': '10.11.12.1'
                    },
                    'cidr':
                    '10.11.12.0/24',
                    'ips': [{
                        'address': '10.11.12.3',
                        'type': 'fixed',
                        'version': 4
                    }]
                }]
            },
            'devname': 'tap920be2f4-2b',
            'address': '00:11:22:33:44:55',
            'id': iface_id,
            'type': network_model.VIF_TYPE_OVS
        }]
        with mock.patch('nova.utils.execute'):
            d = driver.DockerDriver(object)
            fake_inst = {'name': 'fake_instance', 'uuid': 'instance_uuid'}
            d.unplug_vifs(fake_inst, fake_net_info)
            mock_ui.assert_called_once_with(fake_inst, fake_net_info)
コード例 #16
0
 def test_attach_vrouter(self, mock_find_by_name, mock_find_pid):
     vid = '920be1f5-2b98-411e-890a-69bcabb2a5a0'
     if_remote_name = 'ns%s' % vid[:8]
     if_local_name = 'veth%s' % vid[:8]
     address = '10.1.2.1'
     gateway = '1.1.1.254'
     fixed_ip = '1.1.1.42/24'
     calls = [
         mock.call('mkdir', '-p', '/var/run/netns', run_as_root=True),
         mock.call('ln',
                   '-sf',
                   '/proc/7890/ns/net',
                   '/var/run/netns/my_vm',
                   run_as_root=True),
         mock.call('ip',
                   'link',
                   'set',
                   if_remote_name,
                   'netns',
                   'my_vm',
                   run_as_root=True),
         mock.call('ip',
                   'link',
                   'set',
                   if_local_name,
                   'up',
                   run_as_root=True),
         mock.call('ip',
                   'netns',
                   'exec',
                   'my_vm',
                   'ip',
                   'link',
                   'set',
                   if_remote_name,
                   'address',
                   address,
                   run_as_root=True),
         mock.call('ip',
                   'netns',
                   'exec',
                   'my_vm',
                   'ifconfig',
                   if_remote_name,
                   fixed_ip,
                   run_as_root=True),
         mock.call('ip',
                   'netns',
                   'exec',
                   'my_vm',
                   'ip',
                   'route',
                   'replace',
                   'default',
                   'via',
                   gateway,
                   'dev',
                   if_remote_name,
                   run_as_root=True),
         mock.call('ip',
                   'netns',
                   'exec',
                   'my_vm',
                   'ip',
                   'link',
                   'set',
                   if_remote_name,
                   'up',
                   run_as_root=True)
     ]
     network_info = [
         network_model.VIF(
             id=vid,
             address=address,
             network=network_model.Network(
                 id='virtual-network-1',
                 subnets=[
                     network_model.Subnet(
                         cidr='1.1.1.0/24',
                         gateway=network_model.IP(address=gateway,
                                                  type='gateway'),
                         ips=[
                             network_model.IP(address='1.1.1.42',
                                              type='fixed',
                                              version=4)
                         ])
                 ]))
     ]
     instance = dict(name='fake_instance',
                     display_name='fake_vm',
                     hostname='fake_vm',
                     host='linux',
                     project_id='e2d2ddc6-4e0f-4cd4-b846-3bad53093ec6',
                     uuid='d4b817fb-7885-4649-bad7-89302dde12e1')
     with mock.patch('nova.utils.execute') as ex:
         driver = docker_driver.DockerDriver(object)
         driver._attach_vifs(instance, network_info)
         ex.assert_has_calls(calls)
コード例 #17
0
ファイル: test_vmops.py プロジェクト: xzj675/nova
    def setUp(self):
        super(VMwareVMOpsTestCase, self).setUp()
        vmwareapi_fake.reset()
        stubs.set_stubs(self.stubs)
        self.flags(image_cache_subdirectory_name='vmware_base',
                   my_ip='',
                   flat_injected=True,
                   vnc_enabled=True)
        self._context = context.RequestContext('fake_user', 'fake_project')
        self._session = driver.VMwareAPISession()

        self._virtapi = mock.Mock()
        self._vmops = vmops.VMwareVCVMOps(self._session, self._virtapi, None)

        self._image_id = nova.tests.image.fake.get_valid_image_id()
        values = {
            'name': 'fake_name',
            'uuid': 'fake_uuid',
            'vcpus': 1,
            'memory_mb': 512,
            'image_ref': self._image_id,
            'root_gb': 1,
            'node': 'respool-1001(MyResPoolName)'
        }
        self._instance = fake_instance.fake_instance_obj(
                                 self._context, **values)

        fake_ds_ref = vmwareapi_fake.ManagedObjectReference('fake-ds')

        self._ds_record = vm_util.DSRecord(
                datastore=fake_ds_ref, name='fake_ds',
                capacity=10 * units.Gi,
                freespace=10 * units.Gi)
        self._dc_info = vmops.DcInfo(
                ref='fake_dc_ref', name='fake_dc',
                vmFolder='fake_vm_folder')

        subnet_4 = network_model.Subnet(cidr='192.168.0.1/24',
                                        dns=[network_model.IP('192.168.0.1')],
                                        gateway=
                                            network_model.IP('192.168.0.1'),
                                        ips=[
                                            network_model.IP('192.168.0.100')],
                                        routes=None)
        subnet_6 = network_model.Subnet(cidr='dead:beef::1/64',
                                        dns=None,
                                        gateway=
                                            network_model.IP('dead:beef::1'),
                                        ips=[network_model.IP(
                                            'dead:beef::dcad:beff:feef:0')],
                                        routes=None)
        network = network_model.Network(id=0,
                                        bridge='fa0',
                                        label='fake',
                                        subnets=[subnet_4, subnet_6],
                                        vlan=None,
                                        bridge_interface=None,
                                        injected=True)
        self.network_info = network_model.NetworkInfo([
                network_model.VIF(id=None,
                                  address='DE:AD:BE:EF:00:00',
                                  network=network,
                                  type=None,
                                  devname=None,
                                  ovs_interfaceid=None,
                                  rxtx_cap=3)
                ])
        pure_IPv6_network = network_model.Network(id=0,
                                        bridge='fa0',
                                        label='fake',
                                        subnets=[subnet_6],
                                        vlan=None,
                                        bridge_interface=None,
                                        injected=True)
        self.pure_IPv6_network_info = network_model.NetworkInfo([
                network_model.VIF(id=None,
                                  address='DE:AD:BE:EF:00:00',
                                  network=pure_IPv6_network,
                                  type=None,
                                  devname=None,
                                  ovs_interfaceid=None,
                                  rxtx_cap=3)
                ])
コード例 #18
0
ファイル: test_libvirt_vif.py プロジェクト: wingo1990/nova
class LibvirtVifTestCase(test.TestCase):

    gateway_bridge_4 = network_model.IP(address='101.168.1.1', type='gateway')
    dns_bridge_4 = network_model.IP(address='8.8.8.8', type=None)
    ips_bridge_4 = [network_model.IP(address='101.168.1.9', type=None)]
    subnet_bridge_4 = network_model.Subnet(cidr='101.168.1.0/24',
                                           dns=[dns_bridge_4],
                                           gateway=gateway_bridge_4,
                                           routes=None,
                                           dhcp_server='191.168.1.1')

    gateway_bridge_6 = network_model.IP(address='101:1db9::1', type='gateway')
    subnet_bridge_6 = network_model.Subnet(cidr='101:1db9::/64',
                                           dns=None,
                                           gateway=gateway_bridge_6,
                                           ips=None,
                                           routes=None)

    network_bridge = network_model.Network(
        id='network-id-xxx-yyy-zzz',
        bridge='br0',
        label=None,
        subnets=[subnet_bridge_4, subnet_bridge_6],
        bridge_interface='eth0',
        vlan=99)

    vif_bridge = network_model.VIF(id='vif-xxx-yyy-zzz',
                                   address='ca:fe:de:ad:be:ef',
                                   network=network_bridge,
                                   type=network_model.VIF_TYPE_BRIDGE,
                                   devname='tap-xxx-yyy-zzz',
                                   ovs_interfaceid=None)

    network_bridge_neutron = network_model.Network(
        id='network-id-xxx-yyy-zzz',
        bridge=None,
        label=None,
        subnets=[subnet_bridge_4, subnet_bridge_6],
        bridge_interface='eth0',
        vlan=99)

    vif_bridge_neutron = network_model.VIF(id='vif-xxx-yyy-zzz',
                                           address='ca:fe:de:ad:be:ef',
                                           network=network_bridge_neutron,
                                           type=None,
                                           devname='tap-xxx-yyy-zzz',
                                           ovs_interfaceid='aaa-bbb-ccc')

    network_ovs = network_model.Network(
        id='network-id-xxx-yyy-zzz',
        bridge='br0',
        label=None,
        subnets=[subnet_bridge_4, subnet_bridge_6],
        bridge_interface=None,
        vlan=99)

    network_ivs = network_model.Network(
        id='network-id-xxx-yyy-zzz',
        bridge='br0',
        label=None,
        subnets=[subnet_bridge_4, subnet_bridge_6],
        bridge_interface=None,
        vlan=99)

    vif_ovs = network_model.VIF(id='vif-xxx-yyy-zzz',
                                address='ca:fe:de:ad:be:ef',
                                network=network_ovs,
                                type=network_model.VIF_TYPE_OVS,
                                devname='tap-xxx-yyy-zzz',
                                ovs_interfaceid='aaa-bbb-ccc')

    vif_ovs_legacy = network_model.VIF(id='vif-xxx-yyy-zzz',
                                       address='ca:fe:de:ad:be:ef',
                                       network=network_ovs,
                                       type=None,
                                       devname=None,
                                       ovs_interfaceid=None)

    vif_ivs = network_model.VIF(id='vif-xxx-yyy-zzz',
                                address='ca:fe:de:ad:be:ef',
                                network=network_ivs,
                                type=network_model.VIF_TYPE_IVS,
                                devname='tap-xxx-yyy-zzz',
                                ovs_interfaceid='aaa-bbb-ccc')

    vif_ivs_legacy = network_model.VIF(id='vif-xxx-yyy-zzz',
                                       address='ca:fe:de:ad:be:ef',
                                       network=network_ovs,
                                       type=None,
                                       devname=None,
                                       ovs_interfaceid='aaa')

    vif_none = network_model.VIF(id='vif-xxx-yyy-zzz',
                                 address='ca:fe:de:ad:be:ef',
                                 network=network_bridge,
                                 type=None,
                                 devname='tap-xxx-yyy-zzz',
                                 ovs_interfaceid=None)

    network_8021 = network_model.Network(
        id='network-id-xxx-yyy-zzz',
        bridge=None,
        label=None,
        subnets=[subnet_bridge_4, subnet_bridge_6],
        interface='eth0',
        vlan=99)

    vif_8021qbh = network_model.VIF(
        id='vif-xxx-yyy-zzz',
        address='ca:fe:de:ad:be:ef',
        network=network_8021,
        type=network_model.VIF_TYPE_802_QBH,
        devname='tap-xxx-yyy-zzz',
        ovs_interfaceid=None,
        qbh_params=network_model.VIF8021QbhParams(profileid="xxx-yyy-zzz"))

    vif_8021qbg = network_model.VIF(id='vif-xxx-yyy-zzz',
                                    address='ca:fe:de:ad:be:ef',
                                    network=network_8021,
                                    type=network_model.VIF_TYPE_802_QBG,
                                    devname='tap-xxx-yyy-zzz',
                                    ovs_interfaceid=None,
                                    qbg_params=network_model.VIF8021QbgParams(
                                        managerid="xxx-yyy-zzz",
                                        typeid="aaa-bbb-ccc",
                                        typeidversion="1",
                                        instanceid="ddd-eee-fff"))

    instance = {'name': 'instance-name', 'uuid': 'instance-uuid'}

    bandwidth = {
        'quota:vif_inbound_peak': '102400',
        'quota:vif_outbound_peak': '102400',
        'quota:vif_inbound_average': '102400',
        'quota:vif_outbound_average': '102400',
        'quota:vif_inbound_burst': '102400',
        'quota:vif_inbound_burst': '102400'
    }

    def setUp(self):
        super(LibvirtVifTestCase, self).setUp()
        self.flags(allow_same_net_traffic=True)
        self.executes = []

        def fake_execute(*cmd, **kwargs):
            self.executes.append(cmd)
            return None, None

        self.stubs.Set(utils, 'execute', fake_execute)

    def _get_conn(self, uri="qemu:///session", ver=None):
        def __inner():
            if ver is None:
                return fakelibvirt.Connection(uri, False)
            else:
                return fakelibvirt.Connection(uri, False, ver)

        return __inner

    def _get_node(self, xml):
        doc = etree.fromstring(xml)
        ret = doc.findall('./devices/interface')
        self.assertEqual(len(ret), 1)
        return ret[0]

    def _assertMacEquals(self, node, vif):
        mac = node.find("mac").get("address")
        self.assertEqual(mac, vif['address'])

    def _assertTypeEquals(self,
                          node,
                          type,
                          attr,
                          source,
                          br_want,
                          prefix=None):
        self.assertEqual(node.get("type"), type)
        br_name = node.find(attr).get(source)
        if prefix is None:
            self.assertEqual(br_name, br_want)
        else:
            self.assertTrue(br_name.startswith(prefix))

    def _assertTypeAndMacEquals(self,
                                node,
                                type,
                                attr,
                                source,
                                vif,
                                br_want=None,
                                size=0,
                                prefix=None):
        ret = node.findall("filterref")
        self.assertEqual(len(ret), size)
        self._assertTypeEquals(node, type, attr, source, br_want, prefix)
        self._assertMacEquals(node, vif)

    def _assertModel(self, xml, model_want=None, driver_want=None):
        node = self._get_node(xml)
        if model_want is None:
            ret = node.findall("model")
            self.assertEqual(len(ret), 0)
        else:
            model = node.find("model").get("type")
            self.assertEqual(model, model_want)
        if driver_want is None:
            ret = node.findall("driver")
            self.assertEqual(len(ret), 0)
        else:
            driver = node.find("driver").get("name")
            self.assertEqual(driver, driver_want)

    def _get_conf(self):
        conf = vconfig.LibvirtConfigGuest()
        conf.virt_type = "qemu"
        conf.name = "fake-name"
        conf.uuid = "fake-uuid"
        conf.memory = 100 * 1024
        conf.vcpus = 4
        return conf

    def _get_instance_xml(self, driver, vif, image_meta=None):
        default_inst_type = flavors.get_default_flavor()
        extra_specs = default_inst_type['extra_specs'].items()
        quota_bandwith = self.bandwidth.items()
        default_inst_type['extra_specs'] = dict(extra_specs + quota_bandwith)
        conf = self._get_conf()
        nic = driver.get_config(self.instance, vif, image_meta,
                                default_inst_type)
        conf.add_device(nic)
        return conf.to_xml()

    def test_multiple_nics(self):
        conf = self._get_conf()
        # Tests multiple nic configuration and that target_dev is
        # set for each
        nics = [{
            'net_type': 'bridge',
            'mac_addr': '00:00:00:00:00:0b',
            'source_dev': 'b_source_dev',
            'target_dev': 'b_target_dev'
        }, {
            'net_type': 'ethernet',
            'mac_addr': '00:00:00:00:00:0e',
            'source_dev': 'e_source_dev',
            'target_dev': 'e_target_dev'
        }, {
            'net_type': 'direct',
            'mac_addr': '00:00:00:00:00:0d',
            'source_dev': 'd_source_dev',
            'target_dev': 'd_target_dev'
        }]

        for nic in nics:
            nic_conf = vconfig.LibvirtConfigGuestInterface()
            nic_conf.net_type = nic['net_type']
            nic_conf.target_dev = nic['target_dev']
            nic_conf.mac_addr = nic['mac_addr']
            nic_conf.source_dev = nic['source_dev']
            conf.add_device(nic_conf)

        xml = conf.to_xml()
        doc = etree.fromstring(xml)
        for nic in nics:
            path = "./devices/interface/[@type='%s']" % nic['net_type']
            node = doc.find(path)
            self.assertEqual(nic['net_type'], node.get("type"))
            self.assertEqual(nic['mac_addr'], node.find("mac").get("address"))
            self.assertEqual(nic['target_dev'], node.find("target").get("dev"))

    def test_model_novirtio(self):
        self.flags(libvirt_use_virtio_for_bridges=False, libvirt_type='kvm')

        d = vif.LibvirtGenericVIFDriver(self._get_conn())
        xml = self._get_instance_xml(d, self.vif_bridge)
        self._assertModel(xml)

    def test_model_kvm(self):
        self.flags(libvirt_use_virtio_for_bridges=True, libvirt_type='kvm')

        d = vif.LibvirtGenericVIFDriver(self._get_conn())
        xml = self._get_instance_xml(d, self.vif_bridge)

        self._assertModel(xml, "virtio")

    def test_model_kvm_custom(self):
        self.flags(libvirt_use_virtio_for_bridges=True, libvirt_type='kvm')

        d = vif.LibvirtGenericVIFDriver(self._get_conn())
        image_meta = {'properties': {'hw_vif_model': 'e1000'}}
        xml = self._get_instance_xml(d, self.vif_bridge, image_meta)
        self._assertModel(xml, "e1000")

    def test_model_kvm_bogus(self):
        self.flags(libvirt_use_virtio_for_bridges=True, libvirt_type='kvm')

        d = vif.LibvirtGenericVIFDriver(self._get_conn())
        image_meta = {'properties': {'hw_vif_model': 'acme'}}
        self.assertRaises(exception.UnsupportedHardware,
                          self._get_instance_xml, d, self.vif_bridge,
                          image_meta)

    def test_model_qemu(self):
        self.flags(libvirt_use_virtio_for_bridges=True, libvirt_type='qemu')

        d = vif.LibvirtGenericVIFDriver(self._get_conn())
        xml = self._get_instance_xml(d, self.vif_bridge)

        doc = etree.fromstring(xml)

        ret = doc.findall('./devices/interface/bandwidth')
        self.assertEqual(len(ret), 1)

        self._assertModel(xml, "virtio", "qemu")

    def test_model_xen(self):
        self.flags(libvirt_use_virtio_for_bridges=True, libvirt_type='xen')

        d = vif.LibvirtGenericVIFDriver(self._get_conn("xen:///system"))
        xml = self._get_instance_xml(d, self.vif_bridge)
        self._assertModel(xml)

    def test_generic_driver_none(self):
        d = vif.LibvirtGenericVIFDriver(self._get_conn())
        self.assertRaises(exception.NovaException, self._get_instance_xml, d,
                          self.vif_none)

    def _check_bridge_driver(self, d, vif, br_want):
        xml = self._get_instance_xml(d, vif)
        node = self._get_node(xml)
        self._assertTypeAndMacEquals(node, "bridge", "source", "bridge",
                                     self.vif_bridge, br_want, 1)

    def test_bridge_driver(self):
        d = vif.LibvirtBridgeDriver(self._get_conn())
        self._check_bridge_driver(d, self.vif_bridge,
                                  self.vif_bridge['network']['bridge'])

    def test_generic_driver_bridge(self):
        d = vif.LibvirtGenericVIFDriver(self._get_conn())
        self._check_bridge_driver(d, self.vif_bridge,
                                  self.vif_bridge['network']['bridge'])

    def test_neutron_bridge_driver(self):
        d = vif.NeutronLinuxBridgeVIFDriver(self._get_conn())
        br_want = 'brq' + self.vif_bridge_neutron['network']['id']
        br_want = br_want[:network_model.NIC_NAME_LEN]
        self._check_bridge_driver(d, self.vif_bridge_neutron, br_want)

    def _check_ivs_ethernet_driver(self, d, vif, dev_prefix):
        self.flags(firewall_driver="nova.virt.firewall.NoopFirewallDriver")
        xml = self._get_instance_xml(d, vif)
        node = self._get_node(xml)
        self._assertTypeAndMacEquals(node,
                                     "ethernet",
                                     "target",
                                     "dev",
                                     self.vif_ivs,
                                     prefix=dev_prefix)
        script = node.find("script").get("path")
        self.assertEquals(script, "")

    def _check_ovs_ethernet_driver(self, d, vif, dev_prefix):
        self.flags(firewall_driver="nova.virt.firewall.NoopFirewallDriver")
        xml = self._get_instance_xml(d, vif)
        node = self._get_node(xml)
        self._assertTypeAndMacEquals(node,
                                     "ethernet",
                                     "target",
                                     "dev",
                                     self.vif_ovs,
                                     prefix=dev_prefix)
        script = node.find("script").get("path")
        self.assertEquals(script, "")

    def test_ovs_ethernet_driver(self):
        d = vif.LibvirtGenericVIFDriver(self._get_conn(ver=9010))
        self._check_ovs_ethernet_driver(d, self.vif_ovs, "tap")

    def test_ivs_ethernet_driver(self):
        d = vif.LibvirtGenericVIFDriver(self._get_conn(ver=9010))
        self._check_ivs_ethernet_driver(d, self.vif_ivs, "tap")

    def _check_ivs_virtualport_driver(self, d, vif, want_iface_id):
        self.flags(firewall_driver="nova.virt.firewall.NoopFirewallDriver")
        xml = self._get_instance_xml(d, vif)
        node = self._get_node(xml)
        self._assertTypeAndMacEquals(node, "ethernet", "target", "dev", vif,
                                     vif['devname'])

    def _check_ovs_virtualport_driver(self, d, vif, want_iface_id):
        self.flags(firewall_driver="nova.virt.firewall.NoopFirewallDriver")
        xml = self._get_instance_xml(d, vif)
        node = self._get_node(xml)
        self._assertTypeAndMacEquals(node, "bridge", "source", "bridge", vif,
                                     "br0")
        vp = node.find("virtualport")
        self.assertEqual(vp.get("type"), "openvswitch")
        iface_id_found = False
        for p_elem in vp.findall("parameters"):
            iface_id = p_elem.get("interfaceid", None)
            if iface_id:
                self.assertEqual(iface_id, want_iface_id)
                iface_id_found = True

        self.assertTrue(iface_id_found)

    def test_ovs_virtualport_driver(self):
        d = vif.LibvirtOpenVswitchVirtualPortDriver(self._get_conn(ver=9011))
        want_iface_id = 'vif-xxx-yyy-zzz'
        self._check_ovs_virtualport_driver(d, self.vif_ovs_legacy,
                                           want_iface_id)

    def test_generic_ovs_virtualport_driver(self):
        d = vif.LibvirtGenericVIFDriver(self._get_conn(ver=9011))
        want_iface_id = self.vif_ovs['ovs_interfaceid']
        self._check_ovs_virtualport_driver(d, self.vif_ovs, want_iface_id)

    def test_generic_ivs_virtualport_driver(self):
        d = vif.LibvirtGenericVIFDriver(self._get_conn(ver=9011))
        want_iface_id = self.vif_ivs['ovs_interfaceid']
        self._check_ivs_virtualport_driver(d, self.vif_ivs, want_iface_id)

    def _check_neutron_hybrid_driver(self, d, vif, br_want):
        self.flags(firewall_driver="nova.virt.firewall.IptablesFirewallDriver")
        xml = self._get_instance_xml(d, vif)
        node = self._get_node(xml)
        self._assertTypeAndMacEquals(node, "bridge", "source", "bridge", vif,
                                     br_want, 1)

    def test_quantum_hybrid_driver(self):
        br_want = "qbr" + self.vif_ovs['id']
        br_want = br_want[:network_model.NIC_NAME_LEN]
        d = vif.LibvirtHybridOVSBridgeDriver(self._get_conn())
        self._check_neutron_hybrid_driver(d, self.vif_ovs_legacy, br_want)

    def test_generic_hybrid_driver(self):
        d = vif.LibvirtGenericVIFDriver(self._get_conn())
        br_want = "qbr" + self.vif_ovs['id']
        br_want = br_want[:network_model.NIC_NAME_LEN]
        self._check_neutron_hybrid_driver(d, self.vif_ovs, br_want)

    def test_ivs_hybrid_driver(self):
        d = vif.LibvirtGenericVIFDriver(self._get_conn())
        br_want = "qbr" + self.vif_ivs['id']
        br_want = br_want[:network_model.NIC_NAME_LEN]
        self._check_neutron_hybrid_driver(d, self.vif_ivs, br_want)

    def test_generic_8021qbh_driver(self):
        d = vif.LibvirtGenericVIFDriver(self._get_conn())
        xml = self._get_instance_xml(d, self.vif_8021qbh)
        node = self._get_node(xml)
        self._assertTypeEquals(node, "direct", "source", "dev", "eth0")
        self._assertMacEquals(node, self.vif_8021qbh)
        vp = node.find("virtualport")
        self.assertEqual(vp.get("type"), "802.1Qbh")
        profile_id_found = False
        for p_elem in vp.findall("parameters"):
            wantparams = self.vif_8021qbh['qbh_params']
            profile_id = p_elem.get("profileid", None)
            if profile_id:
                self.assertEqual(profile_id, wantparams['profileid'])
                profile_id_found = True

        self.assertTrue(profile_id_found)

    def test_generic_iovisor_driver(self):
        d = vif.LibvirtGenericVIFDriver(self._get_conn())
        self.flags(firewall_driver="nova.virt.firewall.NoopFirewallDriver")
        br_want = self.vif_ivs['devname']
        xml = self._get_instance_xml(d, self.vif_ivs)
        node = self._get_node(xml)
        self._assertTypeAndMacEquals(node, "ethernet", "target", "dev",
                                     self.vif_ivs, br_want)

    def test_generic_8021qbg_driver(self):
        d = vif.LibvirtGenericVIFDriver(self._get_conn())
        xml = self._get_instance_xml(d, self.vif_8021qbg)

        node = self._get_node(xml)
        self._assertTypeEquals(node, "direct", "source", "dev", "eth0")
        self._assertMacEquals(node, self.vif_8021qbg)

        vp = node.find("virtualport")
        self.assertEqual(vp.get("type"), "802.1Qbg")
        manager_id_found = False
        type_id_found = False
        typeversion_id_found = False
        instance_id_found = False
        for p_elem in vp.findall("parameters"):
            wantparams = self.vif_8021qbg['qbg_params']
            manager_id = p_elem.get("managerid", None)
            type_id = p_elem.get("typeid", None)
            typeversion_id = p_elem.get("typeidversion", None)
            instance_id = p_elem.get("instanceid", None)
            if manager_id:
                self.assertEqual(manager_id, wantparams['managerid'])
                manager_id_found = True
            if type_id:
                self.assertEqual(type_id, wantparams['typeid'])
                type_id_found = True
            if typeversion_id:
                self.assertEqual(typeversion_id, wantparams['typeidversion'])
                typeversion_id_found = True
            if instance_id:
                self.assertEqual(instance_id, wantparams['instanceid'])
                instance_id_found = True

        self.assertTrue(manager_id_found)
        self.assertTrue(type_id_found)
        self.assertTrue(typeversion_id_found)
        self.assertTrue(instance_id_found)
コード例 #19
0
    def _build_network_info_model(self, context, instance, networks=None):
        search_opts = {
            'tenant_id': instance['project_id'],
            'device_id': instance['uuid'],
        }
        client = quantumv2.get_client(context, admin=True)
        data = client.list_ports(**search_opts)
        ports = data.get('ports', [])
        if networks is None:
            networks = self._get_available_networks(context,
                                                    instance['project_id'])

        # ensure ports are in preferred network order, and filter out
        # those not attached to one of the provided list of networks
        net_ids = [n['id'] for n in networks]
        ports = [port for port in ports if port['network_id'] in net_ids]
        _ensure_requested_network_ordering(lambda x: x['network_id'], ports,
                                           net_ids)

        nw_info = network_model.NetworkInfo()
        for port in ports:
            # NOTE(danms): This loop can't fail to find a network since we
            # filtered ports to only the ones matching networks above.
            for net in networks:
                if port['network_id'] == net['id']:
                    network_name = net['name']
                    break

            network_IPs = []
            for fixed_ip in port['fixed_ips']:
                fixed = network_model.FixedIP(address=fixed_ip['ip_address'])
                floats = self._get_floating_ips_by_fixed_and_port(
                    client, fixed_ip['ip_address'], port['id'])
                for ip in floats:
                    fip = network_model.IP(address=ip['floating_ip_address'],
                                           type='floating')
                    fixed.add_floating_ip(fip)
                network_IPs.append(fixed)

            subnets = self._get_subnets_from_port(context, port)
            for subnet in subnets:
                subnet['ips'] = [
                    fixed_ip for fixed_ip in network_IPs
                    if fixed_ip.is_in_subnet(subnet)
                ]

            bridge = None
            ovs_interfaceid = None
            # Network model metadata
            should_create_bridge = None
            vif_type = port.get('binding:vif_type')
            # TODO(berrange) Quantum should pass the bridge name
            # in another binding metadata field
            if vif_type == network_model.VIF_TYPE_OVS:
                bridge = CONF.quantum_ovs_bridge
                ovs_interfaceid = port['id']
            elif vif_type == network_model.VIF_TYPE_BRIDGE:
                bridge = "brq" + port['network_id']
                should_create_bridge = True

            if bridge is not None:
                bridge = bridge[:network_model.NIC_NAME_LEN]

            devname = "tap" + port['id']
            devname = devname[:network_model.NIC_NAME_LEN]

            network = network_model.Network(id=port['network_id'],
                                            bridge=bridge,
                                            injected=CONF.flat_injected,
                                            label=network_name,
                                            tenant_id=net['tenant_id'])
            network['subnets'] = subnets
            if should_create_bridge is not None:
                network['should_create_bridge'] = should_create_bridge
            nw_info.append(
                network_model.VIF(id=port['id'],
                                  address=port['mac_address'],
                                  network=network,
                                  type=port.get('binding:vif_type'),
                                  ovs_interfaceid=ovs_interfaceid,
                                  devname=devname))
        return nw_info
コード例 #20
0
ファイル: test_vifs.py プロジェクト: psviderski/nova-docker
class DockerGenericVIFDriverTestCase(test.TestCase):

    REQUIRES_LOCKING = True
    gateway_bridge_4 = network_model.IP(address='10.11.12.1', type='gateway')
    dns_bridge_4 = network_model.IP(address='8.8.8.8', type=None)
    ips_bridge_4 = [
        network_model.IP(address='101.168.1.9', type='fixed', version=4)
    ]

    subnet_bridge_4 = network_model.Subnet(cidr='10.11.1.0/24',
                                           dns=[dns_bridge_4],
                                           gateway=gateway_bridge_4,
                                           ips=ips_bridge_4,
                                           routes=None)

    network_bridge = network_model.Network(id='network-id-xxx-yyy-zzz',
                                           bridge='br100',
                                           label=None,
                                           subnets=[subnet_bridge_4],
                                           bridge_interface='eth0')

    vif_bridge = network_model.VIF(id='920be2f4-2b98-411e-890a-69bcabb2a5a0',
                                   address='00:11:22:33:44:55',
                                   network=network_bridge,
                                   type=network_model.VIF_TYPE_BRIDGE)

    def setUp(self):
        super(DockerGenericVIFDriverTestCase, self).setUp()

        def fake_fe_random_mac(self):
            return 'fe:16:3e:ff:ff:ff'

        self.stubs.Set(vifs.DockerGenericVIFDriver, '_fe_random_mac',
                       fake_fe_random_mac)

    def test_plug_vifs_bridge(self):
        calls = [
            mock.call('ip',
                      'link',
                      'add',
                      'name',
                      'tap920be2f4-2b',
                      'type',
                      'veth',
                      'peer',
                      'name',
                      'ns920be2f4-2b',
                      run_as_root=True),
            mock.call('ip',
                      'link',
                      'set',
                      'tap920be2f4-2b',
                      'address',
                      'fe:16:3e:ff:ff:ff',
                      run_as_root=True),
            mock.call('brctl',
                      'addif',
                      'br100',
                      'tap920be2f4-2b',
                      run_as_root=True),
            mock.call('ip',
                      'link',
                      'set',
                      'tap920be2f4-2b',
                      'up',
                      run_as_root=True)
        ]
        network_info = [self.vif_bridge]
        with mock.patch('nova.utils.execute') as ex:
            driver = docker_driver.DockerDriver(object)
            driver.plug_vifs({'name': 'fake_instance'}, network_info)
            ex.assert_has_calls(calls)

    def test_plug_vifs_bridge_two_interfaces(self):
        calls = [
            # interface 1
            mock.call('ip',
                      'link',
                      'add',
                      'name',
                      'tap920be2f4-2b',
                      'type',
                      'veth',
                      'peer',
                      'name',
                      'ns920be2f4-2b',
                      run_as_root=True),
            mock.call('ip',
                      'link',
                      'set',
                      'tap920be2f4-2b',
                      'address',
                      'fe:16:3e:ff:ff:ff',
                      run_as_root=True),
            mock.call('brctl',
                      'addif',
                      'br100',
                      'tap920be2f4-2b',
                      run_as_root=True),
            mock.call('ip',
                      'link',
                      'set',
                      'tap920be2f4-2b',
                      'up',
                      run_as_root=True),
            # interface 2
            mock.call('ip',
                      'link',
                      'add',
                      'name',
                      'tap920be2f4-2b',
                      'type',
                      'veth',
                      'peer',
                      'name',
                      'ns920be2f4-2b',
                      run_as_root=True),
            mock.call('ip',
                      'link',
                      'set',
                      'tap920be2f4-2b',
                      'address',
                      'fe:16:3e:ff:ff:ff',
                      run_as_root=True),
            mock.call('brctl',
                      'addif',
                      'br100',
                      'tap920be2f4-2b',
                      run_as_root=True),
            mock.call('ip',
                      'link',
                      'set',
                      'tap920be2f4-2b',
                      'up',
                      run_as_root=True),
        ]
        network_info = [self.vif_bridge, self.vif_bridge]
        with mock.patch('nova.utils.execute') as ex:
            driver = docker_driver.DockerDriver(object)
            driver.plug_vifs({'name': 'fake_instance'}, network_info)
            ex.assert_has_calls(calls)

    def test_plug_vifs_ovs(self):
        iface_id = '920be2f4-2b98-411e-890a-69bcabb2a5a0'
        calls = [
            mock.call('ip',
                      'link',
                      'add',
                      'name',
                      'tap920be2f4-2b',
                      'type',
                      'veth',
                      'peer',
                      'name',
                      'ns920be2f4-2b',
                      run_as_root=True),
            mock.call('ovs-vsctl',
                      '--timeout=120',
                      '--',
                      '--if-exists',
                      'del-port',
                      'tap920be2f4-2b',
                      '--',
                      'add-port',
                      'br-int',
                      'tap920be2f4-2b',
                      '--',
                      'set',
                      'Interface',
                      'tap920be2f4-2b',
                      'external-ids:iface-id=%s' % iface_id,
                      'external-ids:iface-status=active',
                      'external-ids:attached-mac=00:11:22:33:44:55',
                      'external-ids:vm-uuid=instance_uuid',
                      run_as_root=True),
            mock.call('ip',
                      'link',
                      'set',
                      'tap920be2f4-2b',
                      'up',
                      run_as_root=True),
        ]
        network_info = [{
            'network': {
                'bridge':
                'br-int',
                'subnets': [{
                    'gateway': {
                        'address': '10.11.12.1'
                    },
                    'cidr':
                    '10.11.12.0/24',
                    'ips': [{
                        'address': '10.11.12.3',
                        'type': 'fixed',
                        'version': 4
                    }]
                }]
            },
            'address': '00:11:22:33:44:55',
            'id': iface_id,
            'type': network_model.VIF_TYPE_OVS
        }]
        with mock.patch('nova.utils.execute') as ex:
            driver = docker_driver.DockerDriver(object)
            driver.plug_vifs({
                'name': 'fake_instance',
                'uuid': 'instance_uuid'
            }, network_info)
            ex.assert_has_calls(calls)

    def test_unplug_vifs_ovs(self):
        iface_id = '920be2f4-2b98-411e-890a-69bcabb2a5a0'
        calls = [
            mock.call('ovs-vsctl',
                      '--timeout=120',
                      '--',
                      '--if-exists',
                      'del-port',
                      'br-int',
                      'tap920be2f4-2b',
                      run_as_root=True)
        ]
        network_info = [{
            'network': {
                'bridge':
                'br-int',
                'subnets': [{
                    'gateway': {
                        'address': '10.11.12.1'
                    },
                    'cidr':
                    '10.11.12.0/24',
                    'ips': [{
                        'address': '10.11.12.3',
                        'type': 'fixed',
                        'version': 4
                    }]
                }]
            },
            'devname': 'tap920be2f4-2b',
            'address': '00:11:22:33:44:55',
            'id': iface_id,
            'type': network_model.VIF_TYPE_OVS
        }]
        with mock.patch('nova.utils.execute') as ex:
            driver = docker_driver.DockerDriver(object)
            driver.unplug_vifs(
                {
                    'name': 'fake_instance',
                    'uuid': 'instance_uuid'
                }, network_info)
            ex.assert_has_calls(calls)

    @mock.patch.object(docker_driver.DockerDriver,
                       '_find_container_by_name',
                       return_value={'id': 'fake_id'})
    @mock.patch.object(docker_driver.DockerDriver,
                       '_find_container_pid',
                       return_value=1234)
    def test_attach_vifs(self, mock_find_by_name, mock_find_pid):
        calls = [
            mock.call('ln',
                      '-sf',
                      '/proc/1234/ns/net',
                      '/var/run/netns/fake_id',
                      run_as_root=True),
            mock.call('ip',
                      'link',
                      'set',
                      'ns920be2f4-2b',
                      'netns',
                      'fake_id',
                      run_as_root=True),
            mock.call('ip',
                      'netns',
                      'exec',
                      'fake_id',
                      'ip',
                      'link',
                      'set',
                      'ns920be2f4-2b',
                      'address',
                      '00:11:22:33:44:55',
                      run_as_root=True),
            mock.call('ip',
                      'netns',
                      'exec',
                      'fake_id',
                      'ifconfig',
                      'ns920be2f4-2b',
                      '10.11.12.3/24',
                      run_as_root=True),
            mock.call('ip',
                      'netns',
                      'exec',
                      'fake_id',
                      'ip',
                      'route',
                      'replace',
                      'default',
                      'via',
                      '10.11.12.1',
                      'dev',
                      'ns920be2f4-2b',
                      run_as_root=True)
        ]
        network_info = [{
            'network': {
                'bridge':
                'br100',
                'subnets': [{
                    'gateway': {
                        'address': '10.11.12.1'
                    },
                    'cidr':
                    '10.11.12.0/24',
                    'ips': [{
                        'address': '10.11.12.3',
                        'type': 'fixed',
                        'version': 4
                    }]
                }]
            },
            'address': '00:11:22:33:44:55',
            'id': '920be2f4-2b98-411e-890a-69bcabb2a5a0',
            'type': network_model.VIF_TYPE_BRIDGE
        }]
        with mock.patch('nova.utils.execute') as ex:
            driver = docker_driver.DockerDriver(object)
            driver._attach_vifs({'name': 'fake_instance'}, network_info)
            ex.assert_has_calls(calls)

    @mock.patch.object(docker_driver.DockerDriver,
                       '_find_container_by_name',
                       return_value={'id': 'fake_id'})
    @mock.patch.object(docker_driver.DockerDriver,
                       '_find_container_pid',
                       return_value=1234)
    def test_attach_vifs_two_interfaces(self, mock_find_by_name,
                                        mock_find_pid):
        calls = [
            mock.call('ln',
                      '-sf',
                      '/proc/1234/ns/net',
                      '/var/run/netns/fake_id',
                      run_as_root=True),
            # interface 1
            mock.call('ip',
                      'link',
                      'set',
                      'ns920be2f4-2b',
                      'netns',
                      'fake_id',
                      run_as_root=True),
            mock.call('ip',
                      'netns',
                      'exec',
                      'fake_id',
                      'ip',
                      'link',
                      'set',
                      'ns920be2f4-2b',
                      'address',
                      '00:11:22:33:44:55',
                      run_as_root=True),
            mock.call('ip',
                      'netns',
                      'exec',
                      'fake_id',
                      'ifconfig',
                      'ns920be2f4-2b',
                      '10.11.12.3/24',
                      run_as_root=True),
            mock.call('ip',
                      'netns',
                      'exec',
                      'fake_id',
                      'ip',
                      'route',
                      'replace',
                      'default',
                      'via',
                      '10.11.12.1',
                      'dev',
                      'ns920be2f4-2b',
                      run_as_root=True),
            # interface 2
            mock.call('ip',
                      'link',
                      'set',
                      'ns920be2f4-2b',
                      'netns',
                      'fake_id',
                      run_as_root=True),
            mock.call('ip',
                      'netns',
                      'exec',
                      'fake_id',
                      'ip',
                      'link',
                      'set',
                      'ns920be2f4-2b',
                      'address',
                      '00:11:22:33:44:66',
                      run_as_root=True),
            mock.call('ip',
                      'netns',
                      'exec',
                      'fake_id',
                      'ifconfig',
                      'ns920be2f4-2b',
                      '10.13.12.3/24',
                      run_as_root=True),
            mock.call('ip',
                      'netns',
                      'exec',
                      'fake_id',
                      'ip',
                      'route',
                      'replace',
                      'default',
                      'via',
                      '10.13.12.1',
                      'dev',
                      'ns920be2f4-2b',
                      run_as_root=True)
        ]
        network_info = [{
            'network': {
                'bridge':
                'br100',
                'subnets': [{
                    'gateway': {
                        'address': '10.11.12.1'
                    },
                    'cidr':
                    '10.11.12.0/24',
                    'ips': [{
                        'address': '10.11.12.3',
                        'type': 'fixed',
                        'version': 4
                    }],
                }]
            },
            'address': '00:11:22:33:44:55',
            'type': network_model.VIF_TYPE_BRIDGE,
            'id': '920be2f4-2b98-411e-890a-69bcabb2a5a0'
        }, {
            'network': {
                'bridge':
                'br100',
                'subnets': [{
                    'gateway': {
                        'address': '10.13.12.1'
                    },
                    'cidr':
                    '10.13.12.0/24',
                    'ips': [{
                        'address': '10.13.12.3',
                        'type': 'fixed',
                        'version': 4
                    }]
                }]
            },
            'address': '00:11:22:33:44:66',
            'type': network_model.VIF_TYPE_BRIDGE,
            'id': '920be2f4-2b98-411e-890a-69bcabb2a5a0'
        }]
        with mock.patch('nova.utils.execute') as ex:
            driver = docker_driver.DockerDriver(object)
            driver._attach_vifs({'name': 'fake_instance'}, network_info)
            ex.assert_has_calls(calls)
コード例 #21
0
    def setUp(self, update_host_status):
        super(ZVMDriverTestCases, self).setUp()

        self.flags(host='fakehost',
                   my_ip='10.1.1.10',
                   instance_name_template = 'test%04x')
        update_host_status.return_value = [{
            'host': 'fakehost',
            'allowed_vm_type': 'zLinux',
            'vcpus': 10,
            'vcpus_used': 10,
            'cpu_info': {'Architecture': 's390x', 'CEC model': '2097'},
            'disk_total': 406105,
            'disk_used': 367263,
            'disk_available': 38842,
            'host_memory_total': 16384,
            'host_memory_free': 8096,
            'hypervisor_type': 'zvm',
            'hypervisor_version': '630',
            'hypervisor_hostname': 'fakenode',
            'supported_instances': [('s390x', 'zvm', 'hvm')],
            'ipl_time': 'IPL at 03/13/14 21:43:12 EDT',
        }]
        self.driver = driver.ZVMDriver(fake.FakeVirtAPI())
        self._context = context.RequestContext('fake_user', 'fake_project')
        self._uuid = uuidsentinel.foo
        self._image_id = uuidsentinel.foo
        self._instance_values = {
            'display_name': 'test',
            'uuid': self._uuid,
            'vcpus': 1,
            'memory_mb': 1024,
            'image_ref': self._image_id,
            'root_gb': 3,
        }
        self._instance = fake_instance.fake_instance_obj(
                                self._context, **self._instance_values)
        self._flavor = objects.Flavor(name='testflavor', memory_mb=512,
                                      vcpus=1, root_gb=3, ephemeral_gb=10,
                                      swap=0, extra_specs={})
        self._instance.flavor = self._flavor

        eph_disks = [{'guest_format': u'ext3',
                      'device_name': u'/dev/sdb',
                      'disk_bus': None,
                      'device_type': None,
                      'size': 1},
                     {'guest_format': u'ext4',
                      'device_name': u'/dev/sdc',
                      'disk_bus': None,
                      'device_type': None,
                      'size': 2}]
        self._block_device_info = {'swap': None,
                                   'root_device_name': u'/dev/sda',
                                   'ephemerals': eph_disks,
                                   'block_device_mapping': []}

        fake_image_meta = {'status': 'active',
                                 'properties': {'os_distro': 'rhel7.2'},
                                 'name': 'rhel72eckdimage',
                                 'deleted': False,
                                 'container_format': 'bare',
                                 'disk_format': 'raw',
                                 'id': self._image_id,
                                 'owner': 'cfc26f9d6af948018621ab00a1675310',
                                 'checksum': 'b026cd083ef8e9610a29eaf71459cc',
                                 'min_disk': 0,
                                 'is_public': False,
                                 'deleted_at': None,
                                 'min_ram': 0,
                                 'size': 465448142}
        self._image_meta = objects.ImageMeta.from_dict(fake_image_meta)
        subnet_4 = network_model.Subnet(cidr='192.168.0.1/24',
                                        dns=[network_model.IP('192.168.0.1')],
                                        gateway=
                                            network_model.IP('192.168.0.1'),
                                        ips=[
                                            network_model.IP('192.168.0.100')],
                                        routes=None)
        network = network_model.Network(id=0,
                                        bridge='fa0',
                                        label='fake',
                                        subnets=[subnet_4],
                                        vlan=None,
                                        bridge_interface=None,
                                        injected=True)
        self._network_values = {
            'id': None,
            'address': 'DE:AD:BE:EF:00:00',
            'network': network,
            'type': network_model.VIF_TYPE_OVS,
            'devname': None,
            'ovs_interfaceid': None,
            'rxtx_cap': 3
        }
        self._network_info = network_model.NetworkInfo([
                network_model.VIF(**self._network_values)
        ])
コード例 #22
0
    def _build_network_info_model(self, context, instance, networks=None):
        """This is a slightly different version than the super.

        Adds support to relax the filters for the service tenant.
        Workaround the fact that nova doesn't like ipv6 subnet only
        """
        search_opts = {'device_id': instance['uuid']}
        # NOTE(rods): The following "if" statement is not present in the
        #            parent method.
        if context.project_name != 'service' or context.user_name != 'neutron':
            search_opts['tenant_id'] = instance['project_id']

        client = neutronv2.get_client(context, admin=True)
        data = client.list_ports(**search_opts)
        ports = data.get('ports', [])
        if networks is None:
            # retrieve networks from info_cache to get correct nic order
            network_cache = self.conductor_api.instance_get_by_uuid(
                context, instance['uuid'])['info_cache']['network_info']
            network_cache = jsonutils.loads(network_cache)
            net_ids = [iface['network']['id'] for iface in network_cache]
            networks = self._get_available_networks(context,
                                                    instance['project_id'],
                                                    net_ids)  # akanda change

        # ensure ports are in preferred network order, and filter out
        # those not attached to one of the provided list of networks
        else:
            net_ids = [n['id'] for n in networks]
        ports = [port for port in ports if port['network_id'] in net_ids]
        api._ensure_requested_network_ordering(lambda x: x['network_id'],
                                               ports, net_ids)

        nw_info = network_model.NetworkInfo()
        for port in ports:
            network_IPs = self._nw_info_get_ips(client, port)
            subnets = self._nw_info_get_subnets(context, port, network_IPs)

            # Nova does not like only IPv6, so let's lie and add a fake
            # link-local IPv4.  Neutron provides DHCP so this is ignored.
            # NOTE(rods): This workaround is not present in the parent method
            if not any(ip['version'] == 4 for ip in network_IPs):
                nova_lie = {
                    'cidr': '169.254.0.0/16',
                    'gateway': network_model.IP(address='', type='gateway'),
                    'ips': [network_model.FixedIP(address='169.254.10.20')]
                }
                subnets.append(nova_lie)

            devname = "tap" + port['id']
            devname = devname[:network_model.NIC_NAME_LEN]

            network, ovs_interfaceid = self._nw_info_build_network(
                port, networks, subnets)

            nw_info.append(
                network_model.VIF(id=port['id'],
                                  address=port['mac_address'],
                                  network=network,
                                  type=port.get('binding:vif_type'),
                                  ovs_interfaceid=ovs_interfaceid,
                                  devname=devname))
        return nw_info
コード例 #23
0
ファイル: api.py プロジェクト: danielscai/openstack_patch
    def _build_network_info_model(self, context, instance, networks=None):
        search_opts = {
            'tenant_id': instance['project_id'],
            'device_id': instance['uuid'],
        }
        client = quantumv2.get_client(context, admin=True)
        data = client.list_ports(**search_opts)
        ports = data.get('ports', [])
        if networks is None:
            networks = self._get_available_networks(context,
                                                    instance['project_id'])
        else:
            # ensure ports are in preferred network order
            _ensure_requested_network_ordering(lambda x: x['network_id'],
                                               ports,
                                               [n['id'] for n in networks])

        nw_info = network_model.NetworkInfo()
        for port in ports:
            network_name = None
            for net in networks:
                if port['network_id'] == net['id']:
                    network_name = net['name']
                    break

            if network_name is None:
                raise exception.NotFound(
                    _('Network %(net)s for '
                      'port %(port_id)s not found!') % {
                          'net': port['network_id'],
                          'port': port['id']
                      })

            network_IPs = []
            for fixed_ip in port['fixed_ips']:
                fixed = network_model.FixedIP(address=fixed_ip['ip_address'])
                floats = self._get_floating_ips_by_fixed_and_port(
                    client, fixed_ip['ip_address'], port['id'])
                for ip in floats:
                    fip = network_model.IP(address=ip['floating_ip_address'],
                                           type='floating')
                    fixed.add_floating_ip(fip)
                network_IPs.append(fixed)

            subnets = self._get_subnets_from_port(context, port)
            for subnet in subnets:
                subnet['ips'] = [
                    fixed_ip for fixed_ip in network_IPs
                    if fixed_ip.is_in_subnet(subnet)
                ]

            bridge = None
            ovs_interfaceid = None
            # Network model metadata
            should_create_bridge = None
            vif_type = port.get('binding:vif_type')
            # TODO(berrange) Quantum should pass the bridge name
            # in another binding metadata field
            if vif_type == network_model.VIF_TYPE_OVS:
                bridge = CONF.quantum_ovs_bridge
                ovs_interfaceid = port['id']
            elif vif_type == network_model.VIF_TYPE_BRIDGE:
                bridge = "brq" + port['network_id']
                should_create_bridge = True

            if bridge is not None:
                bridge = bridge[:network_model.NIC_NAME_LEN]

            devname = "tap" + port['id']
            devname = devname[:network_model.NIC_NAME_LEN]

            network = network_model.Network(id=port['network_id'],
                                            bridge=bridge,
                                            injected=CONF.flat_injected,
                                            label=network_name,
                                            tenant_id=net['tenant_id'])
            network['subnets'] = subnets
            if should_create_bridge is not None:
                network['should_create_bridge'] = should_create_bridge
            nw_info.append(
                network_model.VIF(id=port['id'],
                                  address=port['mac_address'],
                                  network=network,
                                  type=port.get('binding:vif_type'),
                                  ovs_interfaceid=ovs_interfaceid,
                                  devname=devname))
        return nw_info
コード例 #24
0
ファイル: test_vif.py プロジェクト: zhatin/nova-lxd
#
#    Unless required by applicable law or agreed to in writing, software
#    distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
#    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
#    License for the specific language governing permissions and limitations
#    under the License.
import mock

from nova import context
from nova import exception
from nova.network import model as network_model
from nova import test
from nova.tests.unit import fake_instance
from nova.virt.lxd import vif

GATEWAY = network_model.IP(address='101.168.1.1', type='gateway')
DNS_BRIDGE = network_model.IP(address='8.8.8.8', type=None)
SUBNET = network_model.Subnet(cidr='101.168.1.0/24',
                              dns=[DNS_BRIDGE],
                              gateway=GATEWAY,
                              routes=None,
                              dhcp_server='191.168.1.1')
NETWORK = network_model.Network(id='ab7b876b-2c1c-4bb2-afa1-f9f4b6a28053',
                                bridge='br0',
                                label=None,
                                subnets=[SUBNET],
                                bridge_interface=None,
                                vlan=99,
                                mtu=1000)
OVS_VIF = network_model.VIF(
    id='da5cc4bf-f16c-4807-a0b6-911c7c67c3f8',
コード例 #25
0
class LibvirtVifTestCase(test.TestCase):

    gateway_bridge_4 = network_model.IP(address='101.168.1.1', type='gateway')
    dns_bridge_4 = network_model.IP(address='8.8.8.8', type=None)
    ips_bridge_4 = [network_model.IP(address='101.168.1.9', type=None)]
    subnet_bridge_4 = network_model.Subnet(cidr='101.168.1.0/24',
                                           dns=[dns_bridge_4],
                                           gateway=gateway_bridge_4,
                                           routes=None,
                                           dhcp_server='191.168.1.1')

    gateway_bridge_6 = network_model.IP(address='101:1db9::1', type='gateway')
    subnet_bridge_6 = network_model.Subnet(cidr='101:1db9::/64',
                                           dns=None,
                                           gateway=gateway_bridge_6,
                                           ips=None,
                                           routes=None)

    network_bridge = network_model.Network(
        id='network-id-xxx-yyy-zzz',
        bridge='br0',
        label=None,
        subnets=[subnet_bridge_4, subnet_bridge_6],
        bridge_interface='eth0',
        vlan=99)

    vif_bridge = network_model.VIF(id='vif-xxx-yyy-zzz',
                                   address='ca:fe:de:ad:be:ef',
                                   network=network_bridge,
                                   type=network_model.VIF_TYPE_BRIDGE,
                                   devname='tap-xxx-yyy-zzz',
                                   ovs_interfaceid=None)

    network_bridge_neutron = network_model.Network(
        id='network-id-xxx-yyy-zzz',
        bridge=None,
        label=None,
        subnets=[subnet_bridge_4, subnet_bridge_6],
        bridge_interface='eth0',
        vlan=99)

    vif_bridge_neutron = network_model.VIF(id='vif-xxx-yyy-zzz',
                                           address='ca:fe:de:ad:be:ef',
                                           network=network_bridge_neutron,
                                           type=None,
                                           devname='tap-xxx-yyy-zzz',
                                           ovs_interfaceid='aaa-bbb-ccc')

    network_ovs = network_model.Network(
        id='network-id-xxx-yyy-zzz',
        bridge='br0',
        label=None,
        subnets=[subnet_bridge_4, subnet_bridge_6],
        bridge_interface=None,
        vlan=99)

    network_ivs = network_model.Network(
        id='network-id-xxx-yyy-zzz',
        bridge='br0',
        label=None,
        subnets=[subnet_bridge_4, subnet_bridge_6],
        bridge_interface=None,
        vlan=99)

    vif_ovs = network_model.VIF(id='vif-xxx-yyy-zzz',
                                address='ca:fe:de:ad:be:ef',
                                network=network_ovs,
                                type=network_model.VIF_TYPE_OVS,
                                devname='tap-xxx-yyy-zzz',
                                ovs_interfaceid='aaa-bbb-ccc')

    vif_ovs_hybrid = network_model.VIF(id='vif-xxx-yyy-zzz',
                                       address='ca:fe:de:ad:be:ef',
                                       network=network_ovs,
                                       type=network_model.VIF_TYPE_OVS,
                                       details={
                                           'ovs_hybrid_plug': True,
                                           'port_filter': True
                                       },
                                       devname='tap-xxx-yyy-zzz',
                                       ovs_interfaceid='aaa-bbb-ccc')

    vif_ovs_filter_cap = network_model.VIF(id='vif-xxx-yyy-zzz',
                                           address='ca:fe:de:ad:be:ef',
                                           network=network_ovs,
                                           type=network_model.VIF_TYPE_OVS,
                                           details={'port_filter': True},
                                           devname='tap-xxx-yyy-zzz',
                                           ovs_interfaceid='aaa-bbb-ccc')

    vif_ovs_legacy = network_model.VIF(id='vif-xxx-yyy-zzz',
                                       address='ca:fe:de:ad:be:ef',
                                       network=network_ovs,
                                       type=None,
                                       devname=None,
                                       ovs_interfaceid=None)

    vif_ivs = network_model.VIF(id='vif-xxx-yyy-zzz',
                                address='ca:fe:de:ad:be:ef',
                                network=network_ivs,
                                type=network_model.VIF_TYPE_IVS,
                                devname='tap-xxx-yyy-zzz',
                                ovs_interfaceid='aaa-bbb-ccc')

    vif_ivs_legacy = network_model.VIF(id='vif-xxx-yyy-zzz',
                                       address='ca:fe:de:ad:be:ef',
                                       network=network_ovs,
                                       type=None,
                                       devname=None,
                                       ovs_interfaceid='aaa')

    vif_none = network_model.VIF(id='vif-xxx-yyy-zzz',
                                 address='ca:fe:de:ad:be:ef',
                                 network=network_bridge,
                                 type=None,
                                 devname='tap-xxx-yyy-zzz',
                                 ovs_interfaceid=None)

    network_8021 = network_model.Network(
        id='network-id-xxx-yyy-zzz',
        bridge=None,
        label=None,
        subnets=[subnet_bridge_4, subnet_bridge_6],
        interface='eth0',
        vlan=99)

    vif_8021qbh = network_model.VIF(
        id='vif-xxx-yyy-zzz',
        address='ca:fe:de:ad:be:ef',
        network=network_8021,
        type=network_model.VIF_TYPE_802_QBH,
        devname='tap-xxx-yyy-zzz',
        ovs_interfaceid=None,
        qbh_params=network_model.VIF8021QbhParams(profileid="xxx-yyy-zzz"))

    vif_8021qbg = network_model.VIF(id='vif-xxx-yyy-zzz',
                                    address='ca:fe:de:ad:be:ef',
                                    network=network_8021,
                                    type=network_model.VIF_TYPE_802_QBG,
                                    devname='tap-xxx-yyy-zzz',
                                    ovs_interfaceid=None,
                                    qbg_params=network_model.VIF8021QbgParams(
                                        managerid="xxx-yyy-zzz",
                                        typeid="aaa-bbb-ccc",
                                        typeidversion="1",
                                        instanceid="ddd-eee-fff"))

    network_mlnx = network_model.Network(
        id='network-id-xxx-yyy-zzz',
        label=None,
        bridge=None,
        subnets=[subnet_bridge_4, subnet_bridge_6],
        interface='eth0')

    network_midonet = network_model.Network(id='network-id-xxx-yyy-zzz',
                                            label=None,
                                            bridge=None,
                                            subnets=[subnet_bridge_4],
                                            interface='eth0')

    vif_mlnx = network_model.VIF(id='vif-xxx-yyy-zzz',
                                 address='ca:fe:de:ad:be:ef',
                                 network=network_mlnx,
                                 type=network_model.VIF_TYPE_MLNX_DIRECT,
                                 devname='tap-xxx-yyy-zzz')

    vif_midonet = network_model.VIF(id='vif-xxx-yyy-zzz',
                                    address='ca:fe:de:ad:be:ef',
                                    network=network_midonet,
                                    type=network_model.VIF_TYPE_MIDONET,
                                    devname='tap-xxx-yyy-zzz')

    vif_iovisor = network_model.VIF(id='vif-xxx-yyy-zzz',
                                    address='ca:fe:de:ad:be:ef',
                                    network=network_bridge,
                                    type=network_model.VIF_TYPE_IOVISOR,
                                    devname='tap-xxx-yyy-zzz',
                                    ovs_interfaceid=None)

    instance = {'name': 'instance-name', 'uuid': 'instance-uuid'}

    bandwidth = {
        'quota:vif_inbound_peak': '200',
        'quota:vif_outbound_peak': '20',
        'quota:vif_inbound_average': '100',
        'quota:vif_outbound_average': '10',
        'quota:vif_inbound_burst': '300',
        'quota:vif_outbound_burst': '30'
    }

    def setUp(self):
        super(LibvirtVifTestCase, self).setUp()
        self.flags(allow_same_net_traffic=True)
        self.executes = []

        def fake_execute(*cmd, **kwargs):
            self.executes.append(cmd)
            return None, None

        self.stubs.Set(utils, 'execute', fake_execute)

    def _get_conn(self, uri="qemu:///session", ver=None):
        def __inner():
            if ver is None:
                return fakelibvirt.Connection(uri, False)
            else:
                return fakelibvirt.Connection(uri, False, ver)

        return __inner

    def _get_node(self, xml):
        doc = etree.fromstring(xml)
        ret = doc.findall('./devices/interface')
        self.assertEqual(len(ret), 1)
        return ret[0]

    def _assertMacEquals(self, node, vif):
        mac = node.find("mac").get("address")
        self.assertEqual(mac, vif['address'])

    def _assertTypeEquals(self,
                          node,
                          type,
                          attr,
                          source,
                          br_want,
                          prefix=None):
        self.assertEqual(node.get("type"), type)
        br_name = node.find(attr).get(source)
        if prefix is None:
            self.assertEqual(br_name, br_want)
        else:
            self.assertTrue(br_name.startswith(prefix))

    def _assertTypeAndMacEquals(self,
                                node,
                                type,
                                attr,
                                source,
                                vif,
                                br_want=None,
                                size=0,
                                prefix=None):
        ret = node.findall("filterref")
        self.assertEqual(len(ret), size)
        self._assertTypeEquals(node, type, attr, source, br_want, prefix)
        self._assertMacEquals(node, vif)

    def _assertModel(self, xml, model_want=None, driver_want=None):
        node = self._get_node(xml)
        if model_want is None:
            ret = node.findall("model")
            self.assertEqual(len(ret), 0)
        else:
            model = node.find("model").get("type")
            self.assertEqual(model, model_want)
        if driver_want is None:
            ret = node.findall("driver")
            self.assertEqual(len(ret), 0)
        else:
            driver = node.find("driver").get("name")
            self.assertEqual(driver, driver_want)

    def _get_conf(self):
        conf = vconfig.LibvirtConfigGuest()
        conf.virt_type = "qemu"
        conf.name = "fake-name"
        conf.uuid = "fake-uuid"
        conf.memory = 100 * 1024
        conf.vcpus = 4
        return conf

    def _get_instance_xml(self, driver, vif, image_meta=None):
        default_inst_type = flavors.get_default_flavor()
        extra_specs = default_inst_type['extra_specs'].items()
        quota_bandwidth = self.bandwidth.items()
        default_inst_type['extra_specs'] = dict(extra_specs + quota_bandwidth)
        conf = self._get_conf()
        nic = driver.get_config(self.instance, vif, image_meta,
                                default_inst_type)
        conf.add_device(nic)
        return conf.to_xml()

    def test_multiple_nics(self):
        conf = self._get_conf()
        # Tests multiple nic configuration and that target_dev is
        # set for each
        nics = [{
            'net_type': 'bridge',
            'mac_addr': '00:00:00:00:00:0b',
            'source_dev': 'b_source_dev',
            'target_dev': 'b_target_dev'
        }, {
            'net_type': 'ethernet',
            'mac_addr': '00:00:00:00:00:0e',
            'source_dev': 'e_source_dev',
            'target_dev': 'e_target_dev'
        }, {
            'net_type': 'direct',
            'mac_addr': '00:00:00:00:00:0d',
            'source_dev': 'd_source_dev',
            'target_dev': 'd_target_dev'
        }]

        for nic in nics:
            nic_conf = vconfig.LibvirtConfigGuestInterface()
            nic_conf.net_type = nic['net_type']
            nic_conf.target_dev = nic['target_dev']
            nic_conf.mac_addr = nic['mac_addr']
            nic_conf.source_dev = nic['source_dev']
            conf.add_device(nic_conf)

        xml = conf.to_xml()
        doc = etree.fromstring(xml)
        for nic in nics:
            path = "./devices/interface/[@type='%s']" % nic['net_type']
            node = doc.find(path)
            self.assertEqual(nic['net_type'], node.get("type"))
            self.assertEqual(nic['mac_addr'], node.find("mac").get("address"))
            self.assertEqual(nic['target_dev'], node.find("target").get("dev"))

    def test_model_novirtio(self):
        self.flags(use_virtio_for_bridges=False,
                   virt_type='kvm',
                   group='libvirt')

        d = vif.LibvirtGenericVIFDriver(self._get_conn())
        xml = self._get_instance_xml(d, self.vif_bridge)
        self._assertModel(xml)

    def test_model_kvm(self):
        self.flags(use_virtio_for_bridges=True,
                   virt_type='kvm',
                   group='libvirt')

        d = vif.LibvirtGenericVIFDriver(self._get_conn())
        xml = self._get_instance_xml(d, self.vif_bridge)

        self._assertModel(xml, network_model.VIF_MODEL_VIRTIO)

    def test_model_kvm_custom(self):
        self.flags(use_virtio_for_bridges=True,
                   virt_type='kvm',
                   group='libvirt')

        d = vif.LibvirtGenericVIFDriver(self._get_conn())
        image_meta = {
            'properties': {
                'hw_vif_model': network_model.VIF_MODEL_E1000
            }
        }
        xml = self._get_instance_xml(d, self.vif_bridge, image_meta)
        self._assertModel(xml, network_model.VIF_MODEL_E1000)

    def test_model_kvm_bogus(self):
        self.flags(use_virtio_for_bridges=True,
                   virt_type='kvm',
                   group='libvirt')

        d = vif.LibvirtGenericVIFDriver(self._get_conn())
        image_meta = {'properties': {'hw_vif_model': 'acme'}}
        self.assertRaises(exception.UnsupportedHardware,
                          self._get_instance_xml, d, self.vif_bridge,
                          image_meta)

    def _test_model_qemu(self, *vif_objs, **kw):
        libvirt_version = kw.get('libvirt_version')
        self.flags(use_virtio_for_bridges=True,
                   virt_type='qemu',
                   group='libvirt')

        for vif_obj in vif_objs:
            d = vif.LibvirtGenericVIFDriver(self._get_conn())
            if libvirt_version is not None:
                d.libvirt_version = libvirt_version

            xml = self._get_instance_xml(d, vif_obj)

            doc = etree.fromstring(xml)

            bandwidth = doc.find('./devices/interface/bandwidth')
            self.assertNotEqual(bandwidth, None)

            inbound = bandwidth.find('inbound')
            self.assertEqual(inbound.get("average"),
                             self.bandwidth['quota:vif_inbound_average'])
            self.assertEqual(inbound.get("peak"),
                             self.bandwidth['quota:vif_inbound_peak'])
            self.assertEqual(inbound.get("burst"),
                             self.bandwidth['quota:vif_inbound_burst'])

            outbound = bandwidth.find('outbound')
            self.assertEqual(outbound.get("average"),
                             self.bandwidth['quota:vif_outbound_average'])
            self.assertEqual(outbound.get("peak"),
                             self.bandwidth['quota:vif_outbound_peak'])
            self.assertEqual(outbound.get("burst"),
                             self.bandwidth['quota:vif_outbound_burst'])

            self._assertModel(xml, network_model.VIF_MODEL_VIRTIO, "qemu")

    def test_model_qemu_no_firewall(self):
        self.flags(firewall_driver="nova.virt.firewall.NoopFirewallDriver")
        self._test_model_qemu(
            self.vif_bridge,
            self.vif_8021qbh,
            self.vif_8021qbg,
            self.vif_iovisor,
            self.vif_mlnx,
        )
        self._test_model_qemu(self.vif_ovs,
                              libvirt_version=vif.LIBVIRT_OVS_VPORT_VERSION)

    def test_model_qemu_iptables(self):
        self.flags(firewall_driver="nova.virt.firewall.IptablesFirewallDriver")
        self._test_model_qemu(
            self.vif_bridge,
            self.vif_ovs,
            self.vif_ivs,
            self.vif_8021qbh,
            self.vif_8021qbg,
            self.vif_iovisor,
            self.vif_mlnx,
        )

    def test_model_xen(self):
        self.flags(use_virtio_for_bridges=True,
                   virt_type='xen',
                   group='libvirt')

        d = vif.LibvirtGenericVIFDriver(self._get_conn("xen:///system"))
        xml = self._get_instance_xml(d, self.vif_bridge)
        self._assertModel(xml)

    def test_generic_driver_none(self):
        d = vif.LibvirtGenericVIFDriver(self._get_conn())
        self.assertRaises(exception.NovaException, self._get_instance_xml, d,
                          self.vif_none)

    def _check_bridge_driver(self, d, vif, br_want):
        xml = self._get_instance_xml(d, vif)
        node = self._get_node(xml)
        self._assertTypeAndMacEquals(node, "bridge", "source", "bridge",
                                     self.vif_bridge, br_want, 1)

    def test_generic_driver_bridge(self):
        d = vif.LibvirtGenericVIFDriver(self._get_conn())
        self._check_bridge_driver(d, self.vif_bridge,
                                  self.vif_bridge['network']['bridge'])

    def _check_ivs_ethernet_driver(self, d, vif, dev_prefix):
        self.flags(firewall_driver="nova.virt.firewall.NoopFirewallDriver")
        xml = self._get_instance_xml(d, vif)
        node = self._get_node(xml)
        self._assertTypeAndMacEquals(node,
                                     "ethernet",
                                     "target",
                                     "dev",
                                     self.vif_ivs,
                                     prefix=dev_prefix)
        script = node.find("script").get("path")
        self.assertEqual(script, "")

    def _check_ovs_ethernet_driver(self, d, vif, dev_prefix):
        self.flags(firewall_driver="nova.virt.firewall.NoopFirewallDriver")
        xml = self._get_instance_xml(d, vif)
        node = self._get_node(xml)
        self._assertTypeAndMacEquals(node,
                                     "ethernet",
                                     "target",
                                     "dev",
                                     self.vif_ovs,
                                     prefix=dev_prefix)
        script = node.find("script").get("path")
        self.assertEqual(script, "")

    def test_ovs_ethernet_driver(self):
        d = vif.LibvirtGenericVIFDriver(self._get_conn(ver=9010))
        self._check_ovs_ethernet_driver(d, self.vif_ovs, "tap")

    def test_unplug_ivs_ethernet(self):
        d = vif.LibvirtGenericVIFDriver(self._get_conn(ver=9010))
        with mock.patch.object(linux_net, 'delete_ivs_vif_port') as delete:
            delete.side_effect = processutils.ProcessExecutionError
            d.unplug_ivs_ethernet(None, self.vif_ovs)

    def test_plug_ovs_hybrid(self):
        calls = {
            'device_exists':
            [mock.call('qbrvif-xxx-yyy'),
             mock.call('qvovif-xxx-yyy')],
            '_create_veth_pair':
            [mock.call('qvbvif-xxx-yyy', 'qvovif-xxx-yyy')],
            'execute': [
                mock.call('brctl', 'addbr', 'qbrvif-xxx-yyy',
                          run_as_root=True),
                mock.call('brctl',
                          'setfd',
                          'qbrvif-xxx-yyy',
                          0,
                          run_as_root=True),
                mock.call('brctl',
                          'stp',
                          'qbrvif-xxx-yyy',
                          'off',
                          run_as_root=True),
                mock.call('tee', ('/sys/class/net/qbrvif-xxx-yyy'
                                  '/bridge/multicast_snooping'),
                          process_input='0',
                          run_as_root=True,
                          check_exit_code=[0, 1]),
                mock.call('ip',
                          'link',
                          'set',
                          'qbrvif-xxx-yyy',
                          'up',
                          run_as_root=True),
                mock.call('brctl',
                          'addif',
                          'qbrvif-xxx-yyy',
                          'qvbvif-xxx-yyy',
                          run_as_root=True)
            ],
            'create_ovs_vif_port': [
                mock.call('br0', 'qvovif-xxx-yyy', 'aaa-bbb-ccc',
                          'ca:fe:de:ad:be:ef', 'instance-uuid')
            ]
        }
        with contextlib.nested(
                mock.patch.object(linux_net,
                                  'device_exists',
                                  return_value=False),
                mock.patch.object(utils, 'execute'),
                mock.patch.object(linux_net, '_create_veth_pair'),
                mock.patch.object(
                    linux_net,
                    'create_ovs_vif_port')) as (device_exists, execute,
                                                _create_veth_pair,
                                                create_ovs_vif_port):
            d = vif.LibvirtGenericVIFDriver(self._get_conn(ver=9010))
            d.plug_ovs_hybrid(self.instance, self.vif_ovs)
            device_exists.assert_has_calls(calls['device_exists'])
            _create_veth_pair.assert_has_calls(calls['_create_veth_pair'])
            execute.assert_has_calls(calls['execute'])
            create_ovs_vif_port.assert_has_calls(calls['create_ovs_vif_port'])

    def test_unplug_ovs_hybrid(self):
        calls = {
            'device_exists': [mock.call('qbrvif-xxx-yyy')],
            'execute': [
                mock.call('brctl',
                          'delif',
                          'qbrvif-xxx-yyy',
                          'qvbvif-xxx-yyy',
                          run_as_root=True),
                mock.call('ip',
                          'link',
                          'set',
                          'qbrvif-xxx-yyy',
                          'down',
                          run_as_root=True),
                mock.call('brctl', 'delbr', 'qbrvif-xxx-yyy', run_as_root=True)
            ],
            'delete_ovs_vif_port': [mock.call('br0', 'qvovif-xxx-yyy')]
        }
        with contextlib.nested(
                mock.patch.object(linux_net,
                                  'device_exists',
                                  return_value=True),
                mock.patch.object(utils, 'execute'),
                mock.patch.object(
                    linux_net,
                    'delete_ovs_vif_port')) as (device_exists, execute,
                                                delete_ovs_vif_port):
            d = vif.LibvirtGenericVIFDriver(self._get_conn(ver=9010))
            d.unplug_ovs_hybrid(None, self.vif_ovs)
            device_exists.assert_has_calls(calls['device_exists'])
            execute.assert_has_calls(calls['execute'])
            delete_ovs_vif_port.assert_has_calls(calls['delete_ovs_vif_port'])

    def test_unplug_ovs_hybrid_bridge_does_not_exist(self):
        calls = {
            'device_exists': [mock.call('qbrvif-xxx-yyy')],
            'delete_ovs_vif_port': [mock.call('br0', 'qvovif-xxx-yyy')]
        }
        with contextlib.nested(
                mock.patch.object(linux_net,
                                  'device_exists',
                                  return_value=False),
                mock.patch.object(
                    linux_net,
                    'delete_ovs_vif_port')) as (device_exists,
                                                delete_ovs_vif_port):
            d = vif.LibvirtGenericVIFDriver(self._get_conn(ver=9010))
            d.unplug_ovs_hybrid(None, self.vif_ovs)
            device_exists.assert_has_calls(calls['device_exists'])
            delete_ovs_vif_port.assert_has_calls(calls['delete_ovs_vif_port'])

    def test_plug_ivs_hybrid(self):
        calls = {
            'device_exists':
            [mock.call('qbrvif-xxx-yyy'),
             mock.call('qvovif-xxx-yyy')],
            '_create_veth_pair':
            [mock.call('qvbvif-xxx-yyy', 'qvovif-xxx-yyy')],
            'execute': [
                mock.call('brctl', 'addbr', 'qbrvif-xxx-yyy',
                          run_as_root=True),
                mock.call('brctl',
                          'setfd',
                          'qbrvif-xxx-yyy',
                          0,
                          run_as_root=True),
                mock.call('brctl',
                          'stp',
                          'qbrvif-xxx-yyy',
                          'off',
                          run_as_root=True),
                mock.call('tee', ('/sys/class/net/qbrvif-xxx-yyy'
                                  '/bridge/multicast_snooping'),
                          process_input='0',
                          run_as_root=True,
                          check_exit_code=[0, 1]),
                mock.call('ip',
                          'link',
                          'set',
                          'qbrvif-xxx-yyy',
                          'up',
                          run_as_root=True),
                mock.call('brctl',
                          'addif',
                          'qbrvif-xxx-yyy',
                          'qvbvif-xxx-yyy',
                          run_as_root=True)
            ],
            'create_ivs_vif_port': [
                mock.call('qvovif-xxx-yyy', 'aaa-bbb-ccc', 'ca:fe:de:ad:be:ef',
                          'instance-uuid')
            ]
        }
        with contextlib.nested(
                mock.patch.object(linux_net,
                                  'device_exists',
                                  return_value=False),
                mock.patch.object(utils, 'execute'),
                mock.patch.object(linux_net, '_create_veth_pair'),
                mock.patch.object(
                    linux_net,
                    'create_ivs_vif_port')) as (device_exists, execute,
                                                _create_veth_pair,
                                                create_ivs_vif_port):
            d = vif.LibvirtGenericVIFDriver(self._get_conn(ver=9010))
            d.plug_ivs_hybrid(self.instance, self.vif_ivs)
            device_exists.assert_has_calls(calls['device_exists'])
            _create_veth_pair.assert_has_calls(calls['_create_veth_pair'])
            execute.assert_has_calls(calls['execute'])
            create_ivs_vif_port.assert_has_calls(calls['create_ivs_vif_port'])

    def test_unplug_ivs_hybrid(self):
        calls = {
            'execute': [
                mock.call('brctl',
                          'delif',
                          'qbrvif-xxx-yyy',
                          'qvbvif-xxx-yyy',
                          run_as_root=True),
                mock.call('ip',
                          'link',
                          'set',
                          'qbrvif-xxx-yyy',
                          'down',
                          run_as_root=True),
                mock.call('brctl', 'delbr', 'qbrvif-xxx-yyy', run_as_root=True)
            ],
            'delete_ivs_vif_port': [mock.call('qvovif-xxx-yyy')]
        }
        with contextlib.nested(
                mock.patch.object(utils, 'execute'),
                mock.patch.object(
                    linux_net,
                    'delete_ivs_vif_port')) as (execute, delete_ivs_vif_port):
            d = vif.LibvirtGenericVIFDriver(self._get_conn(ver=9010))
            d.unplug_ivs_hybrid(None, self.vif_ivs)
            execute.assert_has_calls(calls['execute'])
            delete_ivs_vif_port.assert_has_calls(calls['delete_ivs_vif_port'])

    def test_unplug_ivs_hybrid_bridge_does_not_exist(self):
        d = vif.LibvirtGenericVIFDriver(self._get_conn(ver=9010))
        with mock.patch.object(utils, 'execute') as execute:
            execute.side_effect = processutils.ProcessExecutionError
            d.unplug_ivs_hybrid(None, self.vif_ivs)

    def test_unplug_iovisor(self):
        d = vif.LibvirtGenericVIFDriver(self._get_conn(ver=9010))
        with mock.patch.object(utils, 'execute') as execute:
            execute.side_effect = processutils.ProcessExecutionError
            mynetwork = network_model.Network(id='network-id-xxx-yyy-zzz',
                                              label='mylabel')
            myvif = network_model.VIF(id='vif-xxx-yyy-zzz',
                                      address='ca:fe:de:ad:be:ef',
                                      network=mynetwork)
            d.unplug_iovisor(None, myvif)

    @mock.patch('nova.network.linux_net.device_exists')
    def test_plug_iovisor(self, device_exists):
        device_exists.return_value = True
        d = vif.LibvirtGenericVIFDriver(self._get_conn(ver=9010))
        with mock.patch.object(utils, 'execute') as execute:
            execute.side_effect = processutils.ProcessExecutionError
            instance = {
                'name': 'instance-name',
                'uuid': 'instance-uuid',
                'project_id': 'myproject'
            }
            d.plug_iovisor(instance, self.vif_ivs)

    def test_ivs_ethernet_driver(self):
        d = vif.LibvirtGenericVIFDriver(self._get_conn(ver=9010))
        self._check_ivs_ethernet_driver(d, self.vif_ivs, "tap")

    def _check_ivs_virtualport_driver(self, d, vif, want_iface_id):
        self.flags(firewall_driver="nova.virt.firewall.NoopFirewallDriver")
        xml = self._get_instance_xml(d, vif)
        node = self._get_node(xml)
        self._assertTypeAndMacEquals(node, "ethernet", "target", "dev", vif,
                                     vif['devname'])

    def _check_ovs_virtualport_driver(self, d, vif, want_iface_id):
        self.flags(firewall_driver="nova.virt.firewall.NoopFirewallDriver")
        xml = self._get_instance_xml(d, vif)
        node = self._get_node(xml)
        self._assertTypeAndMacEquals(node, "bridge", "source", "bridge", vif,
                                     "br0")
        vp = node.find("virtualport")
        self.assertEqual(vp.get("type"), "openvswitch")
        iface_id_found = False
        for p_elem in vp.findall("parameters"):
            iface_id = p_elem.get("interfaceid", None)
            if iface_id:
                self.assertEqual(iface_id, want_iface_id)
                iface_id_found = True

        self.assertTrue(iface_id_found)

    def test_generic_ovs_virtualport_driver(self):
        d = vif.LibvirtGenericVIFDriver(self._get_conn(ver=9011))
        want_iface_id = self.vif_ovs['ovs_interfaceid']
        self._check_ovs_virtualport_driver(d, self.vif_ovs, want_iface_id)

    def test_generic_ivs_virtualport_driver(self):
        d = vif.LibvirtGenericVIFDriver(self._get_conn(ver=9011))
        want_iface_id = self.vif_ivs['ovs_interfaceid']
        self._check_ivs_virtualport_driver(d, self.vif_ivs, want_iface_id)

    def test_hybrid_plug_without_nova_firewall(self):
        d = vif.LibvirtGenericVIFDriver(self._get_conn())
        br_want = "qbr" + self.vif_ovs_hybrid['id']
        br_want = br_want[:network_model.NIC_NAME_LEN]
        self.flags(firewall_driver="nova.virt.firewall.NoopFirewallDriver")
        xml = self._get_instance_xml(d, self.vif_ovs_hybrid)
        node = self._get_node(xml)
        self._assertTypeAndMacEquals(node, "bridge", "source", "bridge",
                                     self.vif_ovs_hybrid, br_want, 0)

    def test_direct_plug_with_port_filter_cap_no_nova_firewall(self):
        d = vif.LibvirtGenericVIFDriver(self._get_conn())
        br_want = self.vif_midonet['devname']
        xml = self._get_instance_xml(d, self.vif_ovs_filter_cap)
        node = self._get_node(xml)
        self._assertTypeAndMacEquals(node, "ethernet", "target", "dev",
                                     self.vif_ovs_filter_cap, br_want)

    def _check_neutron_hybrid_driver(self, d, vif, br_want):
        self.flags(firewall_driver="nova.virt.firewall.IptablesFirewallDriver")
        xml = self._get_instance_xml(d, vif)
        node = self._get_node(xml)
        self._assertTypeAndMacEquals(node, "bridge", "source", "bridge", vif,
                                     br_want, 1)

    def test_generic_hybrid_driver(self):
        d = vif.LibvirtGenericVIFDriver(self._get_conn())
        br_want = "qbr" + self.vif_ovs['id']
        br_want = br_want[:network_model.NIC_NAME_LEN]
        self._check_neutron_hybrid_driver(d, self.vif_ovs, br_want)

    def test_ivs_hybrid_driver(self):
        d = vif.LibvirtGenericVIFDriver(self._get_conn())
        br_want = "qbr" + self.vif_ivs['id']
        br_want = br_want[:network_model.NIC_NAME_LEN]
        self._check_neutron_hybrid_driver(d, self.vif_ivs, br_want)

    def test_mlnx_direct_vif_driver(self):
        d = vif.LibvirtGenericVIFDriver(self._get_conn())
        xml = self._get_instance_xml(d, self.vif_mlnx)
        node = self._get_node(xml)
        self.assertEqual(node.get("type"), "direct")
        self._assertTypeEquals(node, "direct", "source", "dev",
                               "eth-xxx-yyy-zzz")
        self._assertTypeEquals(node, "direct", "source", "mode", "passthrough")
        self._assertMacEquals(node, self.vif_mlnx)
        self._assertModel(xml, network_model.VIF_MODEL_VIRTIO)

    def test_midonet_ethernet_vif_driver(self):
        d = vif.LibvirtGenericVIFDriver(self._get_conn())
        self.flags(firewall_driver="nova.virt.firewall.NoopFirewallDriver")
        br_want = self.vif_midonet['devname']
        xml = self._get_instance_xml(d, self.vif_midonet)
        node = self._get_node(xml)
        self._assertTypeAndMacEquals(node, "ethernet", "target", "dev",
                                     self.vif_midonet, br_want)

    def test_generic_8021qbh_driver(self):
        d = vif.LibvirtGenericVIFDriver(self._get_conn())
        xml = self._get_instance_xml(d, self.vif_8021qbh)
        node = self._get_node(xml)
        self._assertTypeEquals(node, "direct", "source", "dev", "eth0")
        self._assertMacEquals(node, self.vif_8021qbh)
        vp = node.find("virtualport")
        self.assertEqual(vp.get("type"), "802.1Qbh")
        profile_id_found = False
        for p_elem in vp.findall("parameters"):
            wantparams = self.vif_8021qbh['qbh_params']
            profile_id = p_elem.get("profileid", None)
            if profile_id:
                self.assertEqual(profile_id, wantparams['profileid'])
                profile_id_found = True

        self.assertTrue(profile_id_found)

    def test_generic_iovisor_driver(self):
        d = vif.LibvirtGenericVIFDriver(self._get_conn())
        self.flags(firewall_driver="nova.virt.firewall.NoopFirewallDriver")
        br_want = self.vif_ivs['devname']
        xml = self._get_instance_xml(d, self.vif_ivs)
        node = self._get_node(xml)
        self._assertTypeAndMacEquals(node, "ethernet", "target", "dev",
                                     self.vif_ivs, br_want)

    def test_generic_8021qbg_driver(self):
        d = vif.LibvirtGenericVIFDriver(self._get_conn())
        xml = self._get_instance_xml(d, self.vif_8021qbg)

        node = self._get_node(xml)
        self._assertTypeEquals(node, "direct", "source", "dev", "eth0")
        self._assertMacEquals(node, self.vif_8021qbg)

        vp = node.find("virtualport")
        self.assertEqual(vp.get("type"), "802.1Qbg")
        manager_id_found = False
        type_id_found = False
        typeversion_id_found = False
        instance_id_found = False
        for p_elem in vp.findall("parameters"):
            wantparams = self.vif_8021qbg['qbg_params']
            manager_id = p_elem.get("managerid", None)
            type_id = p_elem.get("typeid", None)
            typeversion_id = p_elem.get("typeidversion", None)
            instance_id = p_elem.get("instanceid", None)
            if manager_id:
                self.assertEqual(manager_id, wantparams['managerid'])
                manager_id_found = True
            if type_id:
                self.assertEqual(type_id, wantparams['typeid'])
                type_id_found = True
            if typeversion_id:
                self.assertEqual(typeversion_id, wantparams['typeidversion'])
                typeversion_id_found = True
            if instance_id:
                self.assertEqual(instance_id, wantparams['instanceid'])
                instance_id_found = True

        self.assertTrue(manager_id_found)
        self.assertTrue(type_id_found)
        self.assertTrue(typeversion_id_found)
        self.assertTrue(instance_id_found)
コード例 #26
0
def new_ip(ip_dict=None):
    new_ip = dict(address='192.168.1.100')
    ip_dict = ip_dict or {}
    new_ip.update(ip_dict)
    return model.IP(**new_ip)
コード例 #27
0
    def setUp(self):
        super(TestZVMDriver, self).setUp()
        self.flags(my_ip='192.168.1.1', instance_name_template='abc%05d')
        self.flags(cloud_connector_url='https://1.1.1.1:1111', group='zvm')

        with mock.patch('nova.virt.zvm.utils.ConnectorClient.call') as mcall, \
            mock.patch('pwd.getpwuid', return_value=mock.Mock(pw_name='test')):
            mcall.return_value = {
                'hypervisor_hostname': 'TESTHOST',
                'ipl_time': 'IPL at 11/14/17 10:47:44 EST'
            }
            self._driver = zvmdriver.ZVMDriver(fake.FakeVirtAPI())
            self._hypervisor = self._driver._hypervisor

        self._context = context.RequestContext('fake_user', 'fake_project')
        self._image_id = uuidsentinel.imag_id

        self._instance_values = {
            'display_name': 'test',
            'uuid': uuidsentinel.inst_id,
            'vcpus': 1,
            'memory_mb': 1024,
            'image_ref': self._image_id,
            'root_gb': 0,
        }
        self._instance = fake_instance.fake_instance_obj(
            self._context, **self._instance_values)
        self._instance.flavor = objects.Flavor(name='testflavor',
                                               vcpus=1,
                                               root_gb=3,
                                               ephemeral_gb=10,
                                               swap=0,
                                               memory_mb=512,
                                               extra_specs={})

        self._eph_disks = [{
            'guest_format': u'ext3',
            'device_name': u'/dev/sdb',
            'disk_bus': None,
            'device_type': None,
            'size': 1
        }, {
            'guest_format': u'ext4',
            'device_name': u'/dev/sdc',
            'disk_bus': None,
            'device_type': None,
            'size': 2
        }]
        self._block_device_info = {
            'swap': None,
            'root_device_name': u'/dev/sda',
            'ephemerals': self._eph_disks,
            'block_device_mapping': []
        }
        fake_image_meta = {
            'status': 'active',
            'properties': {
                'os_distro': 'rhel7.2'
            },
            'name': 'rhel72eckdimage',
            'deleted': False,
            'container_format': 'bare',
            'disk_format': 'raw',
            'id': self._image_id,
            'owner': 'cfc26f9d6af948018621ab00a1675310',
            'checksum': 'b026cd083ef8e9610a29eaf71459cc',
            'min_disk': 0,
            'is_public': False,
            'deleted_at': None,
            'min_ram': 0,
            'size': 465448142
        }
        self._image_meta = objects.ImageMeta.from_dict(fake_image_meta)
        subnet_4 = network_model.Subnet(
            cidr='192.168.0.1/24',
            dns=[network_model.IP('192.168.0.1')],
            gateway=network_model.IP('192.168.0.1'),
            ips=[network_model.IP('192.168.0.100')],
            routes=None)
        network = network_model.Network(id=0,
                                        bridge='fa0',
                                        label='fake',
                                        subnets=[subnet_4],
                                        vlan=None,
                                        bridge_interface=None,
                                        injected=True)
        self._network_values = {
            'id': None,
            'address': 'DE:AD:BE:EF:00:00',
            'network': network,
            'type': network_model.VIF_TYPE_OVS,
            'devname': None,
            'ovs_interfaceid': None,
            'rxtx_cap': 3
        }
        self._network_info = network_model.NetworkInfo(
            [network_model.VIF(**self._network_values)])

        self.mock_update_task_state = mock.Mock()
コード例 #28
0
ファイル: fake_network.py プロジェクト: sapcc/nova
def fake_get_instance_nw_info(test, num_networks=1):
    def update_cache_fake(*args, **kwargs):
        fake_info_cache = {
            'created_at': None,
            'updated_at': None,
            'deleted_at': None,
            'deleted': False,
            'instance_uuid': uuids.vifs_1,
            'network_info': '[]',
        }
        return fake_info_cache

    test.stub_out('nova.db.api.instance_info_cache_update', update_cache_fake)

    # TODO(stephenfin): This doesn't match the kind of object we would receive
    # from '_build_vif_model' and callers of same. We should fix that.
    nw_model = network_model.NetworkInfo()
    for network_id in range(1, num_networks + 1):
        network = network_model.Network(
            id=getattr(uuids, 'network%i' % network_id),
            bridge='fake_br%d' % network_id,
            label='test%d' % network_id,
            subnets=[
                network_model.Subnet(
                    cidr='192.168.%d.0/24' % network_id,
                    dns=[
                        network_model.IP(
                            address='192.168.%d.3' % network_id,
                            type='dns',
                            version=4,
                            meta={},
                        ),
                        network_model.IP(
                            address='192.168.%d.4' % network_id,
                            type='dns',
                            version=4,
                            meta={},
                        ),
                    ],
                    gateway=network_model.IP(
                        address='192.168.%d.1' % network_id,
                        type='gateway',
                        version=4,
                        meta={},
                    ),
                    ips=[
                        network_model.FixedIP(
                            address='192.168.%d.100' % network_id,
                            version=4,
                            meta={},
                        ),
                    ],
                    routes=[],
                    version=4,
                    meta={},
                ),
                network_model.Subnet(
                    cidr='2001:db8:0:%x::/64' % network_id,
                    dns=[],
                    gateway=network_model.IP(
                        address='2001:db8:0:%x::1' % network_id,
                        type='gateway',
                        version=6,
                        meta={},
                    ),
                    ips=[
                        network_model.FixedIP(
                            address='2001:db8:0:%x:dcad:beff:feef:1' %
                            (network_id),
                            version=6,
                            meta={},
                        ),
                    ],
                    routes=[],
                    version=6,
                    meta={}),
            ],
            meta={"tenant_id": "806e1f03-b36f-4fc6-be29-11a366f150eb"},
        )
        vif = network_model.VIF(
            id=getattr(uuids, 'vif%i' % network_id),
            address='DE:AD:BE:EF:00:%02x' % network_id,
            network=network,
            type='bridge',
            details={},
            devname=None,
            ovs_interfaceid=None,
            qbh_params=None,
            qbg_params=None,
            active=False,
            vnic_type='normal',
            profile={},
            preserve_on_delete=False,
            meta={'rxtx_cap': 30},
        )
        nw_model.append(vif)

    return nw_model
コード例 #29
0
    def test_nova_to_osvif_subnets(self):
        subnets = [
            model.Subnet(cidr="192.168.1.0/24",
                         dns=[
                             model.IP(
                                 address="192.168.1.1",
                                 type="dns"),
                             model.IP(
                                 address="192.168.1.2",
                                 type="dns"),
                         ],
                         gateway=model.IP(
                             address="192.168.1.254",
                             type='gateway'),
                         ips=[
                             model.FixedIP(
                                 address="192.168.1.100",
                             ),
                             model.FixedIP(
                                 address="192.168.1.101",
                             ),
                         ],
                         routes=[
                             model.Route(
                                 cidr="10.0.0.1/24",
                                 gateway=model.IP(
                                     address="192.168.1.254",
                                     type="gateway"),
                                 interface="eth0"),
                         ]),
            model.Subnet(dns=[
                             model.IP(
                                 address="192.168.1.1",
                                 type="dns"),
                             model.IP(
                                 address="192.168.1.2",
                                 type="dns"),
                         ],
                         ips=[
                             model.FixedIP(
                                 address="192.168.1.100",
                             ),
                             model.FixedIP(
                                 address="192.168.1.101",
                             ),
                         ],
                         routes=[
                             model.Route(
                                 cidr="10.0.0.1/24",
                                 gateway=model.IP(
                                     address="192.168.1.254",
                                     type="gateway"),
                                 interface="eth0"),
                         ]),
            model.Subnet(dns=[
                             model.IP(
                                 address="192.168.1.1",
                                 type="dns"),
                             model.IP(
                                 address="192.168.1.2",
                                 type="dns"),
                         ],
                         gateway=model.IP(
                             type='gateway'),
                         ips=[
                             model.FixedIP(
                                 address="192.168.1.100",
                             ),
                             model.FixedIP(
                                 address="192.168.1.101",
                             ),
                         ],
                         routes=[
                             model.Route(
                                 cidr="10.0.0.1/24",
                                 gateway=model.IP(
                                     address="192.168.1.254",
                                     type="gateway"),
                                 interface="eth0"),
                         ]),
        ]

        expect = osv_objects.subnet.SubnetList(
            objects=[
                osv_objects.subnet.Subnet(
                    cidr="192.168.1.0/24",
                    dns=["192.168.1.1",
                         "192.168.1.2"],
                    gateway="192.168.1.254",
                    ips=osv_objects.fixed_ip.FixedIPList(
                        objects=[
                            osv_objects.fixed_ip.FixedIP(
                                address="192.168.1.100",
                                floating_ips=[]),
                            osv_objects.fixed_ip.FixedIP(
                                address="192.168.1.101",
                                floating_ips=[]),
                            ]),
                    routes=osv_objects.route.RouteList(
                        objects=[
                            osv_objects.route.Route(
                                cidr="10.0.0.1/24",
                                gateway="192.168.1.254",
                                interface="eth0")
                            ]),
                    ),
                osv_objects.subnet.Subnet(
                    dns=["192.168.1.1",
                         "192.168.1.2"],
                    ips=osv_objects.fixed_ip.FixedIPList(
                        objects=[
                            osv_objects.fixed_ip.FixedIP(
                                address="192.168.1.100",
                                floating_ips=[]),
                            osv_objects.fixed_ip.FixedIP(
                                address="192.168.1.101",
                                floating_ips=[]),
                            ]),
                    routes=osv_objects.route.RouteList(
                        objects=[
                            osv_objects.route.Route(
                                cidr="10.0.0.1/24",
                                gateway="192.168.1.254",
                                interface="eth0")
                            ]),
                    ),
                osv_objects.subnet.Subnet(
                    dns=["192.168.1.1",
                         "192.168.1.2"],
                    ips=osv_objects.fixed_ip.FixedIPList(
                        objects=[
                            osv_objects.fixed_ip.FixedIP(
                                address="192.168.1.100",
                                floating_ips=[]),
                            osv_objects.fixed_ip.FixedIP(
                                address="192.168.1.101",
                                floating_ips=[]),
                            ]),
                    routes=osv_objects.route.RouteList(
                        objects=[
                            osv_objects.route.Route(
                                cidr="10.0.0.1/24",
                                gateway="192.168.1.254",
                                interface="eth0")
                            ]),
                    ),
            ])

        actual = os_vif_util._nova_to_osvif_subnets(subnets)

        self.assertObjEqual(expect, actual)
コード例 #30
0
class LibvirtVifTestCase(test.NoDBTestCase):

    gateway_bridge_4 = network_model.IP(address='101.168.1.1', type='gateway')
    dns_bridge_4 = network_model.IP(address='8.8.8.8', type=None)
    ips_bridge_4 = [network_model.IP(address='101.168.1.9', type=None)]
    subnet_bridge_4 = network_model.Subnet(cidr='101.168.1.0/24',
                                           dns=[dns_bridge_4],
                                           gateway=gateway_bridge_4,
                                           routes=None,
                                           dhcp_server='191.168.1.1')

    gateway_bridge_6 = network_model.IP(address='101:1db9::1', type='gateway')
    subnet_bridge_6 = network_model.Subnet(cidr='101:1db9::/64',
                                           dns=None,
                                           gateway=gateway_bridge_6,
                                           ips=None,
                                           routes=None)

    network_bridge = network_model.Network(
        id='network-id-xxx-yyy-zzz',
        bridge='br0',
        label=None,
        subnets=[subnet_bridge_4, subnet_bridge_6],
        bridge_interface='eth0',
        vlan=99)

    vif_bridge = network_model.VIF(id='vif-xxx-yyy-zzz',
                                   address='ca:fe:de:ad:be:ef',
                                   network=network_bridge,
                                   type=network_model.VIF_TYPE_BRIDGE,
                                   devname='tap-xxx-yyy-zzz',
                                   ovs_interfaceid=None)

    network_bridge_neutron = network_model.Network(
        id='network-id-xxx-yyy-zzz',
        bridge=None,
        label=None,
        subnets=[subnet_bridge_4, subnet_bridge_6],
        bridge_interface='eth0',
        vlan=99)

    vif_bridge_neutron = network_model.VIF(id='vif-xxx-yyy-zzz',
                                           address='ca:fe:de:ad:be:ef',
                                           network=network_bridge_neutron,
                                           type=None,
                                           devname='tap-xxx-yyy-zzz',
                                           ovs_interfaceid='aaa-bbb-ccc')

    network_ovs = network_model.Network(
        id='network-id-xxx-yyy-zzz',
        bridge='br0',
        label=None,
        subnets=[subnet_bridge_4, subnet_bridge_6],
        bridge_interface=None,
        vlan=99)

    network_ivs = network_model.Network(
        id='network-id-xxx-yyy-zzz',
        bridge='br0',
        label=None,
        subnets=[subnet_bridge_4, subnet_bridge_6],
        bridge_interface=None,
        vlan=99)

    vif_ovs = network_model.VIF(id='vif-xxx-yyy-zzz',
                                address='ca:fe:de:ad:be:ef',
                                network=network_ovs,
                                type=network_model.VIF_TYPE_OVS,
                                devname='tap-xxx-yyy-zzz',
                                ovs_interfaceid='aaa-bbb-ccc')

    vif_ovs_hybrid = network_model.VIF(id='vif-xxx-yyy-zzz',
                                       address='ca:fe:de:ad:be:ef',
                                       network=network_ovs,
                                       type=network_model.VIF_TYPE_OVS,
                                       details={
                                           'ovs_hybrid_plug': True,
                                           'port_filter': True
                                       },
                                       devname='tap-xxx-yyy-zzz',
                                       ovs_interfaceid='aaa-bbb-ccc')

    vif_ovs_filter_cap = network_model.VIF(id='vif-xxx-yyy-zzz',
                                           address='ca:fe:de:ad:be:ef',
                                           network=network_ovs,
                                           type=network_model.VIF_TYPE_OVS,
                                           details={'port_filter': True},
                                           devname='tap-xxx-yyy-zzz',
                                           ovs_interfaceid='aaa-bbb-ccc')

    vif_ovs_legacy = network_model.VIF(id='vif-xxx-yyy-zzz',
                                       address='ca:fe:de:ad:be:ef',
                                       network=network_ovs,
                                       type=None,
                                       devname=None,
                                       ovs_interfaceid=None)

    vif_ivs = network_model.VIF(id='vif-xxx-yyy-zzz',
                                address='ca:fe:de:ad:be:ef',
                                network=network_ivs,
                                type=network_model.VIF_TYPE_IVS,
                                devname='tap-xxx-yyy-zzz',
                                ovs_interfaceid='aaa-bbb-ccc')

    vif_ivs_legacy = network_model.VIF(id='vif-xxx-yyy-zzz',
                                       address='ca:fe:de:ad:be:ef',
                                       network=network_ovs,
                                       type=None,
                                       devname=None,
                                       ovs_interfaceid='aaa')

    vif_ivs_filter_direct = network_model.VIF(id='vif-xxx-yyy-zzz',
                                              address='ca:fe:de:ad:be:ef',
                                              network=network_ivs,
                                              type=network_model.VIF_TYPE_IVS,
                                              details={'port_filter': True},
                                              devname='tap-xxx-yyy-zzz',
                                              ovs_interfaceid='aaa-bbb-ccc')

    vif_ivs_filter_hybrid = network_model.VIF(id='vif-xxx-yyy-zzz',
                                              address='ca:fe:de:ad:be:ef',
                                              network=network_ivs,
                                              type=network_model.VIF_TYPE_IVS,
                                              details={
                                                  'port_filter': True,
                                                  'ovs_hybrid_plug': True
                                              },
                                              devname='tap-xxx-yyy-zzz',
                                              ovs_interfaceid='aaa-bbb-ccc')

    vif_none = network_model.VIF(id='vif-xxx-yyy-zzz',
                                 address='ca:fe:de:ad:be:ef',
                                 network=network_bridge,
                                 type=None,
                                 devname='tap-xxx-yyy-zzz',
                                 ovs_interfaceid=None)

    network_8021 = network_model.Network(
        id='network-id-xxx-yyy-zzz',
        bridge=None,
        label=None,
        subnets=[subnet_bridge_4, subnet_bridge_6],
        interface='eth0',
        vlan=99)

    vif_8021qbh = network_model.VIF(
        id='vif-xxx-yyy-zzz',
        address='ca:fe:de:ad:be:ef',
        network=network_8021,
        type=network_model.VIF_TYPE_802_QBH,
        vnic_type=network_model.VNIC_TYPE_DIRECT,
        ovs_interfaceid=None,
        details={network_model.VIF_DETAILS_PROFILEID: 'MyPortProfile'},
        profile={
            'pci_vendor_info': '1137:0043',
            'pci_slot': '0000:0a:00.1',
            'physical_network': 'phynet1'
        })

    vif_hw_veb = network_model.VIF(
        id='vif-xxx-yyy-zzz',
        address='ca:fe:de:ad:be:ef',
        network=network_8021,
        type=network_model.VIF_TYPE_HW_VEB,
        vnic_type=network_model.VNIC_TYPE_DIRECT,
        ovs_interfaceid=None,
        details={network_model.VIF_DETAILS_VLAN: '100'},
        profile={
            'pci_vendor_info': '1137:0043',
            'pci_slot': '0000:0a:00.1',
            'physical_network': 'phynet1'
        })

    vif_macvtap = network_model.VIF(
        id='vif-xxx-yyy-zzz',
        address='ca:fe:de:ad:be:ef',
        network=network_8021,
        type=network_model.VIF_TYPE_HW_VEB,
        vnic_type=network_model.VNIC_TYPE_MACVTAP,
        ovs_interfaceid=None,
        details={network_model.VIF_DETAILS_VLAN: '100'},
        profile={
            'pci_vendor_info': '1137:0043',
            'pci_slot': '0000:0a:00.1',
            'physical_network': 'phynet1'
        })

    vif_8021qbg = network_model.VIF(id='vif-xxx-yyy-zzz',
                                    address='ca:fe:de:ad:be:ef',
                                    network=network_8021,
                                    type=network_model.VIF_TYPE_802_QBG,
                                    ovs_interfaceid=None,
                                    qbg_params=network_model.VIF8021QbgParams(
                                        managerid="xxx-yyy-zzz",
                                        typeid="aaa-bbb-ccc",
                                        typeidversion="1",
                                        instanceid="ddd-eee-fff"))

    network_mlnx = network_model.Network(
        id='network-id-xxx-yyy-zzz',
        label=None,
        bridge=None,
        subnets=[subnet_bridge_4, subnet_bridge_6],
        interface='eth0')

    network_midonet = network_model.Network(id='network-id-xxx-yyy-zzz',
                                            label=None,
                                            bridge=None,
                                            subnets=[subnet_bridge_4],
                                            interface='eth0')

    vif_mlnx = network_model.VIF(id='vif-xxx-yyy-zzz',
                                 address='ca:fe:de:ad:be:ef',
                                 network=network_mlnx,
                                 type=network_model.VIF_TYPE_MLNX_DIRECT,
                                 devname='tap-xxx-yyy-zzz')

    vif_mlnx_net = network_model.VIF(
        id='vif-xxx-yyy-zzz',
        address='ca:fe:de:ad:be:ef',
        network=network_mlnx,
        type=network_model.VIF_TYPE_MLNX_DIRECT,
        details={'physical_network': 'fake_phy_network'},
        devname='tap-xxx-yyy-zzz')

    vif_midonet = network_model.VIF(id='vif-xxx-yyy-zzz',
                                    address='ca:fe:de:ad:be:ef',
                                    network=network_midonet,
                                    type=network_model.VIF_TYPE_MIDONET,
                                    devname='tap-xxx-yyy-zzz')

    vif_iovisor = network_model.VIF(id='vif-xxx-yyy-zzz',
                                    address='ca:fe:de:ad:be:ef',
                                    network=network_bridge,
                                    type=network_model.VIF_TYPE_IOVISOR,
                                    devname='tap-xxx-yyy-zzz',
                                    ovs_interfaceid=None)

    instance = {'name': 'instance-name', 'uuid': 'instance-uuid'}

    bandwidth = {
        'quota:vif_inbound_peak': '200',
        'quota:vif_outbound_peak': '20',
        'quota:vif_inbound_average': '100',
        'quota:vif_outbound_average': '10',
        'quota:vif_inbound_burst': '300',
        'quota:vif_outbound_burst': '30'
    }

    def setUp(self):
        super(LibvirtVifTestCase, self).setUp()
        self.flags(allow_same_net_traffic=True)
        self.executes = []

        def fake_execute(*cmd, **kwargs):
            self.executes.append(cmd)
            return None, None

        self.stubs.Set(utils, 'execute', fake_execute)

    def _get_node(self, xml):
        doc = etree.fromstring(xml)
        ret = doc.findall('./devices/interface')
        self.assertEqual(len(ret), 1)
        return ret[0]

    def _assertMacEquals(self, node, vif):
        mac = node.find("mac").get("address")
        self.assertEqual(mac, vif['address'])

    def _assertTypeEquals(self,
                          node,
                          type,
                          attr,
                          source,
                          br_want,
                          prefix=None):
        self.assertEqual(node.get("type"), type)
        br_name = node.find(attr).get(source)
        if prefix is None:
            self.assertEqual(br_name, br_want)
        else:
            self.assertTrue(br_name.startswith(prefix))

    def _assertTypeAndMacEquals(self,
                                node,
                                type,
                                attr,
                                source,
                                vif,
                                br_want=None,
                                size=0,
                                prefix=None):
        ret = node.findall("filterref")
        self.assertEqual(len(ret), size)
        self._assertTypeEquals(node, type, attr, source, br_want, prefix)
        self._assertMacEquals(node, vif)

    def _assertModel(self, xml, model_want=None, driver_want=None):
        node = self._get_node(xml)
        if model_want is None:
            ret = node.findall("model")
            self.assertEqual(len(ret), 0)
        else:
            model = node.find("model").get("type")
            self.assertEqual(model, model_want)
        if driver_want is None:
            ret = node.findall("driver")
            self.assertEqual(len(ret), 0)
        else:
            driver = node.find("driver").get("name")
            self.assertEqual(driver, driver_want)

    def _assertTypeAndPciEquals(self, node, type, vif):
        self.assertEqual(node.get("type"), type)
        address = node.find("source").find("address")
        addr_type = address.get("type")
        self.assertEqual("pci", addr_type)
        pci_slot = "%(domain)s:%(bus)s:%(slot)s.%(func)s" % {
            'domain': address.get("domain")[2:],
            'bus': address.get("bus")[2:],
            'slot': address.get("slot")[2:],
            'func': address.get("function")[2:]
        }

        pci_slot_want = vif['profile']['pci_slot']
        self.assertEqual(pci_slot, pci_slot_want)

    def _get_conf(self):
        conf = vconfig.LibvirtConfigGuest()
        conf.virt_type = "qemu"
        conf.name = "fake-name"
        conf.uuid = "fake-uuid"
        conf.memory = 100 * 1024
        conf.vcpus = 4
        return conf

    def _get_instance_xml(self, driver, vif, image_meta=None, flavor=None):
        if flavor is None:
            flavor = objects.Flavor(name='m1.small',
                                    memory_mb=128,
                                    vcpus=1,
                                    root_gb=0,
                                    ephemeral_gb=0,
                                    swap=0,
                                    extra_specs=dict(self.bandwidth),
                                    deleted_at=None,
                                    deleted=0,
                                    created_at=None,
                                    flavorid=1,
                                    is_public=True,
                                    vcpu_weight=None,
                                    id=2,
                                    disabled=False,
                                    rxtx_factor=1.0)

        conf = self._get_conf()
        nic = driver.get_config(self.instance, vif, image_meta, flavor,
                                CONF.libvirt.virt_type)
        conf.add_device(nic)
        return conf.to_xml()

    def test_multiple_nics(self):
        conf = self._get_conf()
        # Tests multiple nic configuration and that target_dev is
        # set for each
        nics = [{
            'net_type': 'bridge',
            'mac_addr': '00:00:00:00:00:0b',
            'source_dev': 'b_source_dev',
            'target_dev': 'b_target_dev'
        }, {
            'net_type': 'ethernet',
            'mac_addr': '00:00:00:00:00:0e',
            'source_dev': 'e_source_dev',
            'target_dev': 'e_target_dev'
        }, {
            'net_type': 'direct',
            'mac_addr': '00:00:00:00:00:0d',
            'source_dev': 'd_source_dev',
            'target_dev': 'd_target_dev'
        }]

        for nic in nics:
            nic_conf = vconfig.LibvirtConfigGuestInterface()
            nic_conf.net_type = nic['net_type']
            nic_conf.target_dev = nic['target_dev']
            nic_conf.mac_addr = nic['mac_addr']
            nic_conf.source_dev = nic['source_dev']
            conf.add_device(nic_conf)

        xml = conf.to_xml()
        doc = etree.fromstring(xml)
        for nic in nics:
            path = "./devices/interface/[@type='%s']" % nic['net_type']
            node = doc.find(path)
            self.assertEqual(nic['net_type'], node.get("type"))
            self.assertEqual(nic['mac_addr'], node.find("mac").get("address"))
            self.assertEqual(nic['target_dev'], node.find("target").get("dev"))

    def test_model_novirtio(self):
        self.flags(use_virtio_for_bridges=False,
                   virt_type='kvm',
                   group='libvirt')

        d = vif.LibvirtGenericVIFDriver()
        xml = self._get_instance_xml(d, self.vif_bridge)
        self._assertModel(xml)

    def test_model_kvm(self):
        self.flags(use_virtio_for_bridges=True,
                   virt_type='kvm',
                   group='libvirt')

        d = vif.LibvirtGenericVIFDriver()
        xml = self._get_instance_xml(d, self.vif_bridge)
        self._assertModel(xml, network_model.VIF_MODEL_VIRTIO)

    def test_model_kvm_qemu_custom(self):
        for virt in ('kvm', 'qemu'):
            self.flags(use_virtio_for_bridges=True,
                       virt_type=virt,
                       group='libvirt')

            d = vif.LibvirtGenericVIFDriver()
            supported = (network_model.VIF_MODEL_NE2K_PCI,
                         network_model.VIF_MODEL_PCNET,
                         network_model.VIF_MODEL_RTL8139,
                         network_model.VIF_MODEL_E1000,
                         network_model.VIF_MODEL_SPAPR_VLAN)
            for model in supported:
                image_meta = {'properties': {'hw_vif_model': model}}
                xml = self._get_instance_xml(d, self.vif_bridge, image_meta)
                self._assertModel(xml, model)

    def test_model_kvm_bogus(self):
        self.flags(use_virtio_for_bridges=True,
                   virt_type='kvm',
                   group='libvirt')

        d = vif.LibvirtGenericVIFDriver()
        image_meta = {'properties': {'hw_vif_model': 'acme'}}
        self.assertRaises(exception.UnsupportedHardware,
                          self._get_instance_xml, d, self.vif_bridge,
                          image_meta)

    def _test_model_qemu(self, *vif_objs, **kw):
        libvirt_version = kw.get('libvirt_version')
        self.flags(use_virtio_for_bridges=True,
                   virt_type='qemu',
                   group='libvirt')

        for vif_obj in vif_objs:
            d = vif.LibvirtGenericVIFDriver()
            if libvirt_version is not None:
                d.libvirt_version = libvirt_version

            xml = self._get_instance_xml(d, vif_obj)

            doc = etree.fromstring(xml)

            bandwidth = doc.find('./devices/interface/bandwidth')
            self.assertNotEqual(bandwidth, None)

            inbound = bandwidth.find('inbound')
            self.assertEqual(inbound.get("average"),
                             self.bandwidth['quota:vif_inbound_average'])
            self.assertEqual(inbound.get("peak"),
                             self.bandwidth['quota:vif_inbound_peak'])
            self.assertEqual(inbound.get("burst"),
                             self.bandwidth['quota:vif_inbound_burst'])

            outbound = bandwidth.find('outbound')
            self.assertEqual(outbound.get("average"),
                             self.bandwidth['quota:vif_outbound_average'])
            self.assertEqual(outbound.get("peak"),
                             self.bandwidth['quota:vif_outbound_peak'])
            self.assertEqual(outbound.get("burst"),
                             self.bandwidth['quota:vif_outbound_burst'])

            self._assertModel(xml, network_model.VIF_MODEL_VIRTIO, "qemu")

    def test_model_qemu_no_firewall(self):
        self.flags(firewall_driver="nova.virt.firewall.NoopFirewallDriver")
        self._test_model_qemu(
            self.vif_bridge,
            self.vif_8021qbg,
            self.vif_iovisor,
            self.vif_mlnx,
            self.vif_ovs,
        )

    def test_model_qemu_iptables(self):
        self.flags(firewall_driver="nova.virt.firewall.IptablesFirewallDriver")
        self._test_model_qemu(
            self.vif_bridge,
            self.vif_ovs,
            self.vif_ivs,
            self.vif_8021qbg,
            self.vif_iovisor,
            self.vif_mlnx,
        )

    def test_model_xen(self):
        self.flags(use_virtio_for_bridges=True,
                   virt_type='xen',
                   group='libvirt')

        d = vif.LibvirtGenericVIFDriver()
        xml = self._get_instance_xml(d, self.vif_bridge)
        self._assertModel(xml)

    def test_generic_driver_none(self):
        d = vif.LibvirtGenericVIFDriver()
        self.assertRaises(exception.NovaException, self._get_instance_xml, d,
                          self.vif_none)

    def _check_bridge_driver(self, d, vif, br_want):
        xml = self._get_instance_xml(d, vif)
        node = self._get_node(xml)
        self._assertTypeAndMacEquals(node, "bridge", "source", "bridge",
                                     self.vif_bridge, br_want, 1)

    def test_generic_driver_bridge(self):
        d = vif.LibvirtGenericVIFDriver()
        self._check_bridge_driver(d, self.vif_bridge,
                                  self.vif_bridge['network']['bridge'])

    def _check_ivs_ethernet_driver(self, d, vif, dev_prefix):
        self.flags(firewall_driver="nova.virt.firewall.NoopFirewallDriver")
        xml = self._get_instance_xml(d, vif)
        node = self._get_node(xml)
        self._assertTypeAndMacEquals(node,
                                     "ethernet",
                                     "target",
                                     "dev",
                                     self.vif_ivs,
                                     prefix=dev_prefix)
        script = node.find("script").get("path")
        self.assertEqual(script, "")

    def test_unplug_ivs_ethernet(self):
        d = vif.LibvirtGenericVIFDriver()
        with mock.patch.object(linux_net, 'delete_ivs_vif_port') as delete:
            delete.side_effect = processutils.ProcessExecutionError
            d.unplug_ivs_ethernet(None, self.vif_ovs)

    def test_plug_ovs_hybrid(self):
        calls = {
            'device_exists':
            [mock.call('qbrvif-xxx-yyy'),
             mock.call('qvovif-xxx-yyy')],
            '_create_veth_pair':
            [mock.call('qvbvif-xxx-yyy', 'qvovif-xxx-yyy')],
            'execute': [
                mock.call('brctl', 'addbr', 'qbrvif-xxx-yyy',
                          run_as_root=True),
                mock.call('brctl',
                          'setfd',
                          'qbrvif-xxx-yyy',
                          0,
                          run_as_root=True),
                mock.call('brctl',
                          'stp',
                          'qbrvif-xxx-yyy',
                          'off',
                          run_as_root=True),
                mock.call('tee', ('/sys/class/net/qbrvif-xxx-yyy'
                                  '/bridge/multicast_snooping'),
                          process_input='0',
                          run_as_root=True,
                          check_exit_code=[0, 1]),
                mock.call('ip',
                          'link',
                          'set',
                          'qbrvif-xxx-yyy',
                          'up',
                          run_as_root=True),
                mock.call('brctl',
                          'addif',
                          'qbrvif-xxx-yyy',
                          'qvbvif-xxx-yyy',
                          run_as_root=True)
            ],
            'create_ovs_vif_port': [
                mock.call('br0', 'qvovif-xxx-yyy', 'aaa-bbb-ccc',
                          'ca:fe:de:ad:be:ef', 'instance-uuid')
            ]
        }
        with contextlib.nested(
                mock.patch.object(linux_net,
                                  'device_exists',
                                  return_value=False),
                mock.patch.object(utils, 'execute'),
                mock.patch.object(linux_net, '_create_veth_pair'),
                mock.patch.object(
                    linux_net,
                    'create_ovs_vif_port')) as (device_exists, execute,
                                                _create_veth_pair,
                                                create_ovs_vif_port):
            d = vif.LibvirtGenericVIFDriver()
            d.plug_ovs_hybrid(self.instance, self.vif_ovs)
            device_exists.assert_has_calls(calls['device_exists'])
            _create_veth_pair.assert_has_calls(calls['_create_veth_pair'])
            execute.assert_has_calls(calls['execute'])
            create_ovs_vif_port.assert_has_calls(calls['create_ovs_vif_port'])

    def test_unplug_ovs_hybrid(self):
        calls = {
            'device_exists': [mock.call('qbrvif-xxx-yyy')],
            'execute': [
                mock.call('brctl',
                          'delif',
                          'qbrvif-xxx-yyy',
                          'qvbvif-xxx-yyy',
                          run_as_root=True),
                mock.call('ip',
                          'link',
                          'set',
                          'qbrvif-xxx-yyy',
                          'down',
                          run_as_root=True),
                mock.call('brctl', 'delbr', 'qbrvif-xxx-yyy', run_as_root=True)
            ],
            'delete_ovs_vif_port': [mock.call('br0', 'qvovif-xxx-yyy')]
        }
        with contextlib.nested(
                mock.patch.object(linux_net,
                                  'device_exists',
                                  return_value=True),
                mock.patch.object(utils, 'execute'),
                mock.patch.object(
                    linux_net,
                    'delete_ovs_vif_port')) as (device_exists, execute,
                                                delete_ovs_vif_port):
            d = vif.LibvirtGenericVIFDriver()
            d.unplug_ovs_hybrid(None, self.vif_ovs)
            device_exists.assert_has_calls(calls['device_exists'])
            execute.assert_has_calls(calls['execute'])
            delete_ovs_vif_port.assert_has_calls(calls['delete_ovs_vif_port'])

    @mock.patch.object(utils, 'execute')
    @mock.patch.object(pci_utils, 'get_ifname_by_pci_address')
    @mock.patch.object(pci_utils, 'get_vf_num_by_pci_address', return_value=1)
    def _test_hw_veb_op(self, op, vlan, mock_get_vf_num, mock_get_ifname,
                        mock_execute):
        mock_get_ifname.side_effect = ['eth1', 'eth13']
        exit_code = [0, 2, 254]
        port_state = 'up' if vlan > 0 else 'down'
        calls = {
            'get_ifname': [
                mock.call(self.vif_macvtap['profile']['pci_slot'],
                          pf_interface=True),
                mock.call(self.vif_macvtap['profile']['pci_slot'])
            ],
            'get_vf_num': [mock.call(self.vif_macvtap['profile']['pci_slot'])],
            'execute': [
                mock.call('ip',
                          'link',
                          'set',
                          'eth1',
                          'vf',
                          1,
                          'mac',
                          self.vif_macvtap['address'],
                          'vlan',
                          vlan,
                          run_as_root=True,
                          check_exit_code=exit_code),
                mock.call('ip',
                          'link',
                          'set',
                          'eth13',
                          port_state,
                          run_as_root=True,
                          check_exit_code=exit_code)
            ]
        }
        op(None, self.vif_macvtap)
        mock_get_ifname.assert_has_calls(calls['get_ifname'])
        mock_get_vf_num.assert_has_calls(calls['get_vf_num'])
        mock_execute.assert_has_calls(calls['execute'])

    def test_plug_hw_veb(self):
        d = vif.LibvirtGenericVIFDriver()
        self._test_hw_veb_op(
            d.plug_hw_veb,
            self.vif_macvtap['details'][network_model.VIF_DETAILS_VLAN])

    def test_unplug_hw_veb(self):
        d = vif.LibvirtGenericVIFDriver()
        self._test_hw_veb_op(d.unplug_hw_veb, 0)

    def test_unplug_ovs_hybrid_bridge_does_not_exist(self):
        calls = {
            'device_exists': [mock.call('qbrvif-xxx-yyy')],
            'delete_ovs_vif_port': [mock.call('br0', 'qvovif-xxx-yyy')]
        }
        with contextlib.nested(
                mock.patch.object(linux_net,
                                  'device_exists',
                                  return_value=False),
                mock.patch.object(
                    linux_net,
                    'delete_ovs_vif_port')) as (device_exists,
                                                delete_ovs_vif_port):
            d = vif.LibvirtGenericVIFDriver()
            d.unplug_ovs_hybrid(None, self.vif_ovs)
            device_exists.assert_has_calls(calls['device_exists'])
            delete_ovs_vif_port.assert_has_calls(calls['delete_ovs_vif_port'])

    def test_plug_ivs_hybrid(self):
        calls = {
            'device_exists':
            [mock.call('qbrvif-xxx-yyy'),
             mock.call('qvovif-xxx-yyy')],
            '_create_veth_pair':
            [mock.call('qvbvif-xxx-yyy', 'qvovif-xxx-yyy')],
            'execute': [
                mock.call('brctl', 'addbr', 'qbrvif-xxx-yyy',
                          run_as_root=True),
                mock.call('brctl',
                          'setfd',
                          'qbrvif-xxx-yyy',
                          0,
                          run_as_root=True),
                mock.call('brctl',
                          'stp',
                          'qbrvif-xxx-yyy',
                          'off',
                          run_as_root=True),
                mock.call('tee', ('/sys/class/net/qbrvif-xxx-yyy'
                                  '/bridge/multicast_snooping'),
                          process_input='0',
                          run_as_root=True,
                          check_exit_code=[0, 1]),
                mock.call('ip',
                          'link',
                          'set',
                          'qbrvif-xxx-yyy',
                          'up',
                          run_as_root=True),
                mock.call('brctl',
                          'addif',
                          'qbrvif-xxx-yyy',
                          'qvbvif-xxx-yyy',
                          run_as_root=True)
            ],
            'create_ivs_vif_port': [
                mock.call('qvovif-xxx-yyy', 'aaa-bbb-ccc', 'ca:fe:de:ad:be:ef',
                          'instance-uuid')
            ]
        }
        with contextlib.nested(
                mock.patch.object(linux_net,
                                  'device_exists',
                                  return_value=False),
                mock.patch.object(utils, 'execute'),
                mock.patch.object(linux_net, '_create_veth_pair'),
                mock.patch.object(
                    linux_net,
                    'create_ivs_vif_port')) as (device_exists, execute,
                                                _create_veth_pair,
                                                create_ivs_vif_port):
            d = vif.LibvirtGenericVIFDriver()
            d.plug_ivs_hybrid(self.instance, self.vif_ivs)
            device_exists.assert_has_calls(calls['device_exists'])
            _create_veth_pair.assert_has_calls(calls['_create_veth_pair'])
            execute.assert_has_calls(calls['execute'])
            create_ivs_vif_port.assert_has_calls(calls['create_ivs_vif_port'])

    def test_unplug_ivs_hybrid(self):
        calls = {
            'execute': [
                mock.call('brctl',
                          'delif',
                          'qbrvif-xxx-yyy',
                          'qvbvif-xxx-yyy',
                          run_as_root=True),
                mock.call('ip',
                          'link',
                          'set',
                          'qbrvif-xxx-yyy',
                          'down',
                          run_as_root=True),
                mock.call('brctl', 'delbr', 'qbrvif-xxx-yyy', run_as_root=True)
            ],
            'delete_ivs_vif_port': [mock.call('qvovif-xxx-yyy')]
        }
        with contextlib.nested(
                mock.patch.object(utils, 'execute'),
                mock.patch.object(
                    linux_net,
                    'delete_ivs_vif_port')) as (execute, delete_ivs_vif_port):
            d = vif.LibvirtGenericVIFDriver()
            d.unplug_ivs_hybrid(None, self.vif_ivs)
            execute.assert_has_calls(calls['execute'])
            delete_ivs_vif_port.assert_has_calls(calls['delete_ivs_vif_port'])

    def test_unplug_ivs_hybrid_bridge_does_not_exist(self):
        d = vif.LibvirtGenericVIFDriver()
        with mock.patch.object(utils, 'execute') as execute:
            execute.side_effect = processutils.ProcessExecutionError
            d.unplug_ivs_hybrid(None, self.vif_ivs)

    def test_unplug_iovisor(self):
        d = vif.LibvirtGenericVIFDriver()
        with mock.patch.object(utils, 'execute') as execute:
            execute.side_effect = processutils.ProcessExecutionError
            mynetwork = network_model.Network(id='network-id-xxx-yyy-zzz',
                                              label='mylabel')
            myvif = network_model.VIF(id='vif-xxx-yyy-zzz',
                                      address='ca:fe:de:ad:be:ef',
                                      network=mynetwork)
            d.unplug_iovisor(None, myvif)

    @mock.patch('nova.network.linux_net.device_exists')
    def test_plug_iovisor(self, device_exists):
        device_exists.return_value = True
        d = vif.LibvirtGenericVIFDriver()
        with mock.patch.object(utils, 'execute') as execute:
            execute.side_effect = processutils.ProcessExecutionError
            instance = {
                'name': 'instance-name',
                'uuid': 'instance-uuid',
                'project_id': 'myproject'
            }
            d.plug_iovisor(instance, self.vif_ivs)

    def test_unplug_mlnx_with_details(self):
        d = vif.LibvirtGenericVIFDriver()
        with mock.patch.object(utils, 'execute') as execute:
            execute.side_effect = processutils.ProcessExecutionError
            d.unplug_mlnx_direct(None, self.vif_mlnx_net)
            execute.assert_called_once_with('ebrctl',
                                            'del-port',
                                            'fake_phy_network',
                                            'ca:fe:de:ad:be:ef',
                                            run_as_root=True)

    def test_plug_mlnx_with_details(self):
        d = vif.LibvirtGenericVIFDriver()
        with mock.patch.object(utils, 'execute') as execute:
            d.plug_mlnx_direct(self.instance, self.vif_mlnx_net)
            execute.assert_called_once_with('ebrctl',
                                            'add-port',
                                            'ca:fe:de:ad:be:ef',
                                            'instance-uuid',
                                            'fake_phy_network',
                                            'mlnx_direct',
                                            'eth-xxx-yyy-zzz',
                                            run_as_root=True)

    def test_plug_mlnx_no_physical_network(self):
        d = vif.LibvirtGenericVIFDriver()
        with mock.patch.object(utils, 'execute') as execute:
            self.assertRaises(exception.NovaException, d.plug_mlnx_direct,
                              self.instance, self.vif_mlnx)
            self.assertEqual(0, execute.call_count)

    def test_ivs_ethernet_driver(self):
        d = vif.LibvirtGenericVIFDriver()
        self._check_ivs_ethernet_driver(d, self.vif_ivs, "tap")

    def _check_ivs_virtualport_driver(self, d, vif, want_iface_id):
        self.flags(firewall_driver="nova.virt.firewall.NoopFirewallDriver")
        xml = self._get_instance_xml(d, vif)
        node = self._get_node(xml)
        self._assertTypeAndMacEquals(node, "ethernet", "target", "dev", vif,
                                     vif['devname'])

    def _check_ovs_virtualport_driver(self, d, vif, want_iface_id):
        self.flags(firewall_driver="nova.virt.firewall.NoopFirewallDriver")
        xml = self._get_instance_xml(d, vif)
        node = self._get_node(xml)
        self._assertTypeAndMacEquals(node, "bridge", "source", "bridge", vif,
                                     "br0")
        vp = node.find("virtualport")
        self.assertEqual(vp.get("type"), "openvswitch")
        iface_id_found = False
        for p_elem in vp.findall("parameters"):
            iface_id = p_elem.get("interfaceid", None)
            if iface_id:
                self.assertEqual(iface_id, want_iface_id)
                iface_id_found = True

        self.assertTrue(iface_id_found)

    def test_generic_ovs_virtualport_driver(self):
        d = vif.LibvirtGenericVIFDriver()
        want_iface_id = self.vif_ovs['ovs_interfaceid']
        self._check_ovs_virtualport_driver(d, self.vif_ovs, want_iface_id)

    def test_generic_ivs_virtualport_driver(self):
        d = vif.LibvirtGenericVIFDriver()
        want_iface_id = self.vif_ivs['ovs_interfaceid']
        self._check_ivs_virtualport_driver(d, self.vif_ivs, want_iface_id)

    def test_ivs_plug_with_nova_firewall(self):
        d = vif.LibvirtGenericVIFDriver()
        br_want = "qbr" + self.vif_ivs['id']
        br_want = br_want[:network_model.NIC_NAME_LEN]
        xml = self._get_instance_xml(d, self.vif_ivs)
        node = self._get_node(xml)
        self._assertTypeAndMacEquals(node, "bridge", "source", "bridge",
                                     self.vif_ivs, br_want, 1)

    def test_ivs_plug_with_port_filter_direct_no_nova_firewall(self):
        d = vif.LibvirtGenericVIFDriver()
        br_want = "qbr" + self.vif_ivs_filter_hybrid['id']
        br_want = br_want[:network_model.NIC_NAME_LEN]
        self.flags(firewall_driver="nova.virt.firewall.NoopFirewallDriver")
        xml = self._get_instance_xml(d, self.vif_ivs_filter_hybrid)
        node = self._get_node(xml)
        self._assertTypeAndMacEquals(node, "bridge", "source", "bridge",
                                     self.vif_ivs_filter_hybrid, br_want, 0)

    def test_ivs_plug_with_port_filter_hybrid_no_nova_firewall(self):
        d = vif.LibvirtGenericVIFDriver()
        br_want = self.vif_ivs_filter_direct['devname']
        self.flags(firewall_driver="nova.virt.firewall.NoopFirewallDriver")
        xml = self._get_instance_xml(d, self.vif_ivs_filter_direct)
        node = self._get_node(xml)
        self._assertTypeAndMacEquals(node, "ethernet", "target", "dev",
                                     self.vif_ivs_filter_direct, br_want, 0)

    def test_hybrid_plug_without_nova_firewall(self):
        d = vif.LibvirtGenericVIFDriver()
        br_want = "qbr" + self.vif_ovs_hybrid['id']
        br_want = br_want[:network_model.NIC_NAME_LEN]
        self.flags(firewall_driver="nova.virt.firewall.NoopFirewallDriver")
        xml = self._get_instance_xml(d, self.vif_ovs_hybrid)
        node = self._get_node(xml)
        self._assertTypeAndMacEquals(node, "bridge", "source", "bridge",
                                     self.vif_ovs_hybrid, br_want, 0)

    def test_direct_plug_with_port_filter_cap_no_nova_firewall(self):
        d = vif.LibvirtGenericVIFDriver()
        br_want = self.vif_midonet['devname']
        xml = self._get_instance_xml(d, self.vif_ovs_filter_cap)
        node = self._get_node(xml)
        self._assertTypeAndMacEquals(node, "bridge", "target", "dev",
                                     self.vif_ovs_filter_cap, br_want)

    def _check_neutron_hybrid_driver(self, d, vif, br_want):
        self.flags(firewall_driver="nova.virt.firewall.IptablesFirewallDriver")
        xml = self._get_instance_xml(d, vif)
        node = self._get_node(xml)
        self._assertTypeAndMacEquals(node, "bridge", "source", "bridge", vif,
                                     br_want, 1)

    def test_generic_hybrid_driver(self):
        d = vif.LibvirtGenericVIFDriver()
        br_want = "qbr" + self.vif_ovs['id']
        br_want = br_want[:network_model.NIC_NAME_LEN]
        self._check_neutron_hybrid_driver(d, self.vif_ovs, br_want)

    def test_ivs_hybrid_driver(self):
        d = vif.LibvirtGenericVIFDriver()
        br_want = "qbr" + self.vif_ivs['id']
        br_want = br_want[:network_model.NIC_NAME_LEN]
        self._check_neutron_hybrid_driver(d, self.vif_ivs, br_want)

    def test_mlnx_direct_vif_driver(self):
        d = vif.LibvirtGenericVIFDriver()
        xml = self._get_instance_xml(d, self.vif_mlnx)
        node = self._get_node(xml)
        self.assertEqual(node.get("type"), "direct")
        self._assertTypeEquals(node, "direct", "source", "dev",
                               "eth-xxx-yyy-zzz")
        self._assertTypeEquals(node, "direct", "source", "mode", "passthrough")
        self._assertMacEquals(node, self.vif_mlnx)
        self._assertModel(xml, network_model.VIF_MODEL_VIRTIO)

    def test_midonet_ethernet_vif_driver(self):
        d = vif.LibvirtGenericVIFDriver()
        self.flags(firewall_driver="nova.virt.firewall.NoopFirewallDriver")
        br_want = self.vif_midonet['devname']
        xml = self._get_instance_xml(d, self.vif_midonet)
        node = self._get_node(xml)
        self._assertTypeAndMacEquals(node, "ethernet", "target", "dev",
                                     self.vif_midonet, br_want)

    def test_generic_8021qbh_driver(self):
        d = vif.LibvirtGenericVIFDriver()
        xml = self._get_instance_xml(d, self.vif_8021qbh)
        node = self._get_node(xml)
        self._assertTypeAndPciEquals(node, "hostdev", self.vif_8021qbh)
        self._assertMacEquals(node, self.vif_8021qbh)
        vp = node.find("virtualport")
        self.assertEqual(vp.get("type"), "802.1Qbh")
        profile_id_found = False
        for p_elem in vp.findall("parameters"):
            details = self.vif_8021qbh["details"]
            profile_id = p_elem.get("profileid", None)
            if profile_id:
                self.assertEqual(profile_id,
                                 details[network_model.VIF_DETAILS_PROFILEID])
                profile_id_found = True

        self.assertTrue(profile_id_found)

    def test_hw_veb_driver(self):
        d = vif.LibvirtGenericVIFDriver()
        xml = self._get_instance_xml(d, self.vif_hw_veb)
        node = self._get_node(xml)
        self._assertTypeAndPciEquals(node, "hostdev", self.vif_hw_veb)
        self._assertMacEquals(node, self.vif_hw_veb)
        vlan = node.find("vlan").find("tag").get("id")
        vlan_want = self.vif_hw_veb["details"]["vlan"]
        self.assertEqual(vlan, vlan_want)

    @mock.patch.object(pci_utils,
                       'get_ifname_by_pci_address',
                       return_value='eth1')
    def test_hw_veb_driver_macvtap(self, mock_get_ifname):
        d = vif.LibvirtGenericVIFDriver()
        xml = self._get_instance_xml(d, self.vif_macvtap)
        node = self._get_node(xml)
        self.assertEqual(node.get("type"), "direct")
        self._assertTypeEquals(node, "direct", "source", "dev", "eth1")
        self._assertTypeEquals(node, "direct", "source", "mode", "passthrough")
        self._assertMacEquals(node, self.vif_macvtap)
        vlan = node.find("vlan")
        self.assertIsNone(vlan)

    def test_generic_iovisor_driver(self):
        d = vif.LibvirtGenericVIFDriver()
        self.flags(firewall_driver="nova.virt.firewall.NoopFirewallDriver")
        br_want = self.vif_ivs['devname']
        xml = self._get_instance_xml(d, self.vif_ivs)
        node = self._get_node(xml)
        self._assertTypeAndMacEquals(node, "ethernet", "target", "dev",
                                     self.vif_ivs, br_want)

    def test_generic_8021qbg_driver(self):
        d = vif.LibvirtGenericVIFDriver()
        xml = self._get_instance_xml(d, self.vif_8021qbg)

        node = self._get_node(xml)
        self._assertTypeEquals(node, "direct", "source", "dev", "eth0")
        self._assertMacEquals(node, self.vif_8021qbg)

        vp = node.find("virtualport")
        self.assertEqual(vp.get("type"), "802.1Qbg")
        manager_id_found = False
        type_id_found = False
        typeversion_id_found = False
        instance_id_found = False
        for p_elem in vp.findall("parameters"):
            wantparams = self.vif_8021qbg['qbg_params']
            manager_id = p_elem.get("managerid", None)
            type_id = p_elem.get("typeid", None)
            typeversion_id = p_elem.get("typeidversion", None)
            instance_id = p_elem.get("instanceid", None)
            if manager_id:
                self.assertEqual(manager_id, wantparams['managerid'])
                manager_id_found = True
            if type_id:
                self.assertEqual(type_id, wantparams['typeid'])
                type_id_found = True
            if typeversion_id:
                self.assertEqual(typeversion_id, wantparams['typeidversion'])
                typeversion_id_found = True
            if instance_id:
                self.assertEqual(instance_id, wantparams['instanceid'])
                instance_id_found = True

        self.assertTrue(manager_id_found)
        self.assertTrue(type_id_found)
        self.assertTrue(typeversion_id_found)
        self.assertTrue(instance_id_found)