def add_tap_interface(self, network_id, vlan_id, tap_device_name):
        """
        If a VIF has been plugged into a network, this function will
        add the corresponding tap device to the relevant bridge
        """
        if not tap_device_name:
            return False

        if not self.device_exists(tap_device_name):
            LOG.debug("Tap device: %s does not exist on this host, skipped" %
                      tap_device_name)
            return False

        current_bridge_name = self.get_bridge_for_tap_device(tap_device_name)
        bridge_name = self.get_bridge_name(network_id)
        if bridge_name == current_bridge_name:
            return False
        LOG.debug("Adding device %s to bridge %s" % (tap_device_name,
                                                     bridge_name))
        if current_bridge_name:
            if utils.execute(['brctl', 'delif', current_bridge_name,
                              tap_device_name], root_helper=self.root_helper):
                return False

        self.ensure_vlan_bridge(network_id, vlan_id)
        if utils.execute(['brctl', 'addif', bridge_name, tap_device_name],
                         root_helper=self.root_helper):
            return False
        LOG.debug("Done adding device %s to bridge %s" % (tap_device_name,
                                                          bridge_name))
        return True
示例#2
0
    def external_gateway_added(self, ri, ex_gw_port, internal_cidrs):

        interface_name = self.get_external_device_name(ex_gw_port['id'])
        ex_gw_ip = ex_gw_port['fixed_ips'][0]['ip_address']
        if not ip_lib.device_exists(interface_name,
                                    root_helper=self.root_helper,
                                    namespace=ri.ns_name()):
            self.driver.plug(ex_gw_port['network_id'],
                             ex_gw_port['id'],
                             interface_name,
                             ex_gw_port['mac_address'],
                             bridge=self.conf.external_network_bridge,
                             namespace=ri.ns_name(),
                             prefix=EXTERNAL_DEV_PREFIX)
        self.driver.init_l3(interface_name, [ex_gw_port['ip_cidr']],
                            namespace=ri.ns_name())
        ip_address = ex_gw_port['ip_cidr'].split('/')[0]
        self._send_gratuitous_arp_packet(ri, interface_name, ip_address)

        gw_ip = ex_gw_port['subnet']['gateway_ip']
        if ex_gw_port['subnet']['gateway_ip']:
            cmd = ['route', 'add', 'default', 'gw', gw_ip]
            if self.conf.use_namespaces:
                ip_wrapper = ip_lib.IPWrapper(self.root_helper,
                                              namespace=ri.ns_name())
                ip_wrapper.netns.execute(cmd, check_exit_code=False)
            else:
                utils.execute(cmd,
                              check_exit_code=False,
                              root_helper=self.root_helper)

        for (c, r) in self.external_gateway_nat_rules(ex_gw_ip, internal_cidrs,
                                                      interface_name):
            ri.iptables_manager.ipv4['nat'].add_rule(c, r)
        ri.iptables_manager.apply()
 def ensure_vxlan(self, network_id, physical_interface, vlan_id):
     """Create a vxlan unless it already exists."""
     interface = self.get_vxlan_device_name(network_id)
     if not self.device_exists(interface):
         LOG.debug(_("Creating vxlan interface %(interface)s for "
                     "VLAN %(vlan_id)s on interface "
                     "%(physical_interface)s"),
                   locals())
         cmd = ['ip', 'link', 'add', interface, 'type', 'vxlan',
                'id', vlan_id, 'dev', physical_interface,
                'group', cfg.CONF.VXLAN.vxlan_group]
         if cfg.CONF.VXLAN.vxlan_ttl is not None:
             cmd.extend(['ttl', cfg.CONF.VXLAN.vxlan_ttl])
         if cfg.CONF.VXLAN.vxlan_tos is not None:
             cmd.extend(['tos', cfg.CONF.VXLAN.vxlan_tos])
         if len(cfg.CONF.VXLAN.vxlan_port) == 2:
             cmd.extend(['port', cfg.CONF.VXLAN.vxlan_port[0],
                         cfg.CONF.VXLAN.vxlan_port[1]])
         else:
             LOG.error(_("Wrong vxlan_port value: %s !"),
                         ",".join(cfg.CONF.VXLAN.vxlan_port))
         if len(cfg.CONF.VXLAN.vxlan_local_ip):
             cmd.extend(['local', cfg.CONF.VXLAN.vxlan_local_ip])
         if utils.execute(cmd, root_helper=self.root_helper):
             return
         if utils.execute(['ip', 'link', 'set',
                           interface, 'up'], root_helper=self.root_helper):
             return
         LOG.debug(_("Done creating vxlan interface %s"), interface)
     return interface
