Example #1
0
 def test_cookie_passed_to_addmod(self):
     self.br = ovs_lib.OVSBridge("br-tun")
     stamp = str(self.br.default_cookie)
     expected_calls = [
         mock.call(
             'add-flows', ['-'], 'hard_timeout=0,idle_timeout=0,priority=1,'
             'cookie=' + stamp + ',actions=drop'),
         mock.call('mod-flows', ['-'], 'cookie=' + stamp + ',actions=drop')
     ]
     with mock.patch.object(self.br, 'run_ofctl') as f:
         with ovs_lib.DeferredOVSBridge(self.br) as deferred_br:
             deferred_br.add_flow(actions='drop')
             deferred_br.mod_flow(actions='drop')
         f.assert_has_calls(expected_calls)
Example #2
0
    def _set_trunk_metadata(self, trunk_bridge, port, trunk_id, subport_ids):
        """Set trunk metadata in OVS port for trunk parent port."""
        # update the parent port external_ids to store the trunk bridge
        # name, trunk id and subport ids so we can easily remove the trunk
        # bridge and service ports once this port is removed
        trunk_bridge = trunk_bridge or ovs_lib.OVSBridge(
            utils.gen_trunk_br_name(trunk_id))
        port = port or self._get_parent_port(trunk_bridge)

        port['external_ids']['bridge_name'] = trunk_bridge.br_name
        port['external_ids']['trunk_id'] = trunk_id
        port['external_ids']['subport_ids'] = jsonutils.dumps(subport_ids)
        trunk_bridge.set_db_attribute('Interface', port['name'],
                                      'external_ids', port['external_ids'])
Example #3
0
 def fail_gw_router_port(router):
     # NOTE(slaweq): in HA failover tests there are two integration bridges
     # connected with veth pair to each other. To stop traffic from router's
     # namespace to gw ip (19.4.4.1) it needs to be blocked by openflow rule
     # as simple setting ovs_integration_bridge device DOWN will not be
     # enough because same IP address is also configured on
     # ovs_integration_bridge device from second router and it will still
     # respond to ping
     r_br = ovs_lib.OVSBridge(router.driver.conf.ovs_integration_bridge)
     external_port = router.get_ex_gw_port()
     for subnet in external_port['subnets']:
         r_br.add_flow(proto='ip',
                       nw_dst=subnet['gateway_ip'],
                       actions='drop')
Example #4
0
 def test_cleanup_on_vm_delete(self):
     with mock.patch.object(self.ovsdb_handler, 'handle_trunk_remove'):
         br_int = ovs_lib.OVSBridge(self.br_int)
         ports = self._fill_trunk_dict()
         self.setup_agent_and_ports(port_dicts=ports[:1])
         self.wait_until_ports_state(self.ports, up=True)
         self.trunk_br.delete_port(self.trunk_port_name)
         # We do not expect any instance port to show up on the trunk
         # bridge so we can set a much more aggressive timeout and
         # fail fast(er).
         self.ovsdb_handler.timeout = 1
         self.ovsdb_handler.handle_trunk_add(self.trunk_br.br_name)
         # Check no resources are left behind.
         self.assertFalse(self.trunk_br.exists())
         self.assertFalse(ovsdb_handler.bridge_has_service_port(br_int))
Example #5
0
 def get_connected_subports_for_trunk(self, trunk_id):
     """Return the list of subports present on the trunk bridge."""
     bridge = ovs_lib.OVSBridge(utils.gen_trunk_br_name(trunk_id))
     if not bridge.bridge_exists(bridge.br_name):
         return []
     try:
         ports = bridge.get_ports_attributes(
                         'Interface', columns=['name', 'external_ids'])
         return [
             self.trunk_manager.get_port_uuid_from_external_ids(port)
             for port in ports if is_subport(port['name'])
         ]
     except (RuntimeError, tman.TrunkManagerError) as e:
         LOG.error(_LE("Failed to get subports for bridge %(bridge)s: "
                       "%(err)s"), {'bridge': bridge.br_name, 'err': e})
         return []
 def __init__(self):
     self.filtered_ports = {}
     self.provider_port_cache = set()
     if sg_conf.security_bridge_mapping is None:
         LOG.warning(_LW("Security bridge mapping not configured."))
         return
     secbr_list = (sg_conf.security_bridge_mapping).split(':')
     secbr_name = secbr_list[0]
     secbr_phyname = secbr_list[1]
     self.sg_br = ovs_lib.OVSBridge(secbr_name)
     self.phy_ofport = self.sg_br.get_port_ofport(secbr_phyname)
     self.patch_ofport = self.sg_br.get_port_ofport(
         ovsvapp_const.SEC_TO_INT_PATCH)
     self._defer_apply = False
     if not self.check_ovs_firewall_restart():
         self.setup_base_flows()
