Example #1
0
 def test_set_port_mac(self):
     attr = self.generate_device_details()
     self.manage_device(attr)
     plumber = trunk_plumber.Plumber(namespace=attr.namespace)
     # force it to return name of above
     plumber._get_tap_device_name = lambda x: attr.name
     new_mac = utils.get_random_mac('fa:16:3e:00:00:00'.split(':'))
     self.assertTrue(plumber.set_port_mac('port_id', new_mac))
     self.assertFalse(plumber.set_port_mac('port_id', new_mac))
     new_mac = utils.get_random_mac('fa:16:3e:00:00:00'.split(':'))
     self.assertTrue(plumber.set_port_mac('port_id', new_mac))
     self.assertFalse(plumber.set_port_mac('port_id', new_mac))
 def test_set_port_mac(self):
     attr = self.generate_device_details()
     self.manage_device(attr)
     plumber = trunk_plumber.Plumber(namespace=attr.namespace)
     # force it to return name of above
     plumber._get_tap_device_name = lambda x: attr.name
     new_mac = utils.get_random_mac('fa:16:3e:00:00:00'.split(':'))
     self.assertTrue(plumber.set_port_mac('port_id', new_mac))
     self.assertFalse(plumber.set_port_mac('port_id', new_mac))
     new_mac = utils.get_random_mac('fa:16:3e:00:00:00'.split(':'))
     self.assertTrue(plumber.set_port_mac('port_id', new_mac))
     self.assertFalse(plumber.set_port_mac('port_id', new_mac))
    def setUp(self):
        super(TestTaasPlugin, self).setUp()
        mock.patch.object(n_rpc, 'create_connection', auto_spec=True).start()
        mock.patch.object(taas_plugin, 'TaasCallbacks', auto_spec=True).start()
        mock.patch.object(taas_plugin, 'TaasAgentApi', auto_spec=True).start()
        self._plugin = taas_plugin.TaasPlugin()
        self._context = context.get_admin_context()

        self._tenant_id = 'tenant-X'
        self._network_id = uuidutils.generate_uuid()
        self._host_id = 'host-A'
        self._port_id = uuidutils.generate_uuid()
        self._port_details = {
            'tenant_id': self._tenant_id,
            'binding:host_id': self._host_id,
            'mac_address': n_utils.get_random_mac(
                'fa:16:3e:00:00:00'.split(':')),
        }
        self._tap_service = {
            'tenant_id': self._tenant_id,
            'name': 'MyTap',
            'description': 'This is my tap service',
            'port_id': self._port_id,
            'network_id': self._network_id,
        }
        self._tap_flow = {
            'description': 'This is my tap flow',
            'direction': 'BOTH',
            'name': 'MyTapFlow',
            'source_port': self._port_id,
            'tenant_id': self._tenant_id,
        }
Example #4
0
 def _create_dvr_mac_address(self, context, host):
     """Create DVR mac address for a given host."""
     base_mac = cfg.CONF.dvr_base_mac.split(':')
     max_retries = cfg.CONF.mac_generation_retries
     for attempt in reversed(range(max_retries)):
         try:
             with context.session.begin(subtransactions=True):
                 mac_address = utils.get_random_mac(base_mac)
                 dvr_mac_binding = DistributedVirtualRouterMacAddress(
                     host=host, mac_address=mac_address)
                 context.session.add(dvr_mac_binding)
                 LOG.debug(
                     "Generated DVR mac for host %(host)s "
                     "is %(mac_address)s", {
                         'host': host,
                         'mac_address': mac_address
                     })
             dvr_macs = self.get_dvr_mac_address_list(context)
             # TODO(vivek): improve scalability of this fanout by
             # sending a single mac address rather than the entire set
             self.notifier.dvr_mac_address_update(context, dvr_macs)
             return self._make_dvr_mac_address_dict(dvr_mac_binding)
         except db_exc.DBDuplicateEntry:
             LOG.debug(
                 "Generated DVR mac %(mac)s exists."
                 " Remaining attempts %(attempts_left)s.", {
                     'mac': mac_address,
                     'attempts_left': attempt
                 })
     LOG.error(_LE("MAC generation error after %s attempts"), max_retries)
     raise ext_dvr.MacAddressGenerationFailure(host=host)
Example #5
0
    def test_plug_with_namespace_sets_mtu_higher_than_bridge(self):
        device_mtu = 1450

        # Create a new OVS bridge
        ovs_bridge = self.useFixture(net_helpers.OVSBridgeFixture()).bridge
        self.assertFalse(ovs_bridge.get_port_name_list())

        # Add a new linuxbridge port with reduced MTU to OVS bridge
        lb_bridge = self.useFixture(net_helpers.LinuxBridgeFixture()).bridge
        lb_bridge_port = self.useFixture(
            net_helpers.LinuxBridgePortFixture(lb_bridge))
        lb_bridge_port.port.link.set_mtu(device_mtu - 1)
        ovs_bridge.add_port(lb_bridge_port.port.name)

        # Now plug a device with intended MTU that is higher than for the port
        # above and validate that its MTU is not reduced to the least MTU on
        # the bridge
        device_name = utils.get_rand_name()
        mac_address = utils.get_random_mac('fa:16:3e:00:00:00'.split(':'))
        namespace = self.useFixture(net_helpers.NamespaceFixture()).name
        self.interface.plug(network_id=uuidutils.generate_uuid(),
                            port_id=uuidutils.generate_uuid(),
                            device_name=device_name,
                            mac_address=mac_address,
                            bridge=ovs_bridge.br_name,
                            namespace=namespace,
                            mtu=device_mtu)

        self.assertIn(device_name, ovs_bridge.get_port_name_list())
        self.assertTrue(ip_lib.device_exists(device_name, namespace))
        self.assertEqual(
            device_mtu,
            ip_lib.IPDevice(device_name, namespace=namespace).link.mtu)
Example #6
0
    def setUp(self):
        super(TestTaasPlugin, self).setUp()
        mock.patch.object(n_rpc, 'create_connection', auto_spec=True).start()
        mock.patch.object(taas_plugin, 'TaasCallbacks', auto_spec=True).start()
        mock.patch.object(taas_plugin, 'TaasAgentApi', auto_spec=True).start()
        self._plugin = taas_plugin.TaasPlugin()
        self._context = context.get_admin_context()

        self._tenant_id = 'tenant-X'
        self._network_id = uuidutils.generate_uuid()
        self._host_id = 'host-A'
        self._port_id = uuidutils.generate_uuid()
        self._port_details = {
            'tenant_id': self._tenant_id,
            'binding:host_id': self._host_id,
            'mac_address':
            n_utils.get_random_mac('fa:16:3e:00:00:00'.split(':')),
        }
        self._tap_service = {
            'tenant_id': self._tenant_id,
            'name': 'MyTap',
            'description': 'This is my tap service',
            'port_id': self._port_id,
            'network_id': self._network_id,
        }
        self._tap_flow = {
            'description': 'This is my tap flow',
            'direction': 'BOTH',
            'name': 'MyTapFlow',
            'source_port': self._port_id,
            'tenant_id': self._tenant_id,
        }