示例#4
0
    def delete_vlan_bridge(self, bridge_name):
        if self.device_exists(bridge_name):
            interfaces_on_bridge = self.get_interfaces_on_bridge(bridge_name)
            for interface in interfaces_on_bridge:
                self.remove_interface(bridge_name, interface)
                for physical_interface in self.interface_mappings.itervalues():
                    if physical_interface == interface:
                        # This is a flat network => return IP's from bridge to
                        # interface
                        ips, gateway = self.get_interface_details(bridge_name)
                        self.update_interface_ip_details(interface,
                                                         bridge_name,
                                                         ips, gateway)
                    else:
                        if interface.startswith(physical_interface):
                            self.delete_vlan(interface)

            LOG.debug("Deleting bridge %s" % bridge_name)
            if utils.execute(['ip', 'link', 'set', bridge_name, 'down'],
                             root_helper=self.root_helper):
                return
            if utils.execute(['brctl', 'delbr', bridge_name],
                             root_helper=self.root_helper):
                return
            LOG.debug("Done deleting bridge %s" % bridge_name)

        else:
            LOG.error("Cannot delete bridge %s, does not exist" % bridge_name)
示例#5
0
    def disable(self, retain_port=False):
        """Disable DHCP for this network by killing the local process."""
        pid = self.pid

        if self.active:
            cmd = ['kill', '-9', pid]
            if self.namespace:
                ip_wrapper = ip_lib.IPWrapper(self.root_helper, self.namespace)
                ip_wrapper.netns.execute(cmd)
            else:
                utils.execute(cmd, self.root_helper)

            if not retain_port:
                self.device_delegate.destroy(self.network, self.interface_name)

        elif pid:
            LOG.debug(
                _('DHCP for %(net_id)s pid %(pid)d is stale, ignoring '
                  'command'), {
                      'net_id': self.network.id,
                      'pid': pid
                  })
        else:
            LOG.debug(_('No DHCP started for %s'), self.network.id)

        self._remove_config_files()
示例#6
0
 def test_clear_db_attribute(self):
     pname = "tap77"
     utils.execute(["ovs-vsctl", self.TO, "clear", "Port", pname, "tag"],
                   root_helper=self.root_helper)
     self.mox.ReplayAll()
     self.br.clear_db_attribute("Port", pname, "tag")
     self.mox.VerifyAll()
    def add_tap_interface(self, network_id, vlan_id, tap_device_name):
        """
        If a VIF has been plugged into a network, this function will
        add the corresponding tap device to the relevant bridge
        """
        if not tap_device_name:
            return False

        if not self.device_exists(tap_device_name):
            LOG.debug("Tap device: %s does not exist on this host, skipped" %
                      tap_device_name)
            return False

        current_bridge_name = self.get_bridge_for_tap_device(tap_device_name)
        bridge_name = self.get_bridge_name(network_id)
        if bridge_name == current_bridge_name:
            return False
        LOG.debug("Adding device %s to bridge %s" %
                  (tap_device_name, bridge_name))
        if current_bridge_name:
            if utils.execute(
                ['brctl', 'delif', current_bridge_name, tap_device_name],
                    root_helper=self.root_helper):
                return False

        self.ensure_vlan_bridge(network_id, vlan_id)
        if utils.execute(['brctl', 'addif', bridge_name, tap_device_name],
                         root_helper=self.root_helper):
            return False
        LOG.debug("Done adding device %s to bridge %s" %
                  (tap_device_name, bridge_name))
        return True
示例#8
0
    def external_gateway_added(self, ri, ex_gw_port, internal_cidrs):

        interface_name = self.get_external_device_name(ex_gw_port['id'])
        ex_gw_ip = ex_gw_port['fixed_ips'][0]['ip_address']
        if not ip_lib.device_exists(interface_name,
                                    root_helper=self.root_helper,
                                    namespace=ri.ns_name()):
            self.driver.plug(ex_gw_port['network_id'],
                             ex_gw_port['id'], interface_name,
                             ex_gw_port['mac_address'],
                             bridge=self.conf.external_network_bridge,
                             namespace=ri.ns_name(),
                             prefix=EXTERNAL_DEV_PREFIX)
        self.driver.init_l3(interface_name, [ex_gw_port['ip_cidr']],
                            namespace=ri.ns_name())
        ip_address = ex_gw_port['ip_cidr'].split('/')[0]
        self._send_gratuitous_arp_packet(ri, interface_name, ip_address)

        gw_ip = ex_gw_port['subnet']['gateway_ip']
        if ex_gw_port['subnet']['gateway_ip']:
            cmd = ['route', 'add', 'default', 'gw', gw_ip]
            if self.conf.use_namespaces:
                ip_wrapper = ip_lib.IPWrapper(self.root_helper,
                                              namespace=ri.ns_name())
                ip_wrapper.netns.execute(cmd, check_exit_code=False)
            else:
                utils.execute(cmd, check_exit_code=False,
                              root_helper=self.root_helper)

        for (c, r) in self.external_gateway_nat_rules(ex_gw_ip,
                                                      internal_cidrs,
                                                      interface_name):
            ri.iptables_manager.ipv4['nat'].add_rule(c, r)
        ri.iptables_manager.apply()
