当前位置: 首页>>代码示例>>Python>>正文


Python IPRoute.link_create方法代码示例

本文整理汇总了Python中pyroute2.IPRoute.link_create方法的典型用法代码示例。如果您正苦于以下问题:Python IPRoute.link_create方法的具体用法?Python IPRoute.link_create怎么用?Python IPRoute.link_create使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在pyroute2.IPRoute的用法示例。


在下文中一共展示了IPRoute.link_create方法的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: connect_to_br

# 需要导入模块: from pyroute2 import IPRoute [as 别名]
# 或者: from pyroute2.IPRoute import link_create [as 别名]
 def connect_to_br(self):
     index = 0
     with docker_netns(self.name) as pid:
         for quagga_config in self.quagga_config:
             ip = IPRoute()
             br = ip.link_lookup(ifname=quagga_config['bridge'])
             if len(br) == 0:
                 ip.link_create(ifname=quagga_config['bridge'], kind='bridge')
                 br = ip.link_lookup(ifname=quagga_config['bridge'])
             br = br[0]
             ip.link('set', index=br, state='up')
             ifname = '{0}-{1}'.format(self.name, index)
             ifs = ip.link_lookup(ifname=ifname)
             if len(ifs) > 0:
                ip.link_remove(ifs[0])
             peer_ifname = '{0}-{1}'.format(pid, index)
             ip.link_create(ifname=ifname, kind='veth', peer=peer_ifname)
             host = ip.link_lookup(ifname=ifname)[0]
             ip.link('set', index=host, master=br)
             ip.link('set', index=host, state='up')
             guest = ip.link_lookup(ifname=peer_ifname)[0]
             ip.link('set', index=guest, net_ns_fd=pid)
             with Namespace(pid, 'net'):
                 ip = IPRoute()
                 ip.link('set', index=guest, ifname='eth{}'.format(index+1))
                 ip.addr('add', index=guest, address=quagga_config['ip'], mask=quagga_config['mask'])
                 ip.link('set', index=guest, state='up')
             index += 1
开发者ID:chetangaonker,项目名称:cord-tester,代码行数:30,代码来源:CordContainer.py

示例2: create_interface

# 需要导入模块: from pyroute2 import IPRoute [as 别名]
# 或者: from pyroute2.IPRoute import link_create [as 别名]
    def create_interface(self):
        '''
        Create veth-pair
        Creates veth-pair in the host-os first and then one end of the pair is
        moved inside container.

        Name of interface inside container can be same for multiple containers.
        So, the veth-pair cannot be created with name of interface inside
        cotnainer. The veth-pair is created with a temporary name and will be
        renamed later
        '''

        # Check if interface already created
        iproute = IPRoute()
        iface = iproute.link_lookup(ifname=self.host_ifname)
        if len(iface) != 0:
            return

        # Create veth pairs. One end of pair is named host_ifname and the
        # other end of pair is set a temporary name. It will be overridden
        # once interface is moved inside container
        try:
            cn_name = self.host_ifname + '-ns'
            iproute.link_create(ifname=self.host_ifname, peer=cn_name,
                                kind='veth')
        except NetlinkError as e:
            if e.code != errno.EEXIST:
                raise CniError(CNI_ERROR_ADD_VETH,
                               'Error creating veth device ' +
                               self.host_ifname + ' code ' + str(e.code) +
                               ' message ' + e.message)
        # Move one end of pair inside container
        self.move_link(cn_name)
        return
开发者ID:Juniper,项目名称:contrail-controller,代码行数:36,代码来源:cni.py

示例3: create_interface

# 需要导入模块: from pyroute2 import IPRoute [as 别名]
# 或者: from pyroute2.IPRoute import link_create [as 别名]
    def create_interface(self):
        '''
        Create veth-pair
        Creates veth-pair in the container-namespace first and then moves
        one end of the pair to host-os namespace
        '''
        # If the host end of veth is already present in host-os, it means
        # interface create was already done. There is nothing to do
        iproute = IPRoute()
        iface = iproute.link_lookup(ifname=self.host_ifname)
        if len(iface) != 0:
            return

        host_ifindex = None
        with CniNamespace(self.cni.container_netns):
            # Create veth pairs if not already created inside namespace
            # One end of pair is named host_ifname and the other end of pair
            # is set a container_ifname
            ns_iproute = IPRoute()
            ns_iface = ns_iproute.link_lookup(ifname=self.cni.container_ifname)
            if len(ns_iface) == 0:
                try:
                    ns_iproute.link_create(ifname=self.cni.container_ifname,
                                        peer=self.host_ifname, kind='veth',
                                        address=self.container_mac)
                except NetlinkError as e:
                    if e.code != errno.EEXIST:
                        raise Error(CNI_ERROR_VETH_ADD,
                                    'Error creating veth device ' +
                                    self.host_ifname + ' code ' +
                                    str(e.code) + ' message ' + e.message)

            # We must move the host part of veth pair to host-namespace
            # Get the interface-index. We will move to host namespace once
            # we exit container-name space and go to host-namespace
            host_ifindex = ns_iproute.link_lookup(ifname=self.host_ifname)[0]

        if host_ifindex is not None:
            ns_iproute.link('set', index=host_ifindex, net_ns_pid=self.pid)

        return