Example #7
0
    def test_plug_with_namespace_sets_mtu_higher_than_bridge(self):
        device_mtu = 1450

        # Create a new OVS bridge
        ovs_bridge = self.useFixture(net_helpers.OVSBridgeFixture()).bridge
        self.assertFalse(ovs_bridge.get_port_name_list())

        # Add a new linuxbridge port with reduced MTU to OVS bridge
        lb_bridge = self.useFixture(
            net_helpers.LinuxBridgeFixture()).bridge
        lb_bridge_port = self.useFixture(
            net_helpers.LinuxBridgePortFixture(lb_bridge))
        lb_bridge_port.port.link.set_mtu(device_mtu - 1)
        ovs_bridge.add_port(lb_bridge_port.port.name)

        # Now plug a device with intended MTU that is higher than for the port
        # above and validate that its MTU is not reduced to the least MTU on
        # the bridge
        device_name = utils.get_rand_name()
        mac_address = utils.get_random_mac('fa:16:3e:00:00:00'.split(':'))
        namespace = self.useFixture(net_helpers.NamespaceFixture()).name
        self.interface.plug(network_id=uuidutils.generate_uuid(),
                            port_id=uuidutils.generate_uuid(),
                            device_name=device_name,
                            mac_address=mac_address,
                            bridge=ovs_bridge.br_name,
                            namespace=namespace,
                            mtu=device_mtu)

        self.assertIn(device_name, ovs_bridge.get_port_name_list())
        self.assertTrue(ip_lib.device_exists(device_name, namespace))
        self.assertEqual(
            device_mtu,
            ip_lib.IPDevice(device_name, namespace=namespace).link.mtu
        )
Example #8
0
 def generate_device_details(self, name=None, ip_cidr=None,
                             mac_address=None, namespace=None):
     return Device(name or base.get_rand_name(),
                   ip_cidr or '240.0.0.1/24',
                   mac_address or
                   utils.get_random_mac('fa:16:3e:00:00:00'.split(':')),
                   namespace or base.get_rand_name())
Example #9
0
 def generate_device_details(self, name=None, ip_cidrs=None,
                             mac_address=None, namespace=None):
     return Device(name or base.get_rand_name(),
                   ip_cidrs or ["%s/24" % TEST_IP],
                   mac_address or
                   utils.get_random_mac('fa:16:3e:00:00:00'.split(':')),
                   namespace or base.get_rand_name())
Example #10
0
 def generate_device_details(self, name=None, ip_cidrs=None,
                             mac_address=None, namespace=None):
     return Device(name or base.get_rand_name(),
                   ip_cidrs or ['240.0.0.1/24'],
                   mac_address or
                   utils.get_random_mac('fa:16:3e:00:00:00'.split(':')),
                   namespace or base.get_rand_name())
Example #11
0
 def _create_dvr_mac_address(self, context, host):
     """Create DVR mac address for a given host."""
     base_mac = cfg.CONF.dvr_base_mac.split(':')
     max_retries = cfg.CONF.mac_generation_retries
     for attempt in reversed(range(max_retries)):
         try:
             with context.session.begin(subtransactions=True):
                 mac_address = utils.get_random_mac(base_mac)
                 dvr_mac_binding = DistributedVirtualRouterMacAddress(
                     host=host, mac_address=mac_address)
                 context.session.add(dvr_mac_binding)
                 LOG.debug("Generated DVR mac for host %(host)s "
                           "is %(mac_address)s",
                           {'host': host, 'mac_address': mac_address})
             dvr_macs = self.get_dvr_mac_address_list(context)
             # TODO(vivek): improve scalability of this fanout by
             # sending a single mac address rather than the entire set
             self.notifier.dvr_mac_address_update(context, dvr_macs)
             return self._make_dvr_mac_address_dict(dvr_mac_binding)
         except db_exc.DBDuplicateEntry:
             LOG.debug("Generated DVR mac %(mac)s exists."
                       " Remaining attempts %(attempts_left)s.",
                       {'mac': mac_address, 'attempts_left': attempt})
     LOG.error(_LE("MAC generation error after %s attempts"), max_retries)
     raise ext_dvr.MacAddressGenerationFailure(host=host)
Example #12
0
 def generate_router_info(self):
     self.info = copy.deepcopy(FAKE_ROUTER)
     self.info["id"] = _uuid()
     self.info["_interfaces"] = [self._generate_private_interface_for_router(subnet) for subnet in self.private_nets]
     self.info["gw_port"]["id"] = _uuid()
     self.info["gw_port"]["fixed_ips"][0]["ip_address"] = str(self.public_net)
     self.info["gw_port"]["mac_address"] = common_utils.get_random_mac(MAC_BASE)
     self.info["ha"] = False
Example #13
0
    def test_delete_neigh_entries(self):
        attr = self.generate_device_details(
            ip_cidrs=["%s/24" % TEST_IP, "fd00::1/64"])
        mac_address = utils.get_random_mac('fa:16:3e:00:00:00'.split(':'))
        device = self.manage_device(attr)

        # trying to delete a non-existent entry shouldn't raise an error
        device.neigh.delete(TEST_IP_NEIGH, mac_address)
Example #14
0
 def setUp(self):
     super(TrunkParentPortTestCase, self).setUp()
     # Mock out connecting to ovsdb
     mock.patch(NATIVE_OVSDB_CONNECTION).start()
     trunk_id = uuidutils.generate_uuid()
     port_id = uuidutils.generate_uuid()
     trunk_mac = common_utils.get_random_mac('fa:16:3e:00:00:00'.split(':'))
     self.trunk = trunk_manager.TrunkParentPort(trunk_id, port_id,
                                                trunk_mac)
Example #15
0
 def setUp(self):
     super(TrunkParentPortTestCase, self).setUp()
     # Mock out connecting to ovsdb
     mock.patch(NATIVE_OVSDB_CONNECTION).start()
     trunk_id = uuidutils.generate_uuid()
     port_id = uuidutils.generate_uuid()
     trunk_mac = common_utils.get_random_mac('fa:16:3e:00:00:00'.split(':'))
     self.trunk = trunk_manager.TrunkParentPort(
         trunk_id, port_id, trunk_mac)
Example #16
0
 def setUp(self):
     super(TrunkParentPortTestCase, self).setUp()
     trunk_id = uuidutils.generate_uuid()
     port_id = uuidutils.generate_uuid()
     port_mac = common_utils.get_random_mac('fa:16:3e:00:00:00'.split(':'))
     self.trunk = trunk_manager.TrunkParentPort(trunk_id, port_id, port_mac)
     self.trunk.bridge = self.useFixture(
         net_helpers.OVSTrunkBridgeFixture(
             self.trunk.bridge.br_name)).bridge
     self.br_int = self.useFixture(net_helpers.OVSBridgeFixture()).bridge