示例#9
0
    def _test_get_vif_port_set(self, is_xen):
        utils.execute(["ovs-vsctl", self.TO, "list-ports", self.BR_NAME],
                      root_helper=self.root_helper).AndReturn('tap99\ntun22')

        if is_xen:
            id_key = 'xs-vif-uuid'
        else:
            id_key = 'iface-id'

        headings = ['name', 'external_ids']
        data = [
            # A vif port on this bridge:
            ['tap99', {id_key: 'tap99id', 'attached-mac': 'tap99mac'}],
            # A vif port on another bridge:
            ['tap88', {id_key: 'tap88id', 'attached-mac': 'tap88id'}],
            # Non-vif port on this bridge:
            ['tun22', {}],
        ]

        utils.execute(["ovs-vsctl", self.TO, "--format=json",
                       "--", "--columns=name,external_ids",
                       "list", "Interface"],
                      root_helper=self.root_helper).AndReturn(
                          self._encode_ovs_json(headings, data))

        if is_xen:
            self.mox.StubOutWithMock(self.br, 'get_xapi_iface_id')
            self.br.get_xapi_iface_id('tap99id').AndReturn('tap99id')

        self.mox.ReplayAll()

        port_set = self.br.get_vif_port_set()
        self.assertEqual(set(['tap99id']), port_set)
        self.mox.VerifyAll()
示例#10
0
    def spawn_process(self):
        """Spawns a Dnsmasq process for the network."""
        env = {
            self.QUANTUM_NETWORK_ID_KEY: self.network.id,
            self.QUANTUM_RELAY_SOCKET_PATH_KEY:
            self.conf.dhcp_lease_relay_socket
        }

        cmd = [
            'dnsmasq',
            '--no-hosts',
            '--no-resolv',
            '--strict-order',
            '--bind-interfaces',
            '--interface=%s' % self.interface_name,
            '--except-interface=lo',
            '--pid-file=%s' % self.get_conf_file_name(
                'pid', ensure_conf_dir=True),
            #TODO (mark): calculate value from cidr (defaults to 150)
            #'--dhcp-lease-max=%s' % ?,
            '--dhcp-hostsfile=%s' % self._output_hosts_file(),
            '--dhcp-optsfile=%s' % self._output_opts_file(),
            '--dhcp-script=%s' % self._lease_relay_script_path(),
            '--leasefile-ro',
        ]

        for i, subnet in enumerate(self.network.subnets):
            # if a subnet is specified to have dhcp disabled
            if not subnet.enable_dhcp:
                continue
            if subnet.ip_version == 4:
                mode = 'static'
            else:
                # TODO (mark): how do we indicate other options
                # ra-only, slaac, ra-nameservers, and ra-stateless.
                mode = 'static'
            if self.version >= self.MINIMUM_VERSION:
                set_tag = 'set:'
            else:
                set_tag = ''
            cmd.append('--dhcp-range=%s%s,%s,%s,%ss' %
                       (set_tag, self._TAG_PREFIX % i,
                        netaddr.IPNetwork(subnet.cidr).network,
                        mode,
                        self.conf.dhcp_lease_time))

        cmd.append('--conf-file=%s' % self.conf.dnsmasq_config_file)
        if self.conf.dnsmasq_dns_server:
            cmd.append('--server=%s' % self.conf.dnsmasq_dns_server)

        if self.conf.dhcp_domain:
            cmd.append('--domain=%s' % self.conf.dhcp_domain)

        if self.namespace:
            ip_wrapper = ip_lib.IPWrapper(self.root_helper, self.namespace)
            ip_wrapper.netns.execute(cmd, addl_env=env)
        else:
            # For normal sudo prepend the env vars before command
            cmd = ['%s=%s' % pair for pair in env.items()] + cmd
            utils.execute(cmd, self.root_helper)
 def ensure_vlan(self, vlan_id):
     """Create a vlan unless it already exists."""
     interface = self.get_subinterface_name(vlan_id)
     if not self.device_exists(interface):
         LOG.debug(
             "Creating subinterface %s for VLAN %s on interface %s" % (interface, vlan_id, self.physical_interface)
         )
         if utils.execute(
             [
                 "ip",
                 "link",
                 "add",
                 "link",
                 self.physical_interface,
                 "name",
                 interface,
                 "type",
                 "vlan",
                 "id",
                 vlan_id,
             ],
             root_helper=self.root_helper,
         ):
             return
         if utils.execute(["ip", "link", "set", interface, "up"], root_helper=self.root_helper):
             return
         LOG.debug("Done creating subinterface %s" % interface)
     return interface
 def device_exists(self, device):
     """Check if ethernet device exists."""
     try:
         utils.execute(["ip", "link", "show", "dev", device], root_helper=self.root_helper)
     except RuntimeError:
         return False
     return True