开发者ID:Juniper,项目名称:contrail-controller,代码行数:43,代码来源:veth.py

示例4: BasicTest

# 需要导入模块: from pyroute2 import IPRoute [as 别名]
# 或者: from pyroute2.IPRoute import link_create [as 别名]
class BasicTest(object):

    def setup(self):
        require_user('root')
        self.ip = IPRoute()
        self.ifname = uifname()
        self.ip.link_create(ifname=self.ifname, kind='dummy')
        self.interface = self.ip.link_lookup(ifname=self.ifname)[0]

    def teardown(self):
        self.ip.link('delete', index=self.interface)
        self.ip.close()

    def get_qdiscs(self):
        return [x for x in self.ip.get_qdiscs() if
                x['index'] == self.interface]

    def get_qdisc(self):
        # get qdiscs list and filter out our interface
        qds = self.get_qdiscs()
        if qds:
            return qds[0]
        else:
            return None
开发者ID:GateprotectGmbH,项目名称:pyroute2,代码行数:26,代码来源:test_tc.py

示例5: connect_ctn_to_br

# 需要导入模块: from pyroute2 import IPRoute [as 别名]
# 或者: from pyroute2.IPRoute import link_create [as 别名]
def connect_ctn_to_br(ctn, brname):
    with docker_netns(ctn) as pid:
        ip = IPRoute()
        br = ip.link_lookup(ifname=brname)
        if len(br) == 0:
            ip.link_create(ifname=brname, kind='bridge')
            br = ip.link_lookup(ifname=brname)
        br = br[0]
        ip.link('set', index=br, state='up')

        ifs = ip.link_lookup(ifname=ctn)
        if len(ifs) > 0:
           ip.link_remove(ifs[0])

        ip.link_create(ifname=ctn, kind='veth', peer=pid)
        host = ip.link_lookup(ifname=ctn)[0]
        ip.link('set', index=host, master=br)
        ip.link('set', index=host, state='up')
        guest = ip.link_lookup(ifname=pid)[0]
        ip.link('set', index=guest, net_ns_fd=pid)
        with Namespace(pid, 'net'):
            ip = IPRoute()
            ip.link('set', index=guest, ifname='eth1')
            ip.link('set', index=guest, state='up')
开发者ID:chetangaonker,项目名称:bgperf,代码行数:26,代码来源:base.py

示例6: TestIPRoute

# 需要导入模块: from pyroute2 import IPRoute [as 别名]
# 或者: from pyroute2.IPRoute import link_create [as 别名]
class TestIPRoute(object):

    def setup(self):
        self.ip = IPRoute()
        self.ap = AddrPool()
        self.iftmp = 'pr2x{0}'
        try:
            self.dev, idx = self.create()
            self.ifaces = [idx]
        except IndexError:
            pass

    def get_ifname(self):
        return self.iftmp.format(self.ap.alloc())

    def create(self, kind='dummy'):
        name = self.get_ifname()
        create_link(name, kind=kind)
        idx = self.ip.link_lookup(ifname=name)[0]
        return (name, idx)

    def teardown(self):
        if hasattr(self, 'ifaces'):
            for dev in self.ifaces:
                try:
                    self.ip.link('delete', index=dev)
                except:
                    pass
        self.ip.close()

    def _test_nla_operators(self):
        require_user('root')
        self.ip.addr('add', self.ifaces[0], address='172.16.0.1', mask=24)
        self.ip.addr('add', self.ifaces[0], address='172.16.0.2', mask=24)
        r = [x for x in self.ip.get_addr() if x['index'] == self.ifaces[0]]
        complement = r[0] - r[1]
        intersection = r[0] & r[1]

        assert complement.get_attr('IFA_ADDRESS') == '172.16.0.1'
        assert complement.get_attr('IFA_LABEL') is None
        assert complement['prefixlen'] == 0
        assert complement['index'] == 0

        assert intersection.get_attr('IFA_ADDRESS') is None
        assert intersection.get_attr('IFA_LABEL') == self.dev
        assert intersection['prefixlen'] == 24
        assert intersection['index'] == self.ifaces[0]

    def test_add_addr(self):
        require_user('root')
        self.ip.addr('add', self.ifaces[0], address='172.16.0.1', mask=24)
        assert '172.16.0.1/24' in get_ip_addr()

    def _create(self, kind):
        name = self.get_ifname()
        self.ip.link_create(ifname=name, kind=kind)
        devs = self.ip.link_lookup(ifname=name)
        assert devs
        self.ifaces.extend(devs)

    def test_create_dummy(self):
        require_user('root')
        self._create('dummy')

    def test_create_bond(self):
        require_user('root')
        self._create('bond')

    def test_create_bridge(self):
        require_user('root')
        self._create('bridge')

    def test_neigh_real_links(self):
        links = set([x['index'] for x in self.ip.get_links()])
        neigh = set([x['ifindex'] for x in self.ip.get_neighbors()])
        assert neigh < links

    def test_mass_ipv6(self):
        #
        # Achtung! This test is time consuming.
        # It is really time consuming, I'm not not
        # kidding you. Beware.
        #
        require_user('root')
        base = 'fdb3:84e5:4ff4:55e4::{0}'
        limit = int(os.environ.get('PYROUTE2_SLIMIT', '0x800'), 16)

        # add addresses
        for idx in range(limit):
            self.ip.addr('add', self.ifaces[0],
                         base.format(hex(idx)[2:]), 48)

        # assert addresses in two steps, to ease debug
        addrs = self.ip.get_addr(10)
        assert len(addrs) >= limit

        # clean up addresses
        #
        # it is not required, but if you don't do that,
        # you'll get this on the interface removal:
#.........这里部分代码省略.........
开发者ID:jazzmes,项目名称:pyroute2,代码行数:103,代码来源:test_ipr.py

示例7: Copyright

# 需要导入模块: from pyroute2 import IPRoute [as 别名]
# 或者: from pyroute2.IPRoute import link_create [as 别名]
#!/usr/bin/env python
# Copyright (c) PLUMgrid, Inc.
# Licensed under the Apache License, Version 2.0 (the "License")

from bpf import BPF
from pyroute2 import IPRoute

ipr = IPRoute()

text = """
int hello(struct __sk_buff *skb) {
  return 1;
}
"""

try:
    b = BPF(text=text, debug=0)
    fn = b.load_func("hello", BPF.SCHED_CLS)
    ipr.link_create(ifname="t1a", kind="veth", peer="t1b")
    idx = ipr.link_lookup(ifname="t1a")[0]

    ipr.tc("add", "ingress", idx, "ffff:")
    ipr.tc("add-filter", "bpf", idx, ":1", fd=fn.fd,
           name=fn.name, parent="ffff:", action="ok", classid=1)
    ipr.tc("add", "sfq", idx, "1:")
    ipr.tc("add-filter", "bpf", idx, ":1", fd=fn.fd,
           name=fn.name, parent="1:", action="ok", classid=1)
finally:
    if "idx" in locals(): ipr.link_remove(idx)
开发者ID:hgn,项目名称:bcc,代码行数:31,代码来源:simple_tc.py

示例8: TestIPRoute

# 需要导入模块: from pyroute2 import IPRoute [as 别名]
# 或者: from pyroute2.IPRoute import link_create [as 别名]

#.........这里部分代码省略.........
    def test_rules_deprecated(self):
        require_user('root')
        init = len(self.ip.get_rules(family=socket.AF_INET))
        assert len(self.ip.get_rules(priority=lambda x: 100 < x < 500)) == 0
        self.ip.rule('add', 10, 110)
        self.ip.rule('add', 15, 150, 'FR_ACT_PROHIBIT')
        assert len(self.ip.get_rules(priority=lambda x: 100 < x < 500)) == 2
        self.ip.flush_rules(family=socket.AF_INET,
                            priority=lambda x: 100 < x < 500)
        assert len(self.ip.get_rules(priority=lambda x: 100 < x < 500)) == 0
        assert len(self.ip.get_rules(family=socket.AF_INET)) == init

    def test_addr_filter(self):
        require_user('root')
        self.ip.addr('add',
                     index=self.ifaces[0],
                     address='172.16.0.1',
                     prefixlen=24,
                     broadcast='172.16.0.255')
        self.ip.addr('add',
                     index=self.ifaces[0],
                     address='172.16.0.2',
                     prefixlen=24,
                     broadcast='172.16.0.255')
        assert len(self.ip.get_addr(index=self.ifaces[0])) == 2
        assert len(self.ip.get_addr(address='172.16.0.1')) == 1
        assert len(self.ip.get_addr(broadcast='172.16.0.255')) == 2
        assert len(self.ip.get_addr(match=lambda x: x['index'] ==
                                    self.ifaces[0])) == 2

    @skip_if_not_supported
    def _create(self, kind):
        name = uifname()
        self.ip.link_create(ifname=name, kind=kind)
        devs = self.ip.link_lookup(ifname=name)
        assert devs
        self.ifaces.extend(devs)

    def test_create_dummy(self):
        require_user('root')
        self._create('dummy')

    def test_create_bond(self):
        require_user('root')
        self._create('bond')

    def test_create_bridge(self):
        require_user('root')
        self._create('bridge')

    def test_create_ovs_bridge(self):
        require_user('root')
        self._create('ovs-bridge')

    def test_create_team(self):
        require_user('root')
        self._create('team')

    def test_ntables(self):
        setA = set(filter(lambda x: x is not None,
                          [x.get_attr('NDTA_PARMS').get_attr('NDTPA_IFINDEX')
                           for x in self.ip.get_ntables()]))
        setB = set([x['index'] for x in self.ip.get_links()])
        assert setA == setB

    def test_neigh_real_links(self):