Example #17
0
 def setUp(self):
     super(TrunkParentPortTestCase, self).setUp()
     trunk_id = uuidutils.generate_uuid()
     port_id = uuidutils.generate_uuid()
     port_mac = common_utils.get_random_mac('fa:16:3e:00:00:00'.split(':'))
     self.trunk = trunk_manager.TrunkParentPort(trunk_id, port_id, port_mac)
     self.trunk.bridge = self.useFixture(
         net_helpers.OVSTrunkBridgeFixture(
             self.trunk.bridge.br_name)).bridge
     self.br_int = self.useFixture(net_helpers.OVSBridgeFixture()).bridge
Example #18
0
 def _create_test_port_dict(self):
     return {'id': uuidutils.generate_uuid(),
             'mac_address': utils.get_random_mac(
                 'fa:16:3e:00:00:00'.split(':')),
             'fixed_ips': [{
                 'ip_address': '10.%d.%d.%d' % (
                      random.randint(3, 254),
                      random.randint(3, 254),
                      random.randint(3, 254))}],
             'vif_name': base.get_rand_name(
                 self.driver.DEV_NAME_LEN, self.driver.DEV_NAME_PREFIX)}
Example #19
0
 def _create_test_port_dict(self):
     return {'id': uuidutils.generate_uuid(),
             'mac_address': utils.get_random_mac(
                 'fa:16:3e:00:00:00'.split(':')),
             'fixed_ips': [{
                 'ip_address': '10.%d.%d.%d' % (
                      random.randint(3, 254),
                      random.randint(3, 254),
                      random.randint(3, 254))}],
             'vif_name': base.get_rand_name(
                 self.driver.DEV_NAME_LEN, self.driver.DEV_NAME_PREFIX)}
Example #20
0
 def generate_router_info(self):
     self.info = copy.deepcopy(FAKE_ROUTER)
     self.info['id'] = _uuid()
     self.info['_interfaces'] = [
         self._generate_private_interface_for_router(subnet)
         for subnet in self.private_nets]
     self.info['gw_port']['id'] = _uuid()
     self.info['gw_port']['fixed_ips'][0]['ip_address'] = str(
         self.public_net)
     self.info['gw_port']['mac_address'] = (
         common_utils.get_random_mac(MAC_BASE))
     self.info['ha'] = False
Example #21
0
 def generate_router_info(self):
     self.info = copy.deepcopy(FAKE_ROUTER)
     self.info['id'] = _uuid()
     self.info['_interfaces'] = [
         self._generate_private_interface_for_router(subnet)
         for subnet in self.private_nets
     ]
     self.info['gw_port']['id'] = _uuid()
     self.info['gw_port']['fixed_ips'][0]['ip_address'] = str(
         self.public_net)
     self.info['gw_port']['mac_address'] = (
         common_utils.get_random_mac(MAC_BASE))
     self.info['ha'] = False
 def setUp(self):
     super(SubPortTestCase, self).setUp()
     trunk_id = uuidutils.generate_uuid()
     port_id = uuidutils.generate_uuid()
     port_mac = common_utils.get_random_mac('fa:16:3e:00:00:00'.split(':'))
     trunk_bridge_name = utils.gen_trunk_br_name(trunk_id)
     trunk_bridge = self.useFixture(
         net_helpers.OVSTrunkBridgeFixture(trunk_bridge_name)).bridge
     segmentation_id = helpers.get_not_used_vlan(trunk_bridge, VLAN_RANGE)
     self.subport = trunk_manager.SubPort(trunk_id, port_id, port_mac,
                                          segmentation_id)
     self.subport.bridge = trunk_bridge
     self.br_int = self.useFixture(net_helpers.OVSBridgeFixture()).bridge
Example #23
0
 def _create_dvr_mac_address_retry(self, context, host, base_mac):
     with context.session.begin(subtransactions=True):
         mac_address = utils.get_random_mac(base_mac)
         dvr_mac_binding = dvr_models.DistributedVirtualRouterMacAddress(
             host=host, mac_address=mac_address)
         context.session.add(dvr_mac_binding)
         LOG.debug("Generated DVR mac for host %(host)s "
                   "is %(mac_address)s",
                   {'host': host, 'mac_address': mac_address})
     dvr_macs = self.get_dvr_mac_address_list(context)
     # TODO(vivek): improve scalability of this fanout by
     # sending a single mac address rather than the entire set
     self.notifier.dvr_mac_address_update(context, dvr_macs)
     return self._make_dvr_mac_address_dict(dvr_mac_binding)
 def _generate_info(self, public_ip, private_cidr, enable_ha=False):
     """Generate router info"""
     info = copy.deepcopy(FAKE_ROUTER)
     info['id'] = _uuid()
     info['_interfaces'][0]['id'] = _uuid()
     (info['_interfaces'][0]
      ['mac_address']) = common_utils.get_random_mac(MAC_BASE)
     (info['_interfaces'][0]['fixed_ips'][0]
      ['ip_address']) = str(private_cidr[4])
     info['_interfaces'][0]['subnets'][0].update({
         'cidr': str(private_cidr),
         'gateway_ip': str(private_cidr[1])})
     info['gw_port']['id'] = _uuid()
     info['gw_port']['fixed_ips'][0]['ip_address'] = str(public_ip)
     info['gw_port']['mac_address'] = common_utils.get_random_mac(MAC_BASE)
     if enable_ha:
         info['ha'] = True
         info['ha_vr_id'] = 1
         info[l3_constants.HA_INTERFACE_KEY] = (
             l3_test_common.get_ha_interface())
     else:
         info['ha'] = False
     return info
Example #25
0
    def test_plug_succeeds(self):
        device_name = utils.get_rand_name()
        mac_address = utils.get_random_mac('fa:16:3e:00:00:00'.split(':'))
        namespace = self.useFixture(net_helpers.NamespaceFixture()).name

        self.assertFalse(self.bridge.get_port_name_list())
        self.interface.plug(network_id=uuidutils.generate_uuid(),
                            port_id=uuidutils.generate_uuid(),
                            device_name=device_name,
                            mac_address=mac_address,
                            bridge=self.bridge.br_name,
                            namespace=namespace)
        self.assertIn(device_name, self.bridge.get_port_name_list())
        self.assertTrue(ip_lib.device_exists(device_name, namespace))
 def _generate_info(self, public_ip, private_cidr, enable_ha=False):
     """Generate router info"""
     info = copy.deepcopy(FAKE_ROUTER)
     info['id'] = _uuid()
     info['_interfaces'][0]['id'] = _uuid()
     (info['_interfaces'][0]
      ['mac_address']) = common_utils.get_random_mac(MAC_BASE)
     (info['_interfaces'][0]['fixed_ips'][0]
      ['ip_address']) = str(private_cidr[4])
     info['_interfaces'][0]['subnets'][0].update({
         'cidr': str(private_cidr),
         'gateway_ip': str(private_cidr[1])})
     info['gw_port']['id'] = _uuid()
     info['gw_port']['fixed_ips'][0]['ip_address'] = str(public_ip)
     info['gw_port']['mac_address'] = common_utils.get_random_mac(MAC_BASE)
     if enable_ha:
         info['ha'] = True
         info['ha_vr_id'] = 1
         info[l3_constants.HA_INTERFACE_KEY] = (
             l3_test_common.get_ha_interface())
     else:
         info['ha'] = False
     return info