示例#13
0
    def plug(self, network_id, port_id, device_name, mac_address):
        """Plug in the interface."""
        bridge = self.conf.ovs_integration_bridge

        self.check_bridge_exists(bridge)

        if not ip_lib.device_exists(device_name,
                                    self.conf.root_helper,
                                    namespace=network_id):

            utils.execute(['ovs-vsctl',
                           '--', '--may-exist', 'add-port', bridge,
                           device_name,
                           '--', 'set', 'Interface', device_name,
                           'type=internal',
                           '--', 'set', 'Interface', device_name,
                           'external-ids:iface-id=%s' % port_id,
                           '--', 'set', 'Interface', device_name,
                           'external-ids:iface-status=active',
                           '--', 'set', 'Interface', device_name,
                           'external-ids:attached-mac=%s' %
                           mac_address],
                          self.conf.root_helper)

            ip = ip_lib.IPWrapper(self.conf.root_helper)
            device = ip.device(device_name)
            device.link.set_address(mac_address)
            if self.conf.network_device_mtu:
                device.link.set_mtu(self.conf.network_device_mtu)

            namespace = ip.ensure_namespace(network_id)
            namespace.add_device_to_namespace(device)
            device.link.set_up()
        else:
            LOG.error(_('Device %s already exists') % device)
示例#14
0
 def test_clear_db_attribute(self):
     pname = "tap77"
     utils.execute(["ovs-vsctl", self.TO, "clear", "Port",
                    pname, "tag"], root_helper=self.root_helper)
     self.mox.ReplayAll()
     self.br.clear_db_attribute("Port", pname, "tag")
     self.mox.VerifyAll()
示例#15
0
    def delete_vlan_bridge(self, bridge_name):
        if self.device_exists(bridge_name):
            interfaces_on_bridge = self.get_interfaces_on_bridge(bridge_name)
            for interface in interfaces_on_bridge:
                self.remove_interface(bridge_name, interface)
                for physical_interface in self.interface_mappings.itervalues():
                    if physical_interface == interface:
                        # This is a flat network => return IP's from bridge to
                        # interface
                        ips, gateway = self.get_interface_details(bridge_name)
                        self.update_interface_ip_details(
                            interface, bridge_name, ips, gateway)
                    else:
                        if interface.startswith(physical_interface):
                            self.delete_vlan(interface)

            LOG.debug("Deleting bridge %s" % bridge_name)
            if utils.execute(['ip', 'link', 'set', bridge_name, 'down'],
                             root_helper=self.root_helper):
                return
            if utils.execute(['brctl', 'delbr', bridge_name],
                             root_helper=self.root_helper):
                return
            LOG.debug("Done deleting bridge %s" % bridge_name)

        else:
            LOG.error("Cannot delete bridge %s, does not exist" % bridge_name)
示例#16
0
文件: dhcp.py 项目: soheilhy/quantum
    def spawn_process(self):
        """Spawns a Dnsmasq process for the network."""
        env = {
            self.QUANTUM_NETWORK_ID_KEY: self.network.id,
            self.QUANTUM_RELAY_SOCKET_PATH_KEY:
            self.conf.dhcp_lease_relay_socket
        }

        cmd = [
            'dnsmasq',
            '--no-hosts',
            '--no-resolv',
            '--strict-order',
            '--bind-interfaces',
            '--interface=%s' % self.interface_name,
            '--except-interface=lo',
            '--pid-file=%s' %
            self.get_conf_file_name('pid', ensure_conf_dir=True),
            #TODO (mark): calculate value from cidr (defaults to 150)
            #'--dhcp-lease-max=%s' % ?,
            '--dhcp-hostsfile=%s' % self._output_hosts_file(),
            '--dhcp-optsfile=%s' % self._output_opts_file(),
            '--dhcp-script=%s' % self._lease_relay_script_path(),
            '--leasefile-ro',
        ]

        for i, subnet in enumerate(self.network.subnets):
            # if a subnet is specified to have dhcp disabled
            if not subnet.enable_dhcp:
                continue
            if subnet.ip_version == 4:
                mode = 'static'
            else:
                # TODO(mark): how do we indicate other options
                # ra-only, slaac, ra-nameservers, and ra-stateless.
                mode = 'static'
            if self.version >= self.MINIMUM_VERSION:
                set_tag = 'set:'
            else:
                set_tag = ''
            cmd.append(
                '--dhcp-range=%s%s,%s,%s,%ss' %
                (set_tag, self._TAG_PREFIX % i, netaddr.IPNetwork(
                    subnet.cidr).network, mode, self.conf.dhcp_lease_time))

        cmd.append('--conf-file=%s' % self.conf.dnsmasq_config_file)
        if self.conf.dnsmasq_dns_server:
            cmd.append('--server=%s' % self.conf.dnsmasq_dns_server)

        if self.conf.dhcp_domain:
            cmd.append('--domain=%s' % self.conf.dhcp_domain)

        if self.namespace:
            ip_wrapper = ip_lib.IPWrapper(self.root_helper, self.namespace)
            ip_wrapper.netns.execute(cmd, addl_env=env)
        else:
            # For normal sudo prepend the env vars before command
            cmd = ['%s=%s' % pair for pair in env.items()] + cmd
            utils.execute(cmd, self.root_helper)
 def delete_vlan(self, interface):
     if self.device_exists(interface):
         LOG.debug("Deleting subinterface %s for vlan" % interface)
         if utils.execute(["ip", "link", "set", interface, "down"], root_helper=self.root_helper):
             return
         if utils.execute(["ip", "link", "delete", interface], root_helper=self.root_helper):
             return
         LOG.debug("Done deleting subinterface %s" % interface)