Example #7
0
    def _ovs_add_port(self,
                      bridge,
                      device_name,
                      port_id,
                      mac_address,
                      internal=True):
        attrs = [('external_ids', {
            'iface-id': port_id,
            'iface-status': 'active',
            'attached-mac': mac_address
        })]
        if internal:
            attrs.insert(0, ('type', 'internal'))

        ovs = ovs_lib.OVSBridge(bridge)
        ovs.replace_port(device_name, *attrs)
Example #8
0
    def _switch_firewall(self, firewall_driver):
        """Switch firewall_driver to given driver and restart the agent."""
        l2_agent = self.environment.hosts[0].l2_agent
        l2_agent_config = l2_agent.agent_cfg_fixture.config
        l2_agent_config['securitygroup']['firewall_driver'] = firewall_driver
        l2_agent.agent_cfg_fixture.write_config_to_configfile()
        l2_agent.restart()

        int_bridge = ovs_lib.OVSBridge(
            l2_agent_config['ovs']['integration_bridge'])
        predicate = functools.partial(ovs_iptables.is_bridge_cleaned,
                                      int_bridge)
        utils.wait_until_true(
            predicate,
            exception=RuntimeError("Bridge %s hasn't been marked as clean." %
                                   int_bridge.br_name))
Example #9
0
    def handle_trunk_add(self, bridge_name):
        """Create trunk bridge based on parent port ID.

        This method is decorated with a lock that prevents processing deletion
        while creation hasn't been finished yet. It's based on the bridge name
        so we can keep processing other bridges in parallel.

        :param bridge_name: Name of the created trunk bridge.
        """
        # Wait for the VM's port, i.e. the trunk parent port, to show up.
        # If the VM fails to show up, i.e. this fails with a timeout,
        # then we clean the dangling bridge.
        bridge = ovs_lib.OVSBridge(bridge_name)
        bridge_has_port_predicate = functools.partial(bridge_has_instance_port,
                                                      bridge)
        try:
            common_utils.wait_until_true(bridge_has_port_predicate,
                                         timeout=WAIT_FOR_PORT_TIMEOUT)
        except eventlet.TimeoutError:
            LOG.error(
                _LE('No port appeared on trunk bridge %(br_name)s '
                    'in %(timeout)d seconds. Cleaning up the bridge'), {
                        'br_name': bridge.br_name,
                        'timeout': WAIT_FOR_PORT_TIMEOUT
                    })
            bridge.destroy()
            return

        # Once we get hold of the trunk parent port, we can provision
        # the OVS dataplane for the trunk.
        try:
            self._wire_trunk(bridge, self._get_parent_port(bridge))
        except oslo_messaging.MessagingException as e:
            LOG.error(
                _LE("Got messaging error while processing trunk bridge "
                    "%(bridge_name)s: %(err)s"), {
                        'bridge_name': bridge.br_name,
                        'err': e
                    })
        except RuntimeError as e:
            LOG.error(
                _LE("Failed to get parent port for bridge "
                    "%(bridge_name)s: %(err)s"), {
                        'bridge_name': bridge.br_name,
                        'err': e
                    })