Example #27
0
    def test_plug_succeeds(self):
        device_name = utils.get_rand_name()
        mac_address = utils.get_random_mac('fa:16:3e:00:00:00'.split(':'))
        namespace = self.useFixture(net_helpers.NamespaceFixture()).name

        self.assertFalse(self.bridge.get_port_name_list())
        self.interface.plug(network_id=uuidutils.generate_uuid(),
                            port_id=uuidutils.generate_uuid(),
                            device_name=device_name,
                            mac_address=mac_address,
                            bridge=self.bridge.br_name,
                            namespace=namespace)
        self.assertIn(device_name, self.bridge.get_port_name_list())
        self.assertTrue(ip_lib.device_exists(device_name, namespace))
Example #28
0
 def setUp(self):
     super(SubPortTestCase, self).setUp()
     trunk_id = uuidutils.generate_uuid()
     port_id = uuidutils.generate_uuid()
     port_mac = common_utils.get_random_mac('fa:16:3e:00:00:00'.split(':'))
     trunk_bridge_name = utils.gen_trunk_br_name(trunk_id)
     trunk_bridge = self.useFixture(
         net_helpers.OVSTrunkBridgeFixture(trunk_bridge_name)).bridge
     segmentation_id = helpers.get_not_used_vlan(
         trunk_bridge, VLAN_RANGE)
     self.subport = trunk_manager.SubPort(
         trunk_id, port_id, port_mac, segmentation_id)
     self.subport.bridge = trunk_bridge
     self.br_int = self.useFixture(net_helpers.OVSBridgeFixture()).bridge
 def test_arp_correct_protection_allowed_address_pairs(self):
     smac = self.source.port.link.address
     port = {'mac_address': '00:11:22:33:44:55',
             'allowed_address_pairs': [{'mac_address': smac,
                                        'ip_address': self.source.ip}]}
     # make sure a large number of allowed address pairs works
     for i in range(100000):
         port['allowed_address_pairs'].append(
             {'mac_address': utils.get_random_mac(
                  'fa:16:3e:00:00:00'.split(':')),
              'ip_address': '10.10.10.10'})
     self._add_arp_protection(self.source, ['1.2.2.2'], port)
     self._add_arp_protection(self.destination, [self.destination.ip])
     arping(self.source.namespace, self.destination.ip)
     arping(self.destination.namespace, self.source.ip)
 def test_arp_correct_protection_allowed_address_pairs(self):
     smac = self.source.port.link.address
     port = {
         "mac_address": "00:11:22:33:44:55",
         "allowed_address_pairs": [{"mac_address": smac, "ip_address": self.source.ip}],
     }
     # make sure a large number of allowed address pairs works
     for i in range(100000):
         port["allowed_address_pairs"].append(
             {"mac_address": utils.get_random_mac("fa:16:3e:00:00:00".split(":")), "ip_address": "10.10.10.10"}
         )
     self._add_arp_protection(self.source, ["1.2.2.2"], port)
     self._add_arp_protection(self.destination, [self.destination.ip])
     arping(self.source.namespace, self.destination.ip)
     arping(self.destination.namespace, self.source.ip)
Example #31
0
    def _create_dvr_mac_address_retry(self, context, host, base_mac):
        with db_api.context_manager.writer.using(context):
            mac_address = utils.get_random_mac(base_mac)
            dvr_mac_binding = router.DVRMacAddress(
                context, host=host, mac_address=netaddr.EUI(mac_address))
            dvr_mac_binding.create()
            LOG.debug("Generated DVR mac for host %(host)s "
                      "is %(mac_address)s",
                      {'host': host, 'mac_address': mac_address})

        dvr_macs = self.get_dvr_mac_address_list(context)
        # TODO(vivek): improve scalability of this fanout by
        # sending a single mac address rather than the entire set
        self.notifier.dvr_mac_address_update(context, dvr_macs)
        return self._make_dvr_mac_address_dict(dvr_mac_binding)
Example #32
0
    def _setup_port_binding(self, **kwargs):
        with self.ctx.session.begin(subtransactions=True):
            mac = utils.get_random_mac('fa:16:3e:00:00:00'.split(':'))
            port_id = uuidutils.generate_uuid()
            network_id = kwargs.get('network_id', TEST_NETWORK_ID)
            device_owner = kwargs.get('device_owner', '')
            device_id = kwargs.get('device_id', '')
            host = kwargs.get('host', helpers.HOST)

            self.ctx.session.add(
                models_v2.Port(id=port_id,
                               network_id=network_id,
                               mac_address=mac,
                               admin_state_up=True,
                               status=constants.PORT_STATUS_ACTIVE,
                               device_id=device_id,
                               device_owner=device_owner))

            port_binding_cls = models.PortBinding
            binding_kwarg = {
                'port_id': port_id,
                'host': host,
                'vif_type': portbindings.VIF_TYPE_UNBOUND,
                'vnic_type': portbindings.VNIC_NORMAL
            }

            if device_owner == constants.DEVICE_OWNER_DVR_INTERFACE:
                port_binding_cls = models.DistributedPortBinding
                binding_kwarg['router_id'] = TEST_ROUTER_ID
                binding_kwarg['status'] = constants.PORT_STATUS_DOWN

            self.ctx.session.add(port_binding_cls(**binding_kwarg))

            if network_id == TEST_HA_NETWORK_ID:
                agent = self.get_l3_agent_by_host(host)
                haport_bindings_cls = l3_hamode_db.L3HARouterAgentPortBinding
                habinding_kwarg = {
                    'port_id':
                    port_id,
                    'router_id':
                    device_id,
                    'l3_agent_id':
                    agent['id'],
                    'state':
                    kwargs.get('host_state', n_const.HA_ROUTER_STATE_ACTIVE)
                }
                self.ctx.session.add(haport_bindings_cls(**habinding_kwarg))
Example #33
0
 def _create_dvr_mac_address_retry(self, context, host, base_mac):
     with context.session.begin(subtransactions=True):
         mac_address = utils.get_random_mac(base_mac)
         dvr_mac_binding = DistributedVirtualRouterMacAddress(
             host=host, mac_address=mac_address)
         context.session.add(dvr_mac_binding)
         LOG.debug(
             "Generated DVR mac for host %(host)s "
             "is %(mac_address)s", {
                 'host': host,
                 'mac_address': mac_address
             })
     dvr_macs = self.get_dvr_mac_address_list(context)
     # TODO(vivek): improve scalability of this fanout by
     # sending a single mac address rather than the entire set
     self.notifier.dvr_mac_address_update(context, dvr_macs)
     return self._make_dvr_mac_address_dict(dvr_mac_binding)