示例#18
0
 def device_exists(self, device):
     """Check if ethernet device exists."""
     try:
         utils.execute(['ip', 'link', 'show', 'dev', device],
                       root_helper=self.root_helper)
     except RuntimeError:
         return False
     return True
示例#19
0
 def device_exists(self, device):
     """Check if ethernet device exists."""
     try:
         utils.execute(['ip', 'link', 'show', 'dev', device],
                       root_helper=self.root_helper)
     except RuntimeError:
         return False
     return True
示例#20
0
    def test_count_flows(self):
        utils.execute(["ovs-ofctl", "dump-flows", self.BR_NAME],
                      root_helper=self.root_helper).AndReturn('ignore'
                                                              '\nflow-1\n')
        self.mox.ReplayAll()

        # counts the number of flows as total lines of output - 2
        self.assertEqual(self.br.count_flows(), 1)
        self.mox.VerifyAll()
示例#21
0
def kill_pids_in_file(root_helper, pid_path):
    if os.path.exists(pid_path):
        with open(pid_path, 'r') as pids:
            for pid in pids:
                pid = pid.strip()
                try:
                    utils.execute(['kill', '-9', pid], root_helper)
                except RuntimeError:
                    LOG.exception(_('Unable to kill haproxy process: %s'), pid)
def kill_pids_in_file(root_helper, pid_path):
    if os.path.exists(pid_path):
        with open(pid_path, "r") as pids:
            for pid in pids:
                pid = pid.strip()
                try:
                    utils.execute(["kill", "-9", pid], root_helper)
                except RuntimeError:
                    LOG.exception(_("Unable to kill haproxy process: %s"), pid)
示例#23
0
    def test_iface_to_br_handles_ovs_vsctl_exception(self):
        iface = 'tap0'
        root_helper = 'sudo'
        utils.execute(["ovs-vsctl", self.TO, "iface-to-br", iface],
                      root_helper=root_helper).AndRaise(Exception)

        self.mox.ReplayAll()
        self.assertIsNone(ovs_lib.get_bridge_for_iface(root_helper, iface))
        self.mox.VerifyAll()
示例#24
0
    def test_get_datapath_id(self):
        datapath_id = '"0000b67f4fbcc149"'
        utils.execute(["ovs-vsctl", self.TO, "get",
                       "Bridge", self.BR_NAME, "datapath_id"],
                      root_helper=self.root_helper).AndReturn(datapath_id)
        self.mox.ReplayAll()

        self.assertEqual(self.br.get_datapath_id(), datapath_id.strip('"'))
        self.mox.VerifyAll()
示例#25
0
    def test_delete_port(self):
        pname = "tap5"
        utils.execute(["ovs-vsctl", self.TO, "--", "--if-exists",
                       "del-port", self.BR_NAME, pname],
                      root_helper=self.root_helper)

        self.mox.ReplayAll()
        self.br.delete_port(pname)
        self.mox.VerifyAll()
示例#26
0
    def test_get_bridges(self):
        bridges = ['br-int', 'br-ex']
        root_helper = 'sudo'
        utils.execute(["ovs-vsctl", self.TO, "list-br"],
                      root_helper=root_helper).AndReturn('br-int\nbr-ex\n')

        self.mox.ReplayAll()
        self.assertEqual(ovs_lib.get_bridges(root_helper), bridges)
        self.mox.VerifyAll()
示例#27
0
    def test_delete_port(self):
        pname = "tap5"
        utils.execute(["ovs-vsctl", self.TO, "--", "--if-exists",
                       "del-port", self.BR_NAME, pname],
                      root_helper=self.root_helper)

        self.mox.ReplayAll()
        self.br.delete_port(pname)
        self.mox.VerifyAll()
示例#28
0
    def test_iface_to_br_handles_ovs_vsctl_exception(self):
        iface = 'tap0'
        root_helper = 'sudo'
        utils.execute(["ovs-vsctl", self.TO, "iface-to-br", iface],
                      root_helper=root_helper).AndRaise(Exception)

        self.mox.ReplayAll()
        self.assertIsNone(ovs_lib.get_bridge_for_iface(root_helper, iface))
        self.mox.VerifyAll()
示例#29
0
    def test_count_flows(self):
        utils.execute(["ovs-ofctl", "dump-flows", self.BR_NAME],
                      root_helper=self.root_helper).AndReturn('ignore'
                                                              '\nflow-1\n')
        self.mox.ReplayAll()

        # counts the number of flows as total lines of output - 2
        self.assertEqual(self.br.count_flows(), 1)
        self.mox.VerifyAll()