开发者ID:thezeep,项目名称:pyroute2,代码行数:70,代码来源:test_ipr.py

示例9: TestRule

# 需要导入模块: from pyroute2 import IPRoute [as 别名]
# 或者: from pyroute2.IPRoute import link_create [as 别名]
class TestRule(object):

    def setup(self):
        require_user('root')
        self.ip = IPRoute()
        self.ifname = uifname()
        self.ip.link_create(ifname=self.ifname, kind='dummy')
        self.interface = self.ip.link_lookup(ifname=self.ifname)[0]

    def teardown(self):
        self.ip.link('delete', index=self.interface)
        self.ip.close()

    def test_basic(self):
        self.ip.rule('add', 10, 32000)
        assert len([x for x in self.ip.get_rules() if
                    x.get_attr('FRA_PRIORITY') == 32000 and
                    x.get_attr('FRA_TABLE') == 10]) == 1
        self.ip.rule('delete', 10, 32000)
        assert len([x for x in self.ip.get_rules() if
                    x.get_attr('FRA_PRIORITY') == 32000 and
                    x.get_attr('FRA_TABLE') == 10]) == 0

    def test_fwmark(self):
        self.ip.rule('add', 15, 32006, fwmark=10)
        assert len([x for x in self.ip.get_rules() if
                    x.get_attr('FRA_PRIORITY') == 32006 and
                    x.get_attr('FRA_TABLE') == 15 and
                    x.get_attr('FRA_FWMARK')]) == 1
        self.ip.rule('delete', 15, 32006, fwmark=10)
        assert len([x for x in self.ip.get_rules() if
                    x.get_attr('FRA_PRIORITY') == 32006 and
                    x.get_attr('FRA_TABLE') == 15 and
                    x.get_attr('FRA_FWMARK')]) == 0

    def test_fwmark_mask_normalized(self):
        self.ip.rule('add', 15, 32006, fwmark=10, fwmask=20)
        assert len([x for x in self.ip.get_rules() if
                    x.get_attr('FRA_PRIORITY') == 32006 and
                    x.get_attr('FRA_TABLE') == 15 and
                    x.get_attr('FRA_FWMARK') and
                    x.get_attr('FRA_FWMASK')]) == 1
        self.ip.rule('delete', 15, 32006, fwmark=10, fwmask=20)
        assert len([x for x in self.ip.get_rules() if
                    x.get_attr('FRA_PRIORITY') == 32006 and
                    x.get_attr('FRA_TABLE') == 15 and
                    x.get_attr('FRA_FWMARK') and
                    x.get_attr('FRA_FWMASK')]) == 0

    def test_fwmark_mask_raw(self):
        self.ip.rule('add', 15, 32006, fwmark=10, FRA_FWMASK=20)
        assert len([x for x in self.ip.get_rules() if
                    x.get_attr('FRA_PRIORITY') == 32006 and
                    x.get_attr('FRA_TABLE') == 15 and
                    x.get_attr('FRA_FWMARK') and
                    x.get_attr('FRA_FWMASK')]) == 1
        self.ip.rule('delete', 15, 32006, fwmark=10, FRA_FWMASK=20)
        assert len([x for x in self.ip.get_rules() if
                    x.get_attr('FRA_PRIORITY') == 32006 and
                    x.get_attr('FRA_TABLE') == 15 and
                    x.get_attr('FRA_FWMARK') and
                    x.get_attr('FRA_FWMASK')]) == 0

    def test_bad_table(self):
        try:
            self.ip.rule('add', -1, 32000)
        except Exception:
            pass

    def test_big_table(self):
        self.ip.rule('add', 1024, 32000)
        assert len([x for x in self.ip.get_rules() if
                    x.get_attr('FRA_PRIORITY') == 32000 and
                    x.get_attr('FRA_TABLE') == 1024]) == 1
        self.ip.rule('delete', 1024, 32000)
        assert len([x for x in self.ip.get_rules() if
                    x.get_attr('FRA_PRIORITY') == 32000 and
                    x.get_attr('FRA_TABLE') == 1024]) == 0

    def test_src_dst(self):
        self.ip.rule('add', 17, 32005,
                     src='10.0.0.0', src_len=24,
                     dst='10.1.0.0', dst_len=24)
        assert len([x for x in self.ip.get_rules() if
                    x.get_attr('FRA_PRIORITY') == 32005 and
                    x.get_attr('FRA_TABLE') == 17 and
                    x.get_attr('FRA_SRC') == '10.0.0.0' and
                    x.get_attr('FRA_DST') == '10.1.0.0' and
                    x['src_len'] == 24 and
                    x['dst_len'] == 24]) == 1
        self.ip.rule('delete', 17, 32005,
                     src='10.0.0.0', src_len=24,
                     dst='10.1.0.0', dst_len=24)
        assert len([x for x in self.ip.get_rules() if
                    x.get_attr('FRA_PRIORITY') == 32005 and
                    x.get_attr('FRA_TABLE') == 17 and
                    x.get_attr('FRA_SRC') == '10.0.0.0' and
                    x.get_attr('FRA_DST') == '10.1.0.0' and
                    x['src_len'] == 24 and
                    x['dst_len'] == 24]) == 0