Example #34
0
 def _generate_private_interface_for_router(self, subnet):
     subnet_id = _uuid()
     return {
         "id": _uuid(),
         "admin_state_up": True,
         "network_id": _uuid(),
         "mac_address": common_utils.get_random_mac(MAC_BASE),
         "subnets": [
             {
                 "ipv6_ra_mode": None,
                 "cidr": str(subnet),
                 "gateway_ip": str(subnet[1]),
                 "id": subnet_id,
                 "ipv6_address_mode": None,
             }
         ],
         "fixed_ips": [{"subnet_id": subnet_id, "prefixlen": 24, "ip_address": str(subnet[4])}],
     }
Example #35
0
    def setUp(self):
        """Prepare resources.

        Set up trunk_dict representing incoming data from Neutron-server when
        fetching for trunk details. Another resource trunk_br represents the
        trunk bridge which its creation is simulated when creating a port in l2
        agent framework.
        """
        super(OVSDBHandlerTestCase, self).setUp()
        trunk_id = uuidutils.generate_uuid()
        self.trunk_dict = {
            'id': trunk_id,
            'mac_address': common_utils.get_random_mac(
                'fa:16:3e:00:00:00'.split(':')),
            'sub_ports': []}
        self.trunk_port_name = generate_tap_device_name()
        self.trunk_br = trunk_manager.TrunkBridge(trunk_id)
        self.ovsdb_handler = self._prepare_mocked_ovsdb_handler()
Example #36
0
    def _get_ovn_dhcpv4_opts(self, subnet, network, server_mac=None):
        if not subnet['gateway_ip']:
            return {}

        default_lease_time = str(config.get_ovn_dhcp_default_lease_time())
        mtu = network['mtu']
        options = {
            'server_id': subnet['gateway_ip'],
            'lease_time': default_lease_time,
            'mtu': str(mtu),
            'router': subnet['gateway_ip']
        }

        if server_mac:
            options['server_mac'] = server_mac
        else:
            options['server_mac'] = n_utils.get_random_mac(
                cfg.CONF.base_mac.split(':'))

        if subnet['dns_nameservers']:
            dns_servers = '{'
            for dns in subnet["dns_nameservers"]:
                dns_servers += dns + ', '
            dns_servers = dns_servers.strip(', ')
            dns_servers += '}'
            options['dns_server'] = dns_servers

        # If subnet hostroutes are defined, add them in the
        # 'classless_static_route' dhcp option
        classless_static_routes = "{"
        for route in subnet['host_routes']:
            classless_static_routes += ("%s,%s, ") % (
                route['destination'], route['nexthop'])

        if classless_static_routes != "{":
            # if there are static routes, then we need to add the
            # default route in this option. As per RFC 3442 dhcp clients
            # should ignore 'router' dhcp option (option 3)
            # if option 121 is present.
            classless_static_routes += "0.0.0.0/0,%s}" % (subnet['gateway_ip'])
            options['classless_static_route'] = classless_static_routes

        return options
Example #37
0
    def test_get_neigh_entries(self):
        attr = self.generate_device_details(
            ip_cidrs=["%s/24" % TEST_IP, "fd00::1/64"]
        )
        mac_address = utils.get_random_mac('fa:16:3e:00:00:00'.split(':'))
        device = self.manage_device(attr)
        device.neigh.add(TEST_IP_NEIGH, mac_address)

        expected_neighs = [{'dst': TEST_IP_NEIGH,
                            'lladdr': mac_address,
                            'device': attr.name}]

        neighs = device.neigh.dump(4)
        self.assertItemsEqual(expected_neighs, neighs)
        self.assertIsInstance(neighs, list)

        device.neigh.delete(TEST_IP_NEIGH, mac_address)
        neighs = device.neigh.dump(4, dst=TEST_IP_NEIGH, lladdr=mac_address)
        self.assertEqual([], neighs)
Example #38
0
    def _get_ovn_dhcpv4_opts(self, subnet, network, server_mac=None):
        if not subnet['gateway_ip']:
            return {}

        default_lease_time = str(config.get_ovn_dhcp_default_lease_time())
        mtu = network['mtu']
        options = {
            'server_id': subnet['gateway_ip'],
            'lease_time': default_lease_time,
            'mtu': str(mtu),
            'router': subnet['gateway_ip']
        }

        if server_mac:
            options['server_mac'] = server_mac
        else:
            options['server_mac'] = n_utils.get_random_mac(
                cfg.CONF.base_mac.split(':'))

        if subnet['dns_nameservers']:
            dns_servers = '{'
            for dns in subnet["dns_nameservers"]:
                dns_servers += dns + ', '
            dns_servers = dns_servers.strip(', ')
            dns_servers += '}'
            options['dns_server'] = dns_servers

        # If subnet hostroutes are defined, add them in the
        # 'classless_static_route' dhcp option
        classless_static_routes = "{"
        for route in subnet['host_routes']:
            classless_static_routes += ("%s,%s, ") % (route['destination'],
                                                      route['nexthop'])

        if classless_static_routes != "{":
            # if there are static routes, then we need to add the
            # default route in this option. As per RFC 3442 dhcp clients
            # should ignore 'router' dhcp option (option 3)
            # if option 121 is present.
            classless_static_routes += "0.0.0.0/0,%s}" % (subnet['gateway_ip'])
            options['classless_static_route'] = classless_static_routes

        return options
    def setUp(self):
        super(TestTaasPlugin, self).setUp()
        mock.patch.object(n_rpc, 'create_connection', auto_spec=True).start()
        mock.patch.object(taas_agent_api, 'TaasCallbacks',
                          auto_spec=True).start()
        mock.patch.object(taas_agent_api, 'TaasAgentApi',
                          auto_spec=True).start()
        self.driver = mock.MagicMock()
        mock.patch('neutron.services.service_base.load_drivers',
                   return_value=({
                       'dummy_provider': self.driver
                   }, 'dummy_provider')).start()
        mock.patch('neutron.db.servicetype_db.ServiceTypeManager.get_instance',
                   return_value=mock.MagicMock()).start()
        self._plugin = taas_plugin.TaasPlugin()
        self._context = context.get_admin_context()

        self._project_id = self._tenant_id = 'tenant-X'
        self._network_id = uuidutils.generate_uuid()
        self._host_id = 'host-A'
        self._port_id = uuidutils.generate_uuid()
        self._port_details = {
            'tenant_id': self._tenant_id,
            'binding:host_id': self._host_id,
            'mac_address':
            n_utils.get_random_mac('fa:16:3e:00:00:00'.split(':')),
        }
        self._tap_service = {
            'tenant_id': self._tenant_id,
            'name': 'MyTap',
            'description': 'This is my tap service',
            'port_id': self._port_id,
            'project_id': self._project_id,
        }
        self._tap_flow = {
            'description': 'This is my tap flow',
            'direction': 'BOTH',
            'name': 'MyTapFlow',
            'source_port': self._port_id,
            'tenant_id': self._tenant_id,
            'project_id': self._project_id,
        }