示例#30
0
    def test_get_datapath_id(self):
        datapath_id = '"0000b67f4fbcc149"'
        utils.execute(["ovs-vsctl", self.TO, "get",
                       "Bridge", self.BR_NAME, "datapath_id"],
                      root_helper=self.root_helper).AndReturn(datapath_id)
        self.mox.ReplayAll()

        self.assertEqual(self.br.get_datapath_id(), datapath_id.strip('"'))
        self.mox.VerifyAll()
示例#31
0
    def test_get_bridges(self):
        bridges = ['br-int', 'br-ex']
        root_helper = 'sudo'
        utils.execute(["ovs-vsctl", self.TO, "list-br"],
                      root_helper=root_helper).AndReturn('br-int\nbr-ex\n')

        self.mox.ReplayAll()
        self.assertEqual(ovs_lib.get_bridges(root_helper), bridges)
        self.mox.VerifyAll()
示例#32
0
    def enable(self, cmd_callback):
        if not self.active:
            cmd = cmd_callback(self.get_pid_file_name(ensure_pids_dir=True))

            if self.namespace:
                ip_wrapper = ip_lib.IPWrapper(self.root_helper, self.namespace)
                ip_wrapper.netns.execute(cmd)
            else:
                # For normal sudo prepend the env vars before command
                utils.execute(cmd, self.root_helper)
示例#33
0
 def test_get_vif_port_set_list_interface_error(self):
     utils.execute(["ovs-vsctl", self.TO, "list-ports", self.BR_NAME],
                   root_helper=self.root_helper).AndRaise('tap99\n')
     utils.execute(["ovs-vsctl", self.TO, "--format=json",
                    "--", "--columns=name,external_ids",
                    "list", "Interface"],
                   root_helper=self.root_helper).AndRaise(RuntimeError())
     self.mox.ReplayAll()
     self.assertEqual(set(), self.br.get_vif_port_set())
     self.mox.VerifyAll()
示例#34
0
    def test_iface_to_br(self):
        iface = 'tap0'
        br = 'br-int'
        root_helper = 'sudo'
        utils.execute(["ovs-vsctl", self.TO, "iface-to-br", iface],
                      root_helper=root_helper).AndReturn('br-int')

        self.mox.ReplayAll()
        self.assertEqual(ovs_lib.get_bridge_for_iface(root_helper, iface), br)
        self.mox.VerifyAll()
示例#35
0
 def delete_vlan(self, interface):
     if self.device_exists(interface):
         LOG.debug("Deleting subinterface %s for vlan" % interface)
         if utils.execute(['ip', 'link', 'set', interface, 'down'],
                          root_helper=self.root_helper):
             return
         if utils.execute(['ip', 'link', 'delete', interface],
                          root_helper=self.root_helper):
             return
         LOG.debug("Done deleting subinterface %s" % interface)
示例#36
0
 def delete_vlan(self, interface):
     if self.device_exists(interface):
         LOG.debug("Deleting subinterface %s for vlan" % interface)
         if utils.execute(['ip', 'link', 'set', interface, 'down'],
                          root_helper=self.root_helper):
             return
         if utils.execute(['ip', 'link', 'delete', interface],
                          root_helper=self.root_helper):
             return
         LOG.debug("Done deleting subinterface %s" % interface)
示例#37
0
    def test_get_port_ofport(self):
        pname = "tap99"
        ofport = "6"
        utils.execute(["ovs-vsctl", self.TO, "get",
                       "Interface", pname, "ofport"],
                      root_helper=self.root_helper).AndReturn(ofport)
        self.mox.ReplayAll()

        self.assertEqual(self.br.get_port_ofport(pname), ofport)
        self.mox.VerifyAll()
示例#38
0
    def test_get_port_ofport(self):
        pname = "tap99"
        ofport = "6"
        utils.execute(
            ["ovs-vsctl", self.TO, "get", "Interface", pname, "ofport"],
            root_helper=self.root_helper).AndReturn(ofport)
        self.mox.ReplayAll()

        self.assertEqual(self.br.get_port_ofport(pname), ofport)
        self.mox.VerifyAll()
示例#39
0
    def test_reset_bridge(self):
        utils.execute(["ovs-vsctl", self.TO, "--",
                       "--if-exists", "del-br", self.BR_NAME],
                      root_helper=self.root_helper)
        utils.execute(["ovs-vsctl", self.TO, "add-br", self.BR_NAME],
                      root_helper=self.root_helper)
        self.mox.ReplayAll()

        self.br.reset_bridge()
        self.mox.VerifyAll()
示例#40
0
    def test_reset_bridge(self):
        utils.execute(["ovs-vsctl", self.TO, "--",
                       "--if-exists", "del-br", self.BR_NAME],
                      root_helper=self.root_helper)
        utils.execute(["ovs-vsctl", self.TO, "add-br", self.BR_NAME],
                      root_helper=self.root_helper)
        self.mox.ReplayAll()

        self.br.reset_bridge()
        self.mox.VerifyAll()
示例#41
0
    def test_iface_to_br(self):
        iface = 'tap0'
        br = 'br-int'
        root_helper = 'sudo'
        utils.execute(["ovs-vsctl", self.TO, "iface-to-br", iface],
                      root_helper=root_helper).AndReturn('br-int')

        self.mox.ReplayAll()
        self.assertEqual(ovs_lib.get_bridge_for_iface(root_helper, iface), br)
        self.mox.VerifyAll()