开发者ID:FirefighterBlu3,项目名称:pyroute2,代码行数:102,代码来源:test_rule.py

示例10: bench

# 需要导入模块: from pyroute2 import IPRoute [as 别名]
# 或者: from pyroute2.IPRoute import link_create [as 别名]
def bench(args):
    config_dir = '{0}/{1}'.format(args.dir, args.bench_name)
    brname = args.bench_name + '-br'

    ip = IPRoute()
    ctn_intfs = flatten((l.get_attr('IFLA_IFNAME') for l in ip.get_links() if l.get_attr('IFLA_MASTER') == br) for br in ip.link_lookup(ifname=brname))

    if not args.repeat:
        # currently ctn name is same as ctn intf
        # TODO support proper mapping between ctn name and intf name
        for ctn in ctn_intfs:
            dckr.remove_container(ctn, force=True) if ctn_exists(ctn) else None

        if os.path.exists(config_dir):
            shutil.rmtree(config_dir)
    else:
        for ctn in ctn_intfs:
            if ctn != 'tester':
                dckr.remove_container(ctn, force=True) if ctn_exists(ctn) else None

    if args.file:
        with open(args.file) as f:
            conf = yaml.load(f)
    else:
        conf = gen_conf(args)
        if not os.path.exists(config_dir):
            os.makedirs(config_dir)
        with open('{0}/scenario.yaml'.format(config_dir), 'w') as f:
            f.write(yaml.dump(conf))

    if len(conf['tester']) > gc_thresh3():
        print 'gc_thresh3({0}) is lower than the number of peer({1})'.format(gc_thresh3(), len(conf['tester']))
        print 'type next to increase the value'
        print '$ echo 16384 | sudo tee /proc/sys/net/ipv4/neigh/default/gc_thresh3'

    if args.target == 'gobgp':
        target = GoBGP
    elif args.target == 'bird':
        target = BIRD
    elif args.target == 'quagga':
        target = Quagga

    is_remote = True if 'remote' in conf['target'] and conf['target']['remote'] else False

    if is_remote:
        r = ip.get_routes(dst=conf['target']['local-address'].split('/')[0], family=AF_INET)
        if len(r) == 0:
            print 'no route to remote target {0}'.format(conf['target']['local-address'])
            sys.exit(1)

        idx = [t[1] for t in r[0]['attrs'] if t[0] == 'RTA_OIF'][0]
        intf = ip.get_links(idx)[0]

        if intf.get_attr('IFLA_MASTER') not in ip.link_lookup(ifname=brname):
            br = ip.link_lookup(ifname=brname)
            if len(br) == 0:
                ip.link_create(ifname=brname, kind='bridge')
                br = ip.link_lookup(ifname=brname)
            br = br[0]
            ip.link('set', index=idx, master=br)
    else:
        print 'run', args.target
        if args.image:
            target = target(args.target, '{0}/{1}'.format(config_dir, args.target), image=args.image)
        else:
            target = target(args.target, '{0}/{1}'.format(config_dir, args.target))
        target.run(conf, brname)

    print 'run monitor'
    m = Monitor('monitor', config_dir+'/monitor')
    m.run(conf, brname)

    time.sleep(1)

    print 'waiting bgp connection between {0} and monitor'.format(args.target)
    m.wait_established(conf['target']['local-address'].split('/')[0])

    if not args.repeat:
        print 'run tester'
        t = Tester('tester', config_dir+'/tester')
        t.run(conf, brname)

    start = datetime.datetime.now()

    q = Queue()

    m.stats(q)
    if not is_remote:
        target.stats(q)

    def mem_human(v):
        if v > 1000 * 1000 * 1000:
            return '{0:.2f}GB'.format(float(v) / (1000 * 1000 * 1000))
        elif v > 1000 * 1000:
            return '{0:.2f}MB'.format(float(v) / (1000 * 1000))
        elif v > 1000:
            return '{0:.2f}KB'.format(float(v) / 1000)
        else:
            return '{0:.2f}B'.format(float(v))