Example #40
0
    def _test_mtu_set_after_action(self, device_name, br_name, namespace,
                                   action=None):
        mac_address = utils.get_random_mac('fa:16:3e:00:00:00'.split(':'))

        plug = functools.partial(
            self.interface.plug,
            network_id=uuidutils.generate_uuid(),
            port_id=uuidutils.generate_uuid(),
            device_name=device_name,
            mac_address=mac_address,
            bridge=self.bridge_name,
            namespace=namespace)
        plug(mtu=1500)
        self.assertTrue(ip_lib.device_exists(device_name, namespace))

        action = action or plug
        for mtu in (1450, 1500, 9000, 9000, 1450):
            action(mtu=mtu)
            self.assertEqual(
                mtu,
                ip_lib.IPDevice(device_name, namespace=namespace).link.mtu)
Example #41
0
 def _create_dvr_mac_for_extern_ip(self, context, host):
     """Create dvr mac address for a extern net ip."""
     base_mac = cfg.CONF.dvr_base_mac.split(':')
     max_retries = cfg.CONF.mac_generation_retries
     for attempt in reversed(range(max_retries)):
         try:
             with context.session.begin(subtransactions=True):
                 mac_address = utils.get_random_mac(base_mac)
                 dvr_mac_binding = DistributedVirtualRouterMacAddress(
                     host=host, mac_address=mac_address)
                 context.session.add(dvr_mac_binding)
                 LOG.debug("Generated dvr mac for host %(host)s "
                           "is %(mac_address)s",
                           {'host': host, 'mac_address': mac_address})
             return self._make_dvr_mac_address_dict(dvr_mac_binding)
         except db_exc.DBDuplicateEntry:
             LOG.debug("Generated dvr mac %(mac)s exists."
                       " Remaining attempts %(attempts_left)s.",
                       {'mac': mac_address, 'attempts_left': attempt})
     LOG.error(_("MAC generation error after %s attempts"), max_retries)
     raise ext_dvr.MacAddressGenerationFailure(host=host)
Example #42
0
 def test_arp_correct_protection_allowed_address_pairs(self):
     smac = self.source.port.link.address
     port = {
         'mac_address':
         '00:11:22:33:44:55',
         'allowed_address_pairs': [{
             'mac_address': smac,
             'ip_address': self.source.ip
         }]
     }
     # make sure a large number of allowed address pairs works
     for i in range(100000):
         port['allowed_address_pairs'].append({
             'mac_address':
             utils.get_random_mac('fa:16:3e:00:00:00'.split(':')),
             'ip_address':
             '10.10.10.10'
         })
     self._add_arp_protection(self.source, ['1.2.2.2'], port)
     self._add_arp_protection(self.destination, [self.destination.ip])
     arping(self.source.namespace, self.destination.ip)
     arping(self.destination.namespace, self.source.ip)
Example #43
0
    def _test_mtu_set_after_action(self,
                                   device_name,
                                   br_name,
                                   namespace,
                                   action=None):
        mac_address = utils.get_random_mac('fa:16:3e:00:00:00'.split(':'))

        plug = functools.partial(self.interface.plug,
                                 network_id=uuidutils.generate_uuid(),
                                 port_id=uuidutils.generate_uuid(),
                                 device_name=device_name,
                                 mac_address=mac_address,
                                 bridge=self.bridge_name,
                                 namespace=namespace)
        plug(mtu=1500)
        self.assertTrue(ip_lib.device_exists(device_name, namespace))

        action = action or plug
        for mtu in (1450, 1500, 9000, 9000, 1450):
            action(mtu=mtu)
            self.assertEqual(
                mtu,
                ip_lib.IPDevice(device_name, namespace=namespace).link.mtu)
Example #44
0
    def _get_ovn_dhcpv4_opts(self, subnet, network):
        if not subnet["gateway_ip"]:
            return {}

        default_lease_time = str(config.get_ovn_dhcp_default_lease_time())
        mtu = network["mtu"]
        options = {
            "server_id": subnet["gateway_ip"],
            "server_mac": n_utils.get_random_mac(cfg.CONF.base_mac.split(":")),
            "lease_time": default_lease_time,
            "mtu": str(mtu),
            "router": subnet["gateway_ip"],
        }

        if subnet["dns_nameservers"]:
            dns_servers = "{"
            for dns in subnet["dns_nameservers"]:
                dns_servers += dns + ", "
            dns_servers = dns_servers.strip(", ")
            dns_servers += "}"
            options["dns_server"] = dns_servers

        # If subnet hostroutes are defined, add them in the
        # 'classless_static_route' dhcp option
        classless_static_routes = "{"
        for route in subnet["host_routes"]:
            classless_static_routes += ("%s,%s, ") % (route["destination"], route["nexthop"])

        if classless_static_routes != "{":
            # if there are static routes, then we need to add the
            # default route in this option. As per RFC 3442 dhcp clients
            # should ignore 'router' dhcp option (option 3)
            # if option 121 is present.
            classless_static_routes += "0.0.0.0/0,%s}" % (subnet["gateway_ip"])
            options["classless_static_route"] = classless_static_routes

        return options
Example #45
0
 def _generate_private_interface_for_router(self, subnet):
     subnet_id = _uuid()
     return {
         'id': _uuid(),
         'admin_state_up': True,
         'network_id': _uuid(),
         'mac_address': common_utils.get_random_mac(MAC_BASE),
         'subnets': [
             {
                 'ipv6_ra_mode': None,
                 'cidr': str(subnet),
                 'gateway_ip': str(subnet[1]),
                 'id': subnet_id,
                 'ipv6_address_mode': None
             }
         ],
         'fixed_ips': [
             {
                 'subnet_id': subnet_id,
                 'prefixlen': 24,
                 'ip_address': str(subnet[4])
             }
         ]
     }
Example #46
0
 def _generate_private_interface_for_router(self, subnet):
     subnet_id = _uuid()
     return {
         'id':
         _uuid(),
         'admin_state_up':
         True,
         'network_id':
         _uuid(),
         'mac_address':
         common_utils.get_random_mac(MAC_BASE),
         'subnets': [{
             'ipv6_ra_mode': None,
             'cidr': str(subnet),
             'gateway_ip': str(subnet[1]),
             'id': subnet_id,
             'ipv6_address_mode': None
         }],
         'fixed_ips': [{
             'subnet_id': subnet_id,
             'prefixlen': 24,
             'ip_address': str(subnet[4])
         }]
     }