示例#42
0
 def unplug(self, device_name, bridge=None, namespace=None, prefix=None):
     """Unplug the interface."""
     tap_name = self._get_tap_name(device_name, prefix)
     try:
         cmd = ['ivs-ctl', 'del-port', tap_name]
         utils.execute(cmd, self.root_helper)
         device = ip_lib.IPDevice(device_name, self.root_helper, namespace)
         device.link.delete()
         LOG.debug(_("Unplugged interface '%s'"), device_name)
     except RuntimeError:
         LOG.error(_("Failed unplugging interface '%s'"), device_name)
示例#43
0
 def _update_routing_table(self, ri, operation, route):
     cmd = ['ip', 'route', operation, 'to', route['destination'],
            'via', route['nexthop']]
     #TODO(nati) move this code to iplib
     if self.conf.use_namespaces:
         ip_wrapper = ip_lib.IPWrapper(self.conf.root_helper,
                                       namespace=ri.ns_name())
         ip_wrapper.netns.execute(cmd, check_exit_code=False)
     else:
         utils.execute(cmd, check_exit_code=False,
                       root_helper=self.conf.root_helper)
示例#44
0
    def disable(self):
        pid = self.pid

        if self.active:
            cmd = ['kill', '-9', pid]
            utils.execute(cmd, self.root_helper)
        elif pid:
            LOG.debug(_('Process for %(uuid)s pid %(pid)d is stale, ignoring '
                        'command'), {'uuid': self.uuid, 'pid': pid})
        else:
            LOG.debug(_('No process started for %s'), self.uuid)
示例#45
0
def kill_pids_in_file(root_helper, pid_path):
    if os.path.exists(pid_path):
        with open(pid_path, 'r') as pids:
            for pid in pids:
                pid = pid.strip()
                try:
                    utils.execute(['kill', '-9', pid], root_helper)
                except RuntimeError:
                    LOG.exception(
                        _('Unable to kill haproxy process: %s'),
                        pid
                    )
示例#46
0
文件: dhcp.py 项目: Milstein/quantum
    def disable(self):
        """Disable DHCP for this network by killing the local process."""
        pid = self.pid

        if self.active:
            utils.execute(['kill', '-9', pid], self.root_helper)
            self.device_delegate.destroy(self.network)
        elif pid:
            LOG.debug(_('DHCP for %s pid %d is stale, ignoring command') %
                      (self.network.id, pid))
        else:
            LOG.debug(_('No DHCP started for %s') % self.network.id)
示例#47
0
 def _ovs_add_port(self, bridge, device_name, port_id, mac_address,
                   internal=True):
     cmd = ['ovs-vsctl', '--', '--may-exist',
            'add-port', bridge, device_name]
     if internal:
         cmd += ['--', 'set', 'Interface', device_name, 'type=internal']
     cmd += ['--', 'set', 'Interface', device_name,
             'external-ids:iface-id=%s' % port_id,
             '--', 'set', 'Interface', device_name,
             'external-ids:iface-status=active',
             '--', 'set', 'Interface', device_name,
             'external-ids:attached-mac=%s' % mac_address]
     utils.execute(cmd, self.root_helper)
示例#48
0
    def plug(self, network_id, port_id, device_name, mac_address):
        """Plugin the interface."""
        if not ip_lib.device_exists(device_name):
            device = ip_lib.IPDevice(device_name, self.conf.root_helper)
            try:
                # First, try with 'ip'
                device.tuntap.add()
            except RuntimeError, e:
                # Second option: tunctl
                utils.execute(["tunctl", "-b", "-t", device_name], self.conf.root_helper)

            device.link.set_address(mac_address)
            device.link.set_up()
示例#49
0
 def _update_routing_table(self, ri, operation, route):
     cmd = [
         'ip', 'route', operation, 'to', route['destination'], 'via',
         route['nexthop']
     ]
     #TODO(nati) move this code to iplib
     if self.conf.use_namespaces:
         ip_wrapper = ip_lib.IPWrapper(self.conf.root_helper,
                                       namespace=ri.ns_name())
         ip_wrapper.netns.execute(cmd, check_exit_code=False)
     else:
         utils.execute(cmd,
                       check_exit_code=False,
                       root_helper=self.conf.root_helper)
    def add_tap_interface(self, network_id, physical_network, vlan_id,
                          tap_device_name):
        """
        If a VIF has been plugged into a network, this function will
        add the corresponding tap device to the relevant bridge
        """
        if not tap_device_name:
            return False

        if not self.device_exists(tap_device_name):
            LOG.debug("Tap device: %s does not exist on this host, skipped" %
                      tap_device_name)
            return False

        current_bridge_name = self.get_bridge_for_tap_device(tap_device_name)
        bridge_name = self.get_bridge_name(network_id)
        if bridge_name == current_bridge_name:
            return False
        LOG.debug("Adding device %s to bridge %s" %
                  (tap_device_name, bridge_name))
        if current_bridge_name:
            if utils.execute(
                ['brctl', 'delif', current_bridge_name, tap_device_name],
                    root_helper=self.root_helper):
                return False

        if int(vlan_id) == lconst.LOCAL_VLAN_ID:
            self.ensure_local_bridge(network_id)
        else:
            physical_interface = self.interface_mappings.get(physical_network)
            if not physical_interface:
                LOG.error("No mapping for physical network %s" %
                          physical_network)
                return False

            if int(vlan_id) == lconst.FLAT_VLAN_ID:
                self.ensure_flat_bridge(network_id, physical_interface)
            else:
                self.ensure_vlan_bridge(network_id, physical_interface,
                                        vlan_id)

        if utils.execute(['brctl', 'addif', bridge_name, tap_device_name],
                         root_helper=self.root_helper):
            return False

        LOG.debug("Done adding device %s to bridge %s" %
                  (tap_device_name, bridge_name))
        return True