#.........这里部分代码省略.........
开发者ID:chetangaonker,项目名称:bgperf,代码行数:103,代码来源:bgperf.py

示例11: IPRoute

# 需要导入模块: from pyroute2 import IPRoute [as 别名]
# 或者: from pyroute2.IPRoute import link_create [as 别名]
from socket import AF_INET
from pyroute2 import IPRoute

# get access to the netlink socket
ip = IPRoute()

# print interfaces
# print(ip.get_links())

# NOTE: do this in case veth or netns exist:
# ip link del v0p0;  ip netns del test

netns.create('test')

# create VETH pair and move v0p1 to netns 'test'
ip.link_create(ifname='v0p0', peer='v0p1', kind='veth')
idx = ip.link_lookup(ifname='v0p1')[0]
ip.link('set',
        index=idx,
        net_ns_fd='test')

# bring v0p0 up and add an address
idx = ip.link_lookup(ifname='v0p0')[0]
ip.link('set',
        index=idx,
        state='up')
ip.addr('add',
        index=idx,
        address='10.0.0.1',
        broadcast='10.0.0.255',
        prefixlen=24)
开发者ID:Arvinderpal,项目名称:networkplayground,代码行数:33,代码来源:pyroute2_tests.py

示例12: NetworkBase

# 需要导入模块: from pyroute2 import IPRoute [as 别名]
# 或者: from pyroute2.IPRoute import link_create [as 别名]
class NetworkBase(Base):
    def __init__(self):
        Base.__init__(self)
        self.ipr = IPRoute()
        self.nodes = []

    def add_node(self, node):
        assert isinstance(node, Node)
        self.nodes.append(node)

    def get_interface_name(self, source, dest):
        assert isinstance(source, Node)
        assert isinstance(dest, Node)
        interface_name = "veth-" + source.name + "-" + dest.name
        return interface_name

    def get_interface(self, ifname):
        interfaces = self.ipr.link_lookup(ifname=ifname)
        if len(interfaces) != 1:
            raise Exception("Could not identify interface " + ifname)
        ix = interfaces[0]
        assert isinstance(ix, int)
        return ix

    def set_interface_ipaddress(self, node, ifname, address, mask):
        # Ask a node to set the specified interface address
        if address is None:
            return

        assert isinstance(node, Node)
        command = ["ip", "addr", "add", str(address) + "/" + str(mask),
                   "dev", str(ifname)]
        result = node.execute(command)
        assert(result == 0)

    def create_link(self, src, dest):
        assert isinstance(src, Endpoint)
        assert isinstance(dest, Endpoint)

        ifname = self.get_interface_name(src.parent, dest.parent)
        destname = self.get_interface_name(dest.parent, src.parent)
        self.ipr.link_create(ifname=ifname, kind="veth", peer=destname)

        self.message("Create", ifname, "link")

        # Set source endpoint information
        ix = self.get_interface(ifname)
        self.ipr.link("set", index=ix, address=src.mac_addr)
        # push source endpoint into source namespace
        self.ipr.link("set", index=ix,
                      net_ns_fd=src.parent.get_ns_name(), state="up")
        # Set interface ip address; seems to be
        # lost of set prior to moving to namespace
        self.set_interface_ipaddress(
            src.parent, ifname, src.ipaddress , src.prefixlen)

        # Sef destination endpoint information
        ix = self.get_interface(destname)
        self.ipr.link("set", index=ix, address=dest.mac_addr)
        # push destination endpoint into the destination namespace
        self.ipr.link("set", index=ix,
                      net_ns_fd=dest.parent.get_ns_name(), state="up")
        # Set interface ip address
        self.set_interface_ipaddress(dest.parent, destname,
                                     dest.ipaddress, dest.prefixlen)

    def show_interfaces(self, node):
        cmd = ["ip", "addr"]
        if node is None:
            # Run with no namespace
            subprocess.call(cmd)
        else:
            # Run in node's namespace
            assert isinstance(node, Node)
            self.message("Enumerating all interfaces in ", node.name)
            node.execute(cmd)

    def delete(self):
        self.message("Deleting virtual network")
        for n in self.nodes:
            n.remove()
        self.ipr.close()