Example #10
0
    def unplug(self, device_name, bridge=None, namespace=None, prefix=None):
        """Unplug the interface."""
        if not bridge:
            bridge = self.conf.ovs_integration_bridge

        tap_name = self._get_tap_name(device_name, prefix)
        self.check_bridge_exists(bridge)
        ovs = ovs_lib.OVSBridge(bridge)

        try:
            ovs.delete_port(tap_name)
            if self.conf.ovs_use_veth:
                device = ip_lib.IPDevice(device_name, namespace=namespace)
                device.link.delete()
                LOG.debug("Unplugged interface '%s'", device_name)
        except RuntimeError:
            LOG.error("Failed unplugging interface '%s'", device_name)
Example #11
0
        def __init__(self):
            self._filtered_ports = {}
            self._int_br = ovs_lib.OVSBridge(cfg.CONF.OVS.integration_bridge)
            self._int_br_not_deferred = self._int_br
            self._deferred = False

            # List of security group rules for ports residing on this host
            self.sg_rules = {}

            # List of security group member ips for ports residing on this
            # host
            self.sg_members = collections.defaultdict(
                lambda: collections.defaultdict(list))
            self.pre_sg_members = None

            # Known ports managed.
            self.known_in_port_for_device = {}
Example #12
0
def unplug_device(conf, device):
    orig_log_fail_as_error = device.get_log_fail_as_error()
    device.set_log_fail_as_error(False)
    try:
        device.link.delete()
    except RuntimeError:
        device.set_log_fail_as_error(orig_log_fail_as_error)
        # Maybe the device is OVS port, so try to delete
        ovs = ovs_lib.BaseOVS()
        bridge_name = ovs.get_bridge_for_iface(device.name)
        if bridge_name:
            bridge = ovs_lib.OVSBridge(bridge_name)
            bridge.delete_port(device.name)
        else:
            LOG.debug('Unable to find bridge for device: %s', device.name)
    finally:
        device.set_log_fail_as_error(orig_log_fail_as_error)
Example #13
0
    def handle_trunk_add(self, bridge_name):
        """Create trunk bridge based on parent port ID.

        This method is decorated with a lock that prevents processing deletion
        while creation hasn't been finished yet. It's based on the bridge name
        so we can keep processing other bridges in parallel.

        :param bridge_name: Name of the created trunk bridge.
        """
        bridge = ovs_lib.OVSBridge(bridge_name)
        # Handle condition when there was bridge in both added and removed
        # events and handle_trunk_remove greenthread was executed before
        # handle_trunk_add
        if not bridge.bridge_exists(bridge_name):
            LOG.debug("The bridge %s was deleted before it was handled.",
                      bridge_name)
            return

        # Determine the state of the trunk bridge by looking for the VM's port,
        # i.e. the trunk parent port and/or patch ports to be present. If the
        # VM is absent, then we clean the dangling bridge. If the VM is present
        # the value of 'rewire' tells us whether or not the bridge was dealt
        # with in a previous added event, and thus it has active patch ports.
        if not self._is_vm_connected(bridge):
            LOG.debug("No instance port associated to bridge %s could be "
                      "found. Deleting bridge and its resources.", bridge_name)
            self.trunk_manager.dispose_trunk(bridge)
            return

        # Check if the trunk was provisioned in a previous run. This can happen
        # at agent startup when existing trunks are notified as added events.
        rewire = bridge_has_service_port(bridge)
        # Once we get hold of the trunk parent port, we can provision
        # the OVS dataplane for the trunk.
        try:
            self._wire_trunk(bridge, self._get_parent_port(bridge), rewire)
        except oslo_messaging.MessagingException as e:
            LOG.error(_LE("Got messaging error while processing trunk bridge "
                          "%(bridge_name)s: %(err)s"),
                      {'bridge_name': bridge.br_name,
                       'err': e})
        except exceptions.ParentPortNotFound as e:
            LOG.error(_LE("Failed to get parent port for bridge "
                          "%(bridge_name)s: %(err)s"),
                      {'bridge_name': bridge.br_name,
                       'err': e})