Example #47
0
    def _setup_port_binding(self, **kwargs):
        with self.ctx.session.begin(subtransactions=True):
            mac = utils.get_random_mac('fa:16:3e:00:00:00'.split(':'))
            port_id = uuidutils.generate_uuid()
            network_id = kwargs.get('network_id', TEST_NETWORK_ID)
            device_owner = kwargs.get('device_owner', '')
            device_id = kwargs.get('device_id', '')
            host = kwargs.get('host', helpers.HOST)

            self.ctx.session.add(models_v2.Port(
                id=port_id, network_id=network_id, mac_address=mac,
                admin_state_up=True, status=constants.PORT_STATUS_ACTIVE,
                device_id=device_id, device_owner=device_owner))

            port_binding_cls = models.PortBinding
            binding_kwarg = {'port_id': port_id,
                             'host': host,
                             'vif_type': portbindings.VIF_TYPE_UNBOUND,
                             'vnic_type': portbindings.VNIC_NORMAL}

            if device_owner == constants.DEVICE_OWNER_DVR_INTERFACE:
                port_binding_cls = models.DistributedPortBinding
                binding_kwarg['router_id'] = TEST_ROUTER_ID
                binding_kwarg['status'] = constants.PORT_STATUS_DOWN

            self.ctx.session.add(port_binding_cls(**binding_kwarg))

            if network_id == TEST_HA_NETWORK_ID:
                agent = self.get_l3_agent_by_host(host)
                haport_bindings_cls = l3ha_model.L3HARouterAgentPortBinding
                habinding_kwarg = {'port_id': port_id,
                                   'router_id': device_id,
                                   'l3_agent_id': agent['id'],
                                   'state': kwargs.get('host_state',
                                       n_const.HA_ROUTER_STATE_ACTIVE)}
                self.ctx.session.add(haport_bindings_cls(**habinding_kwarg))
Example #48
0
    def test_connectivity(self):
        """Test connectivity with trunk and sub ports.

        In this test we create a vm that has a trunk on net1 and a vm peer on
        the same network. We check connectivity between the peer and the vm.
        We create a sub port on net2 and a peer, check connectivity again.

        """
        vlan_net1 = helpers.get_not_used_vlan(self.tester.bridge, VLAN_RANGE)
        vlan_net2 = helpers.get_not_used_vlan(self.tester.bridge, VLAN_RANGE)
        trunk_mac = common_utils.get_random_mac('fa:16:3e:00:00:00'.split(':'))
        sub_port_mac = common_utils.get_random_mac(
            'fa:16:3e:00:00:00'.split(':'))
        sub_port_segmentation_id = helpers.get_not_used_vlan(
            self.tester.bridge, VLAN_RANGE)
        LOG.debug("Using %(n1)d vlan tag as local vlan ID for net1 and %(n2)d "
                  "for local vlan ID for net2", {
                      'n1': vlan_net1, 'n2': vlan_net2})
        self.tester.set_peer_tag(vlan_net1)
        self.trunk_manager.create_trunk(self.trunk.trunk_id,
                                        self.trunk.port_id,
                                        trunk_mac)

        # tag the patch port, this should be done by the ovs agent but we mock
        # it for this test
        conn_testers.OVSBaseConnectionTester.set_tag(
            self.trunk.patch_port_int_name, self.tester.bridge, vlan_net1)

        self.tester.wait_for_connection(self.tester.INGRESS)
        self.tester.wait_for_connection(self.tester.EGRESS)

        self.tester.add_vlan_interface_and_peer(sub_port_segmentation_id,
                                                self.net2_cidr)
        conn_testers.OVSBaseConnectionTester.set_tag(
            self.tester._peer2.port.name, self.tester.bridge, vlan_net2)

        sub_port = trunk_manager.SubPort(self.trunk.trunk_id,
                                         uuidutils.generate_uuid(),
                                         sub_port_mac,
                                         sub_port_segmentation_id)

        self.trunk_manager.add_sub_port(sub_port.trunk_id,
                                        sub_port.port_id,
                                        sub_port.port_mac,
                                        sub_port.segmentation_id)
        # tag the patch port, this should be done by the ovs agent but we mock
        # it for this test
        conn_testers.OVSBaseConnectionTester.set_tag(
            sub_port.patch_port_int_name, self.tester.bridge, vlan_net2)

        self.tester.wait_for_sub_port_connectivity(self.tester.INGRESS)
        self.tester.wait_for_sub_port_connectivity(self.tester.EGRESS)

        self.trunk_manager.remove_sub_port(sub_port.trunk_id,
                                           sub_port.port_id)
        self.tester.wait_for_sub_port_no_connectivity(self.tester.INGRESS)
        self.tester.wait_for_sub_port_no_connectivity(self.tester.EGRESS)

        self.trunk_manager.remove_trunk(self.trunk.trunk_id,
                                        self.trunk.port_id)
        self.tester.wait_for_no_connection(self.tester.INGRESS)
 def _generate_mac():
     return utils.get_random_mac(cfg.CONF.base_mac.split(':'))
}

PUBLIC_NET = netaddr.IPNetwork('19.4.4.0/24')
PRIVATE_NET = netaddr.IPNetwork('35.4.0.0/16')
FAKE_PUBLIC_SUBNET_ID = _uuid()
FAKE_PRIVATE_SUBNET_ID = _uuid()