开发者ID:ColinIanKing,项目名称:bcc,代码行数:84,代码来源:endToEndTest.py

示例13: __init__

# 需要导入模块: from pyroute2 import IPRoute [as 别名]
# 或者: from pyroute2.IPRoute import link_create [as 别名]

#.........这里部分代码省略.........
  def __getDefaultNetnsSymlinkPath(self):
    netnsDir = netns.NETNS_RUN_DIR
    if (not netnsDir.endswith('/')):
      netnsDir += '/'
    return netnsDir + self.__NETNS_DEFAULT_NAME


  def __createDefaultNetnsSymlink(self):
    symlinkPath = self.__getDefaultNetnsSymlinkPath()
    if (not os.path.exists(os.path.dirname(symlinkPath))):
      os.makedirs(os.path.dirname(symlinkPath))
    if (os.path.exists(symlinkPath) and os.path.islink(symlinkPath)):
      os.unlink(symlinkPath)
    os.symlink(self.__NETNS_DEFAULT_PROC, symlinkPath)
    LOG.debug('symlink {0}->{1} created'.format(symlinkPath, os.readlink(symlinkPath)))


  def __removeDefaultNetnsSymlink(self):
    symlinkPath = self.__getDefaultNetnsSymlinkPath()
    if (os.path.exists(symlinkPath) and os.path.islink(symlinkPath)):
      # need to read the link target for logging prior to delete a link
      symlinkTarget = os.readlink(symlinkPath)
      os.unlink(symlinkPath)
    LOG.debug('symlink {0}->{1} removed'.format(symlinkPath, symlinkTarget))


  def __createNetns(self, phyIfaceIndex):
    netnsName = self.__getNetnsName()
    (pvdIfaceName, pvdIfaceIndex) = self.__getPvdIfaceParams()
    netns.create(netnsName)
    LOG.debug('network namespace {0} created'.format(netnsName))

    # create a virtual interface where PvD parameters are going to be configured, then move the interface to the new network namespace
    self.ipRoot.link_create(ifname=pvdIfaceName, index=pvdIfaceIndex, kind=self.__PVD_IFACE_TYPE, link=phyIfaceIndex)
    LOG.debug('macvlan {0} created in default network namespace'.format(pvdIfaceName))
    pvdIfaceIndex = self.ipRoot.link_lookup(ifname=pvdIfaceName)
    self.ipRoot.link('set', index=pvdIfaceIndex[0], net_ns_fd=netnsName)
    LOG.debug('macvlan {0} moved to network namespace {1}'.format(pvdIfaceName, netnsName))

    # change the namespace and get new NETLINK handles to operate in new namespace
    netns.setns(netnsName)
    LOG.debug('network namespace switched to {0}'.format(netnsName))
    ip = IPRoute()
    ipdb = IPDB()
    ipdb.register_callback(self.__onIfaceStateChange)
    # disable kernel to auto-configure the interface associated with the PvD, let the pvdman to solely control interface configuration
    acceptRaConfFile = self.__ACCEPT_RA_CONF_FILE.replace(self.__IFACENAME_REPLACE_PATTERN, pvdIfaceName)
    acceptRaConfFile = open(acceptRaConfFile, 'w')
    acceptRaConfFile.write('0')
    LOG.debug('processing of RAs by kernel disabled in {0}'.format(acceptRaConfFile.name))
    # return to a default network namespace to not cause a colision with other modules
    # ip and ipdb handles continue to work in the target network namespace
    netns.setns(self.__NETNS_DEFAULT_NAME)
    LOG.debug('network namespace switched to default')

    # get new index since interface has been moved to a different namespace
    loIfaceIndex = ip.link_lookup(ifname=self.__LOOPBACK_IFACE_NAME)
    if (len(loIfaceIndex) > 0):
      loIfaceIndex = loIfaceIndex[0]
    pvdIfaceIndex = ip.link_lookup(ifname=pvdIfaceName)
    if (len(pvdIfaceIndex) > 0):
      pvdIfaceIndex = pvdIfaceIndex[0]

    # start interfaces
    ip.link_up(loIfaceIndex)
    ip.link_up(pvdIfaceIndex)
开发者ID:l30nard0,项目名称:mif,代码行数:70,代码来源:pvdman.py

示例14: main