Example #14
0
def keepalived_ipv6_supported():
    """Check if keepalived supports IPv6 functionality.

    Validation is done as follows.
    1. Create a namespace.
    2. Create OVS bridge with two ports (ha_port and gw_port)
    3. Move the ovs ports to the namespace.
    4. Spawn keepalived process inside the namespace with IPv6 configuration.
    5. Verify if IPv6 address is assigned to gw_port.
    6. Verify if IPv6 default route is configured by keepalived.
    """

    random_str = utils.get_random_string(6)
    br_name = "ka-test-" + random_str
    ha_port = ha_router.HA_DEV_PREFIX + random_str
    gw_port = namespaces.INTERNAL_DEV_PREFIX + random_str
    gw_vip = 'fdf8:f53b:82e4::10/64'
    expected_default_gw = 'fe80:f816::1'

    with ovs_lib.OVSBridge(br_name) as br:
        with KeepalivedIPv6Test(ha_port, gw_port, gw_vip,
                                expected_default_gw) as ka:
            br.add_port(ha_port, ('type', 'internal'))
            br.add_port(gw_port, ('type', 'internal'))

            ha_dev = ip_lib.IPDevice(ha_port)
            gw_dev = ip_lib.IPDevice(gw_port)

            ha_dev.link.set_netns(ka.nsname)
            gw_dev.link.set_netns(ka.nsname)

            ha_dev.link.set_up()
            gw_dev.link.set_up()

            ka.configure()

            ka.start_keepalived_process()

            ka.verify_ipv6_address_assignment(gw_dev)

            default_gw = gw_dev.route.get_gateway(ip_version=6)
            if default_gw:
                default_gw = default_gw['gateway']

    return expected_default_gw == default_gw
Example #15
0
    def handle_trunk_remove(self, bridge_name, port):
        """Remove wiring between trunk bridge and integration bridge.

        The method calls into trunk manager to remove patch ports on
        integration bridge side and to delete the trunk bridge. It's decorated
        with a lock to prevent deletion of bridge while creation is still in
        process.

        :param bridge_name: Name of the bridge used for locking purposes.
        :param port: Parent port dict.
        """
        # TODO(njohnston): In the case of DPDK with trunk ports, if nova
        # deletes an interface and then re-adds it we can get a race
        # condition where the port is re-added and then the bridge is
        # deleted because we did not properly catch the re-addition.  To
        # solve this would require transitioning to ordered event
        # resolution, like the L3 agent does with the
        # ResourceProcessingQueue class.  Until we can make that happen, we
        # try to mitigate the issue by checking if there is a port on the
        # bridge and if so then do not remove it.
        bridge = ovs_lib.OVSBridge(bridge_name)
        time.sleep(WAIT_BEFORE_TRUNK_DELETE)
        if bridge_has_instance_port(bridge):
            LOG.debug(
                "The bridge %s has instances attached so it will not "
                "be deleted.", bridge_name)
            return
        try:
            # TODO(jlibosva): Investigate how to proceed during removal of
            # trunk bridge that doesn't have metadata stored.
            parent_port_id, trunk_id, subport_ids = self._get_trunk_metadata(
                port)
            # NOTE(status_police): we do not report changes in trunk status on
            # removal to avoid potential races between agents in case the event
            # is due to a live migration or reassociation of a trunk to a new
            # VM.
            self.unwire_subports_for_trunk(trunk_id, subport_ids)
            self.trunk_manager.remove_trunk(trunk_id, parent_port_id)
        except tman.TrunkManagerError as te:
            LOG.error("Removing trunk %(trunk_id)s failed: %(err)s", {
                'trunk_id': port['external_ids']['trunk_id'],
                'err': te
            })
        else:
            LOG.debug("Deleted resources associated to trunk: %s", trunk_id)
Example #16
0
 def test_bridge_lifecycle_ovsbridge(self):
     name = six.text_type(utils.get_rand_name(prefix=net_helpers.BR_PREFIX))
     mac_table_size = 12345
     cfg.CONF.set_override('bridge_mac_table_size', mac_table_size)
     br = ovs_lib.OVSBridge(name)
     self.assertEqual(br.br_name, name)
     # Make sure that instantiating an OVSBridge does not actually create
     self.assertFalse(self.ovs.bridge_exists(name))
     self.addCleanup(self.ovs.delete_bridge, name)
     br.create()
     self.assertTrue(self.ovs.bridge_exists(name))
     br_other_config = self.ovs.ovsdb.db_find(
         'Bridge', ('name', '=', name),
         columns=['other_config']).execute()[0]['other_config']
     self.assertEqual(str(mac_table_size),
                      br_other_config['mac-table-size'])
     br.destroy()
     self.assertFalse(self.ovs.bridge_exists(name))