示例#51
0
 def active(self):
     pid = self.pid
     cmd = ['cat', '/proc/%s/cmdline' % pid]
     try:
         return self.network.id in utils.execute(cmd, self.root_helper)
     except RuntimeError, e:
         return False
示例#52
0
 def get_xapi_iface_id(self, xs_vif_uuid):
     return utils.execute([
         "xe", "vif-param-get", "param-name=other-config",
         "param-key=nicira-iface-id",
         "uuid=%s" % xs_vif_uuid
     ],
                          root_helper=self.root_helper).strip()
示例#53
0
 def _send_gratuitous_arp_packet(self, ri, interface_name, ip_address):
     if self.conf.send_arp_for_ha > 0:
         arping_cmd = ['arping', '-A', '-U',
                       '-I', interface_name,
                       '-c', self.conf.send_arp_for_ha,
                       ip_address]
         try:
             if self.conf.use_namespaces:
                 ip_wrapper = ip_lib.IPWrapper(self.conf.root_helper,
                                               namespace=ri.ns_name())
                 ip_wrapper.netns.execute(arping_cmd, check_exit_code=True)
             else:
                 utils.execute(arping_cmd, check_exit_code=True,
                               root_helper=self.conf.root_helper)
         except Exception as e:
             LOG.error(_("Failed sending gratuitous ARP: %s") % str(e))
示例#54
0
    def add_tap_interface(self, network_id, physical_network, vlan_id,
                          tap_device_name):
        """
        If a VIF has been plugged into a network, this function will
        add the corresponding tap device to the relevant bridge
        """
        if not self.device_exists(tap_device_name):
            LOG.debug(
                _("Tap device: %s does not exist on "
                  "this host, skipped" % tap_device_name))
            return False

        bridge_name = self.get_bridge_name(network_id)
        if int(vlan_id) == lconst.LOCAL_VLAN_ID:
            self.ensure_local_bridge(network_id)
        else:
            result = self.ensure_physical_in_bridge(network_id,
                                                    physical_network, vlan_id)
            if not result:
                return False

        # Check if device needs to be added to bridge
        tap_device_in_bridge = self.get_bridge_for_tap_device(tap_device_name)
        if not tap_device_in_bridge:
            msg = _("Adding device %(tap_device_name)s to bridge "
                    "%(bridge_name)s") % locals()
            LOG.debug(msg)
            if utils.execute(['brctl', 'addif', bridge_name, tap_device_name],
                             root_helper=self.root_helper):
                return False
        else:
            msg = _("%(tap_device_name)s already exists on bridge "
                    "%(bridge_name)s") % locals()
            LOG.debug(msg)
        return True
示例#55
0
def get_bridge_for_iface(root_helper, iface):
    args = ["ovs-vsctl", "--timeout=2", "iface-to-br", iface]
    try:
        return utils.execute(args, root_helper=root_helper).strip()
    except Exception:
        LOG.exception(_("Interface %s not found."), iface)
        return None
示例#56
0
def get_bridges(root_helper):
    args = ["ovs-vsctl", "--timeout=2", "list-br"]
    try:
        return utils.execute(args, root_helper=root_helper).strip().split("\n")
    except Exception, e:
        LOG.exception(_("Unable to retrieve bridges. Exception: %s"), e)
        return []
示例#57
0
 def run_vsctl(self, args):
     full_args = ["ovs-vsctl", "--timeout=2"] + args
     try:
         return utils.execute(full_args, root_helper=self.root_helper)
     except Exception, e:
         LOG.error(_("Unable to execute %(cmd)s. Exception: %(exception)s"),
                   {'cmd': full_args, 'exception': e})
示例#58
0
 def run_ofctl(self, cmd, args):
     full_args = ["ovs-ofctl", cmd, self.br_name] + args
     try:
         return utils.execute(full_args, root_helper=self.root_helper)
     except Exception, e:
         LOG.error(_("Unable to execute %(cmd)s. Exception: %(exception)s"),
                   {'cmd': full_args, 'exception': e})