# 需要导入模块: from pyroute2 import IPRoute [as 别名]
# 或者: from pyroute2.IPRoute import link_create [as 别名]
def main(argv):
    if (len(argv) !=  2):
        print('Usage: python pvdtest_veth.py PVD_ID')
        print('PVD_ID := name of the interface that contains PvD-related network configuration')
        sys.exit()

    # Get user-entered PVD ID
    pvdId = sys.argv[1]
    
    # Create IPRoute object for manipulation with a default network namespace
    ipMain = IPRoute()

    # Create a PvD-related network namespace
    pvdNetnsName = getPvdNetnsName(pvdId);
    if (pvdNetnsName in netns.listnetns()):
        netns.remove(pvdNetnsName)
    netns.create(pvdNetnsName)

    # Create IPRoute object for manipulation with a PvD-related network namespace
    netns.setns(pvdNetnsName)
    ipPvd = IPRoute()

    # Activate loopback interface in a PvD-related network namespace
    loIndex = ipPvd.link_lookup(ifname='lo')[0]
    ipPvd.link_up(loIndex)

    # Get addresses from a PvD-related network interface
    pvdIfIndex = ipMain.link_lookup(ifname=getPvdIfName(pvdId))[0]
    pvdAddresses = ipMain.get_addr(index=pvdIfIndex)

    # Get current routes
    pvdRoutes = ipMain.get_routes()

    # Create bridge
    bridge = getPvdBridgeName(pvdId)
    ipMain.link_create(ifname=bridge, kind='bridge')

    # Create veth interface
    (veth0, veth1) = getPvdVethNames(pvdId)
    ipMain.link_create(ifname=veth0, kind='veth', peer=veth1)

    # Move one end of the veth interafce to a PvD-related network namespace
    veth1Index = ipMain.link_lookup(ifname=veth1)[0]
    ipMain.link('set', index=veth1Index, net_ns_fd=pvdNetnsName)

    # Shut down and remove addresses from the PvD interface before adding it to the bridge
    ipMain.link_down(pvdIfIndex)
    ipMain.flush_addr(pvdIfIndex)

    # Make a bridge between PvD interface and one end of veth interface
    veth0Index = ipMain.link_lookup(ifname=veth0)[0]
    bridgeIndex = ipMain.link_lookup(ifname=bridge)[0]
    ipMain.link('set', index=veth0Index, master=bridgeIndex)
    ipMain.link('set', index=pvdIfIndex, master=bridgeIndex)

    # Activate bridge and connected interfaces
    ipMain.link_up(pvdIfIndex)
    ipMain.link_up(veth0Index)
    ipMain.link_up(bridgeIndex)
    ipPvd.link_up(veth1Index)

    # Configure bridge and another end of the veth interface with PvD-related network parameters + add routes
    ipMain.flush_routes()
    ipPvd.flush_routes()
    for address in pvdAddresses:
        ipAddress = broadcastAddress = netmask = addrFamily = None
        for attr in address['attrs']:
            if attr[0] == 'IFA_ADDRESS':
                ipAddress = attr[1]
            if attr[0] == 'IFA_BROADCAST':
                broadcastAddress = attr[1]
        netmask = address['prefixlen']
        addrFamily = address['family']
        # Configure bridge
        try:
            ipMain.addr('add', index=bridgeIndex, family=addrFamily, address=ipAddress, broadcast=broadcastAddress, mask=netmask)
        except:
            pass
        # Configure veth
        try:
            ipPvd.addr('add', index=veth1Index, family=addrFamily, address=ipAddress, broadcast=broadcastAddress, mask=netmask)
        except:
            pass
        # Configure routes
        # Some routes are added during interface IP address/netmask configuration, skip them if already there
        ipNetwork = IPNetwork(ipAddress + '/' + str(netmask))
        try:
            ipMain.route('add', dst=str(ipNetwork.network), mask=netmask, oif=bridgeIndex, src=ipAddress, rtproto='RTPROT_STATIC', rtscope='RT_SCOPE_LINK')
        except:
            pass
        try:
            ipPvd.route('add', dst=str(ipNetwork.network), mask=netmask, oif=veth1Index, src=ipAddress, rtproto='RTPROT_STATIC', rtscope='RT_SCOPE_LINK')
        except:
            pass

    # Fing gateway(s) and add default routes
    defGateways = []
    for route in pvdRoutes:
        for attr in route['attrs']:
            if (attr[0] == 'RTA_GATEWAY' and attr[1] not in defGateways):
#.........这里部分代码省略.........
开发者ID:dskvorc,项目名称:misc,代码行数:103,代码来源:pvdtest_veth.py


注:本文中的pyroute2.IPRoute.link_create方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。