Example #17
0
    def _update_trunk_metadata(self, trunk_bridge, port,
                               trunk_id, subport_ids, wire=True):
        """Update trunk metadata.

        :param trunk_bridge: OVS trunk bridge.
        :param port: OVS parent port.
        :param trunk_id: trunk ID.
        :param subport_ids: subports affecting the metadata.
        :param wire: if True subport_ids are added, otherwise removed.
        """
        trunk_bridge = trunk_bridge or ovs_lib.OVSBridge(
            utils.gen_trunk_br_name(trunk_id))
        port = port or self._get_parent_port(trunk_bridge)
        _port_id, _trunk_id, old_subports = self._get_trunk_metadata(port)
        if wire:
            new_subports = set(old_subports) | set(subport_ids)
        else:
            new_subports = set(old_subports) - set(subport_ids)
        self._set_trunk_metadata(trunk_bridge, port, trunk_id, new_subports)
Example #18
0
 def plug(self, network, port, interface_name):
     mac_address = (cfg.CONF.dhcp_override_mac
                    if cfg.CONF.dhcp_override_mac
                    else port.mac_address)
     self.driver.plug(network.id,
                      port.id,
                      interface_name,
                      mac_address,
                      namespace=network.namespace,
                      mtu=network.get('mtu'),
                      bridge=cfg.CONF.dvs_integration_bridge)
     vlan_tag = getattr(network, 'provider:segmentation_id',
                        None)
     # Treat vlans
     if vlan_tag and vlan_tag != 0:
         br_dvs = ovs_lib.OVSBridge(self.conf.dvs_integration_bridge)
         # When ovs_use_veth is set to True, the DEV_NAME_PREFIX
         # will be changed from 'tap' to 'ns-' in
         # OVSInterfaceDriver
         dvs_port_name = interface_name.replace('ns-', 'tap')
         br_dvs.set_db_attribute("Port", dvs_port_name, "tag", vlan_tag)
Example #19
0
def main():
    """Main method for cleaning up OVS bridges.

    The utility cleans up the integration bridges used by Neutron.
    """

    conf = setup_conf()
    conf()
    config.setup_logging()

    configuration_bridges = set([conf.ovs_integration_bridge,
                                 conf.external_network_bridge])
    ovs = ovs_lib.BaseOVS()
    ovs_bridges = set(ovs.get_bridges())
    available_configuration_bridges = configuration_bridges & ovs_bridges

    if conf.ovs_all_ports:
        bridges = ovs_bridges
    else:
        bridges = available_configuration_bridges

    # Collect existing ports created by Neutron on configuration bridges.
    # After deleting ports from OVS bridges, we cannot determine which
    # ports were created by Neutron, so port information is collected now.
    ports = collect_neutron_ports(available_configuration_bridges)

    for bridge in bridges:
        LOG.info("Cleaning bridge: %s", bridge)
        ovs = ovs_lib.OVSBridge(bridge)
        if conf.ovs_all_ports:
            port_names = ovs.get_port_name_list()
        else:
            port_names = get_bridge_deletable_ports(ovs)
        for port_name in port_names:
            ovs.delete_port(port_name)

    # Remove remaining ports created by Neutron (usually veth pair)
    delete_neutron_ports(ports)

    LOG.info("OVS cleanup completed successfully")