MAC_BASE = cfg.CONF.base_mac.split(':')
FAKE_ROUTER = {
    'id': _uuid(),
    '_interfaces': [
        {
            'id': _uuid(),
            'admin_state_up': True,
            'network_id': _uuid(),
            'mac_address': common_utils.get_random_mac(MAC_BASE),
            'subnets': [
                {
                    'ipv6_ra_mode': None,
                    'cidr': str(PRIVATE_NET),
                    'gateway_ip': str(PRIVATE_NET[1]),
                    'id': FAKE_PRIVATE_SUBNET_ID,
                    'ipv6_address_mode': None
                }
            ],
            'fixed_ips': [
                {
                    'subnet_id': FAKE_PRIVATE_SUBNET_ID,
                    'prefixlen': 24,
                    'ip_address': PRIVATE_NET[4]
                }
Example #51
0
    def test_connectivity(self):
        """Test connectivity with trunk and sub ports.

        In this test we create a vm that has a trunk on net1 and a vm peer on
        the same network. We check connectivity between the peer and the vm.
        We create a sub port on net2 and a peer, check connectivity again.

        """
        vlan_net1 = helpers.get_not_used_vlan(self.tester.bridge, VLAN_RANGE)
        vlan_net2 = helpers.get_not_used_vlan(self.tester.bridge, VLAN_RANGE)
        trunk_mac = common_utils.get_random_mac('fa:16:3e:00:00:00'.split(':'))
        sub_port_mac = common_utils.get_random_mac(
            'fa:16:3e:00:00:00'.split(':'))
        sub_port_segmentation_id = helpers.get_not_used_vlan(
            self.tester.bridge, VLAN_RANGE)
        LOG.debug("Using %(n1)d vlan tag as local vlan ID for net1 and %(n2)d "
                  "for local vlan ID for net2", {
                      'n1': vlan_net1, 'n2': vlan_net2})
        self.tester.set_peer_tag(vlan_net1)
        self.trunk_manager.create_trunk(self.trunk.trunk_id,
                                        self.trunk.port_id,
                                        trunk_mac)

        # tag the patch port, this should be done by the ovs agent but we mock
        # it for this test
        conn_testers.OVSBaseConnectionTester.set_tag(
            self.trunk.patch_port_int_name, self.tester.bridge, vlan_net1)

        self.tester.assert_connection(protocol=self.tester.ICMP,
                                      direction=self.tester.INGRESS)
        self.tester.assert_connection(protocol=self.tester.ICMP,
                                      direction=self.tester.EGRESS)

        self.tester.add_vlan_interface_and_peer(sub_port_segmentation_id,
                                                self.net2_cidr)
        conn_testers.OVSBaseConnectionTester.set_tag(
            self.tester._peer2.port.name, self.tester.bridge, vlan_net2)

        sub_port = trunk_manager.SubPort(self.trunk.trunk_id,
                                         uuidutils.generate_uuid(),
                                         sub_port_mac,
                                         sub_port_segmentation_id)

        self.trunk_manager.add_sub_port(sub_port.trunk_id,
                                        sub_port.port_id,
                                        sub_port.port_mac,
                                        sub_port.segmentation_id)
        # tag the patch port, this should be done by the ovs agent but we mock
        # it for this test
        conn_testers.OVSBaseConnectionTester.set_tag(
            sub_port.patch_port_int_name, self.tester.bridge, vlan_net2)

        self.tester.test_sub_port_icmp_connectivity(self.tester.INGRESS)
        self.tester.test_sub_port_icmp_connectivity(self.tester.EGRESS)

        self.trunk_manager.remove_sub_port(sub_port.trunk_id,
                                           sub_port.port_id)
        self.tester.test_sub_port_icmp_no_connectivity(self.tester.INGRESS)
        self.tester.test_sub_port_icmp_no_connectivity(self.tester.EGRESS)

        self.trunk_manager.remove_trunk(self.trunk.trunk_id,
                                        self.trunk.port_id)
        self.tester.assert_no_connection(protocol=self.tester.ICMP,
                                         direction=self.tester.INGRESS)
}

PUBLIC_NET = netaddr.IPNetwork('19.4.4.0/24')
PRIVATE_NET = netaddr.IPNetwork('35.4.0.0/16')
FAKE_PUBLIC_SUBNET_ID = _uuid()
FAKE_PRIVATE_SUBNET_ID = _uuid()

MAC_BASE = cfg.CONF.base_mac.split(':')
FAKE_ROUTER = {
    'id': _uuid(),
    '_interfaces': [
        {
            'id': _uuid(),
            'admin_state_up': True,
            'network_id': _uuid(),
            'mac_address': common_utils.get_random_mac(MAC_BASE),
            'subnets': [
                {
                    'ipv6_ra_mode': None,
                    'cidr': str(PRIVATE_NET),
                    'gateway_ip': str(PRIVATE_NET[1]),
                    'id': FAKE_PRIVATE_SUBNET_ID,
                    'ipv6_address_mode': None
                }
            ],
            'fixed_ips': [
                {
                    'subnet_id': FAKE_PRIVATE_SUBNET_ID,
                    'prefixlen': 24,
                    'ip_address': PRIVATE_NET[4]
                }
 def _generate_mac():
     return utils.get_random_mac(cfg.CONF.base_mac.split(':'))
Example #54
0
    def create_lrouter_in_ovn(self, router):
        """Create lrouter in OVN

        @param router: Router to be created in OVN
        @return: Nothing
        """

        router_name = utils.ovn_name(router['id'])
        external_ids = {
            ovn_const.OVN_ROUTER_NAME_EXT_ID_KEY:
            router.get('name', 'no_router_name')
        }
        enabled = router.get('admin_state_up')
        with self._ovn.transaction(check_error=True) as txn:
            txn.add(
                self._ovn.create_lrouter(router_name,
                                         external_ids=external_ids,
                                         enabled=enabled))
            # todo(zhoucx): create gw resource.
            selected_chassis = self.scheduler.select(self._ovn, self._sb_ovn,
                                                     None)
            # NOTE(zhoucx) here we can ignore selected_chassis == ovn_const.OVN_GATEWAY_INVALID_CHASSIS,
            # schedule_unhosted_routers() will update it .
            gw_router_name = utils.ovn_gateway_name(router['id'])
            router_options = {'chassis': selected_chassis}
            txn.add(
                self._ovn.create_lrouter(gw_router_name,
                                         external_ids={
                                             ovn_const.OVN_GATEWAY_EXT_ID_KEY:
                                             router['name']
                                         },
                                         options=router_options,
                                         enabled=True))
            # create transit switch
            transit_switch_name = 'transit-' + router['id']
            txn.add(
                self._ovn.create_lswitch(
                    lswitch_name=transit_switch_name,
                    external_ids={
                        ovn_const.OVN_TRANSIT_NETWORK_EXT_ID_KEY:
                        router['name']
                    }))
        # create
        with self._ovn.transaction(check_error=True) as txn:
            base_mac = n_cfg.CONF.base_mac.split(':')
            dvr_to_transit_port = {
                'mac_address': n_utils.get_random_mac(base_mac),
                'networks': ovn_const.OVN_LROUTER_TRANSIT_PORT_NETWORK,
                'ip_address': ovn_const.OVN_LROUTER_TRANSIT_PORT_IP
            }
            txn.add(
                self._ovn.add_lrouter_port(
                    name='dvr-to-transit-%s' % router['id'],
                    lrouter=router_name,
                    mac=dvr_to_transit_port['mac_address'],
                    networks=dvr_to_transit_port['networks']))

            txn.add(
                self._ovn.create_lswitch_port(
                    lport_name='transit-to-dvr-%s' % router['id'],
                    lswitch_name=transit_switch_name,
                    addresses=[
                        dvr_to_transit_port['mac_address'] + ' ' +
                        dvr_to_transit_port['ip_address']
                    ],
                    external_ids=None,
                    type='router'))
            gw_to_transit_port = {
                'mac_address': n_utils.get_random_mac(base_mac),
                'networks': ovn_const.OVN_GATEWAY_TRANSIT_PORT_NETWORK,
                'ip_address': ovn_const.OVN_GATEWAY_TRANSIT_PORT_IP
            }
            txn.add(
                self._ovn.add_lrouter_port(
                    name='gw-to-transit-%s' % router['id'],
                    lrouter=gw_router_name,
                    mac=gw_to_transit_port['mac_address'],
                    networks=gw_to_transit_port['networks']))
            txn.add(
                self._ovn.create_lswitch_port(
                    lport_name='transit-to-gw-%s' % router['id'],
                    lswitch_name=transit_switch_name,
                    addresses=[
                        gw_to_transit_port['mac_address'] + ' ' +
                        gw_to_transit_port['ip_address']
                    ],
                    external_ids=None,
                    type='router'))
        # connect them.
        with self._ovn.transaction(check_error=True) as txn:
            txn.add(
                self._ovn.set_lrouter_port_in_lswitch_port(
                    lswitch_port='transit-to-dvr-%s' % router['id'],
                    lrouter_port='dvr-to-transit-%s' % router['id']))
            txn.add(
                self._ovn.set_lrouter_port_in_lswitch_port(
                    lswitch_port='transit-to-gw-%s' % router['id'],
                    lrouter_port='gw-to-transit-%s' % router['id']))