Example #20
0
    def __init__(self, integ_br, polling_interval):
        '''Constructor.

        :param integ_br: name of the integration bridge.
        :param polling_interval: interval (secs) to check the bridge.
        '''
        self.int_br = ovs_lib.OVSBridge(integ_br)
        self.polling_interval = polling_interval
        self.cur_ports = []
        self.need_sync = True

        self.datapath_id = "0x%s" % self.int_br.get_datapath_id()

        self.agent_state = {
            'binary': 'neutron-nec-agent',
            'host': cfg.CONF.host,
            'topic': q_const.L2_AGENT_TOPIC,
            'configurations': {},
            'agent_type': q_const.AGENT_TYPE_NEC,
            'start_flag': True}

        self.setup_rpc()
Example #21
0
    def __init__(self, integ_br, polling_interval, vs='ovs'):
        super(RestProxyAgent, self).__init__()
        self.polling_interval = polling_interval
        if vs == 'ivs':
            self.int_br = IVSBridge()
            self.agent_type = "BSN IVS Agent"
        elif vs == "nfvswitch":
            self.int_br = NFVSwitchBridge()
            self.agent_type = "BSN NFVSwitch Agent"
        else:
            self.int_br = ovs_lib.OVSBridge(integ_br)
            self.agent_type = "OVS Agent"
        self.agent_state = {
            'binary': 'neutron-bsn-agent',
            'host': cfg.CONF.host,
            'topic': q_const.L2_AGENT_TOPIC,
            'configurations': {},
            'agent_type': self.agent_type,
            'start_flag': True}
        self.use_call = True

        self._setup_rpc()
        self.sg_agent = FilterDeviceIDMixin(self.context, self.sg_plugin_rpc)
Example #22
0
def ofctl_arg_supported(cmd, **kwargs):
    """Verify if ovs-ofctl binary supports cmd with **kwargs.

    :param cmd: ovs-ofctl command to use for test.
    :param **kwargs: arguments to test with the command.
    :returns: a boolean if the supplied arguments are supported.
    """
    br_name = 'br-test-%s' % utils.get_random_string(6)
    with ovs_lib.OVSBridge(br_name) as test_br:
        full_args = ["ovs-ofctl", cmd, test_br.br_name,
                     ovs_lib._build_flow_expr_str(kwargs, cmd.split('-')[0])]
        try:
            agent_utils.execute(full_args, run_as_root=True)
        except RuntimeError as e:
            LOG.debug("Exception while checking supported feature via "
                      "command %s. Exception: %s", full_args, e)
            return False
        except Exception:
            LOG.exception(_LE("Unexpected exception while checking supported"
                              " feature via command: %s"), full_args)
            return False
        else:
            return True
Example #23
0
def do_main(conf):
    configuration_bridges = set(
        [conf.ovs_integration_bridge, conf.external_network_bridge])
    ovs = ovs_lib.BaseOVS()
    ovs_bridges = set(ovs.get_bridges())
    available_configuration_bridges = configuration_bridges & ovs_bridges

    if conf.ovs_all_ports:
        bridges = ovs_bridges
    else:
        bridges = available_configuration_bridges

    try:
        # The ovs_cleanup method not added to the deprecated vsctl backend
        for bridge in bridges:
            LOG.info("Cleaning bridge: %s", bridge)
            ovs.ovsdb.ovs_cleanup(bridge,
                                  conf.ovs_all_ports).execute(check_error=True)
    except AttributeError:
        # Collect existing ports created by Neutron on configuration bridges.
        # After deleting ports from OVS bridges, we cannot determine which
        # ports were created by Neutron, so port information is collected now.
        ports = collect_neutron_ports(available_configuration_bridges)

        for bridge in bridges:
            LOG.info("Cleaning bridge: %s", bridge)
            ovs = ovs_lib.OVSBridge(bridge)
            if conf.ovs_all_ports:
                port_names = ovs.get_port_name_list()
            else:
                port_names = get_bridge_deletable_ports(ovs)
            for port_name in port_names:
                ovs.delete_port(port_name)
        # Remove remaining ports created by Neutron (usually veth pair)
        delete_neutron_ports(ports)

    LOG.info("OVS cleanup completed successfully")
Example #24
0
 def remove_vlan_tag(self, bridge, interface):
     ovs = ovs_lib.OVSBridge(bridge)
     ovs.clear_db_attribute("Port", interface, "tag")
Example #25
0
    def plug_new(self,
                 network_id,
                 port_id,
                 device_name,
                 mac_address,
                 bridge=None,
                 namespace=None,
                 prefix=None,
                 mtu=None):
        """Plug in the interface."""
        if not bridge:
            bridge = self.conf.ovs_integration_bridge

        self.check_bridge_exists(bridge)

        ip = ip_lib.IPWrapper()
        tap_name = self._get_tap_name(device_name, prefix)

        if self.conf.ovs_use_veth:
            # Create ns_dev in a namespace if one is configured.
            root_dev, ns_dev = ip.add_veth(tap_name,
                                           device_name,
                                           namespace2=namespace)
            root_dev.disable_ipv6()
        else:
            ns_dev = ip.device(device_name)

        internal = not self.conf.ovs_use_veth
        self._ovs_add_port(bridge,
                           tap_name,
                           port_id,
                           mac_address,
                           internal=internal)
        for i in range(9):
            # workaround for the OVS shy port syndrome. ports sometimes
            # hide for a bit right after they are first created.
            # see bug/1618987
            try:
                ns_dev.link.set_address(mac_address)
                break
            except RuntimeError as e:
                LOG.warning("Got error trying to set mac, retrying: %s",
                            str(e))
                time.sleep(1)
        else:
            # didn't break, we give it one last shot without catching
            ns_dev.link.set_address(mac_address)

        # Add an interface created by ovs to the namespace.
        if not self.conf.ovs_use_veth and namespace:
            try:
                namespace_obj = ip.ensure_namespace(namespace)
                namespace_obj.add_device_to_namespace(ns_dev)
            except exceptions.ProcessExecutionError:
                # To prevent the namespace failure from blasting
                # ovs, the ovs port created should be reverted
                # When the namespace is corrupted, the ProcessExecutionError
                # has execption message as:
                # Exit code: 2; Stdin: ; Stdout: ; Stderr: RTNETLINK
                # answers: Invalid argument
                LOG.warning(
                    "Failed to plug interface %s into bridge %s, "
                    "cleaning up", device_name, bridge)
                with excutils.save_and_reraise_exception():
                    ovs = ovs_lib.OVSBridge(bridge)
                    ovs.delete_port(tap_name)

        # NOTE(ihrachys): the order here is significant: we must set MTU after
        # the device is moved into a namespace, otherwise OVS bridge does not
        # allow to set MTU that is higher than the least of all device MTUs on
        # the bridge
        if mtu:
            self.set_mtu(device_name, mtu, namespace=namespace, prefix=prefix)
        else:
            LOG.warning("No MTU configured for port %s", port_id)

        ns_dev.link.set_up()
        if self.conf.ovs_use_veth:
            root_dev.link.set_up()
Example #26
0
 def test_non_default_datapath(self):
     expected = p_const.OVS_DATAPATH_NETDEV
     self.br = ovs_lib.OVSBridge(self.BR_NAME, datapath_type=expected)
     br2 = self.br.add_bridge('another-br', datapath_type=expected)
     self.assertEqual(expected, self.br.datapath_type)
     self.assertEqual(expected, br2.datapath_type)
Example #27
0
 def test_default_cookie(self):
     self.br = ovs_lib.OVSBridge("br-tun")
     uuid_stamp1 = self.br.default_cookie
     self.assertEqual(uuid_stamp1, self.br.default_cookie)
Example #28
0
 def assert_ovs_bridge_empty(bridge_name):
     bridge = ovs_lib.OVSBridge(bridge_name)
     self.assertFalse(bridge.get_port_name_list())
Example #29
0
def get_ovs_bridge(br_name):
    return ovs_lib.OVSBridge(br_name)
Example #30
0
def patch_supported():
    name, peer_name, patch_name = common_utils.get_related_rand_device_names(
        ['patchtest-', 'peertest0-', 'peertest1-'])
    with ovs_lib.OVSBridge(name) as br:
        port = br.add_patch_port(patch_name, peer_name)
        return port != ovs_lib.INVALID_OFPORT