예제 #1
0
    def test_move_ns_fd(self):
        foo = str(uuid4())
        bar = str(uuid4())
        ifA = uifname()
        ifB = uifname()
        netnsmod.create(foo)
        netnsmod.create(bar)

        with IPDB(nl=NetNS(foo)) as ip:
            ip.create(ifname=ifA, kind='veth', peer=ifB).commit()
            assert ifA in ip.interfaces.keys()
            assert ifB in ip.interfaces.keys()
            with ip.interfaces[ifB] as intf:
                intf.net_ns_fd = bar
            assert ifA in ip.interfaces.keys()
            assert ifB not in ip.interfaces.keys()

        with IPDB(nl=NetNS(bar)) as ip:
            assert ifA not in ip.interfaces.keys()
            assert ifB in ip.interfaces.keys()
            ip.interfaces[ifB].remove().commit()
            assert ifA not in ip.interfaces.keys()
            assert ifB not in ip.interfaces.keys()

        with IPDB(nl=NetNS(foo)) as ip:
            assert ifA not in ip.interfaces.keys()
            assert ifB not in ip.interfaces.keys()

        netnsmod.remove(foo)
        netnsmod.remove(bar)
예제 #2
0
    def test_connect_netns(self):
        nsname = str(uuid.uuid4())
        with self.ndb.readonly:
            s = len(list(self.ndb.interfaces.summary()))
            assert self.count_interfaces(nsname) == 0
            assert self.count_interfaces('localhost') <= s

        # connect RTNL source
        event = threading.Event()
        self.ndb.sources.add(**{'target': nsname,
                                'kind': 'netns',
                                'netns': nsname,
                                'event': event})
        assert event.wait(5)

        with self.ndb.readonly:
            s = len(list(self.ndb.interfaces.summary()))
            assert self.count_interfaces(nsname) > 0
            assert self.count_interfaces('localhost') < s

        # disconnect the source
        self.ndb.sources[nsname].close()
        with self.ndb.readonly:
            s = len(list(self.ndb.interfaces.summary()))
            assert self.count_interfaces(nsname) == 0
            assert self.count_interfaces('localhost') <= s

        netns.remove(nsname)
예제 #3
0
    def test_connect_netns(self):
        nsname = str(uuid.uuid4())
        with self.ndb.readonly:
            s = len(list(self.ndb.interfaces.summary()))
            assert self.count_interfaces(nsname) == 0
            assert self.count_interfaces('localhost') == s

        # connect RTNL source
        event = threading.Event()
        self.ndb.sources.add(**{'target': nsname,
                                'kind': 'netns',
                                'netns': nsname,
                                'event': event})
        assert event.wait(5)

        with self.ndb.readonly:
            s = len(list(self.ndb.interfaces.summary()))
            assert self.count_interfaces(nsname) > 0
            assert self.count_interfaces('localhost') < s

        # disconnect the source
        self.ndb.sources[nsname].close()
        with self.ndb.readonly:
            s = len(list(self.ndb.interfaces.summary()))
            assert self.count_interfaces(nsname) == 0
            assert self.count_interfaces('localhost') == s

        netns.remove(nsname)
예제 #4
0
    def test_create_peer_attrs(self):
        foo = str(uuid4())
        bar = str(uuid4())
        ifA = uifname()
        ifB = uifname()
        netnsmod.create(foo)
        netnsmod.create(bar)

        with IPDB(nl=NetNS(foo)) as ip:
            ip.create(ifname=ifA,
                      kind='veth',
                      peer={'ifname': ifB,
                            'net_ns_fd': bar}).commit()
            assert ifA in ip.interfaces.keys()
            assert ifB not in ip.interfaces.keys()

        with IPDB(nl=NetNS(bar)) as ip:
            assert ifA not in ip.interfaces.keys()
            assert ifB in ip.interfaces.keys()
            ip.interfaces[ifB].remove().commit()
            assert ifA not in ip.interfaces.keys()
            assert ifB not in ip.interfaces.keys()

        with IPDB(nl=NetNS(foo)) as ip:
            assert ifA not in ip.interfaces.keys()
            assert ifB not in ip.interfaces.keys()

        netnsmod.remove(foo)
        netnsmod.remove(bar)
예제 #5
0
    def test_connect_netns(self):
        nsname = str(uuid.uuid4())
        self.ndb.schema.allow_write(False)
        s = len(list(self.ndb.interfaces.summary()))
        assert self.count_interfaces(nsname) == 0
        assert self.count_interfaces('localhost') == s
        self.ndb.schema.allow_write(True)

        # connect RTNL source
        event = threading.Event()
        self.ndb.sources.add(**{'target': nsname,
                                'kind': 'netns',
                                'netns': nsname,
                                'event': event})
        assert event.wait(5)

        self.ndb.schema.allow_write(False)
        s = len(list(self.ndb.interfaces.summary()))
        assert self.count_interfaces(nsname) > 0
        assert self.count_interfaces('localhost') < s
        self.ndb.schema.allow_write(True)

        # disconnect the source
        self.ndb.sources[nsname].close()
        self.ndb.schema.allow_write(False)
        s = len(list(self.ndb.interfaces.summary()))
        assert self.count_interfaces(nsname) == 0
        assert self.count_interfaces('localhost') == s
        self.ndb.schema.allow_write(True)

        netns.remove(nsname)
예제 #6
0
    def test_move_ns_pid(self):
        foo = str(uuid4())
        bar = str(uuid4())
        ifA = uifname()
        netnsmod.create(foo)
        netnsmod.create(bar)

        ns_foo = IPDB(nl=NetNS(foo))
        ns_bar = IPDB(nl=NetNS(bar))

        try:
            ns_foo.create(ifname=ifA, kind='dummy').commit()
            with ns_foo.interfaces[ifA] as iface:
                iface.net_ns_pid = ns_bar.nl.server.pid

            assert ifA in ns_bar.interfaces.keys()
            assert ifA not in ns_foo.interfaces.keys()

            with ns_bar.interfaces[ifA] as iface:
                iface.net_ns_pid = ns_foo.nl.server.pid

            assert ifA not in ns_bar.interfaces.keys()
            assert ifA in ns_foo.interfaces.keys()

        finally:
            ns_foo.release()
            ns_bar.release()
            netnsmod.remove(foo)
            netnsmod.remove(bar)
예제 #7
0
 def teardown(self):
     with NDB() as indb:
         if self.nsname:
             (indb
              .sources
              .add(netns=self.nsname))
         for link in reversed(self.interfaces):
             try:
                 (indb
                  .interfaces[link]
                  .remove()
                  .commit())
             except Exception:
                 pass
         for link in reversed(self.interfaces):
             try:
                 (indb
                  .interfaces[self.getspec(ifname=link)]
                  .remove()
                  .commit())
             except Exception:
                 pass
     self.ndb.close()
     for net in self.ipnets:
         free_network(net)
     if self.nsname:
         netns.remove(self.nsname)
예제 #8
0
    def test_connect_netns(self):
        nsname = str(uuid.uuid4())
        with self.ndb.schema.db_lock:
            s = len(self.ndb.interfaces.summary()) - 1
            assert self.count_interfaces(nsname) == 0
            assert self.count_interfaces('localhost') == s

        # connect RTNL source
        event = threading.Event()
        self.ndb.connect_source(nsname, NetNS(nsname), event)
        assert event.wait(5)

        with self.ndb.schema.db_lock:
            s = len(self.ndb.interfaces.summary()) - 1
            assert self.count_interfaces(nsname) > 0
            assert self.count_interfaces('localhost') < s

        # disconnect the source
        self.ndb.disconnect_source(nsname)
        with self.ndb.schema.db_lock:
            s = len(self.ndb.interfaces.summary()) - 1
            assert self.count_interfaces(nsname) == 0
            assert self.count_interfaces('localhost') == s

        netns.remove(nsname)
예제 #9
0
파일: daemon.py 프로젝트: veksev/capd
def setup_vnets(n_nets=3):
    vnets = list()
    for i in map(str, range(0, n_nets)):
        try:
            vns = IPDB(nl=NetNS('capdnet'+i, flags=os.O_CREAT | os.O_EXCL))
        except OSError:
            netns.remove('capdnet'+i)
            vns = IPDB(nl=NetNS('capdnet'+i, flags=os.O_CREAT | os.O_EXCL))

        try:
            os.symlink(RUNDIR+'/defaults', '/etc/netns/capdnet'+i)
        except OSError:
            # some other day.
            pass
        vns.interfaces.lo.up().commit()
        with ip.create(ifname='capd0peer'+i, kind='veth', peer='veth0') as dev:
            dev.master = ip.interfaces['capd0'].index
            dev.up()
        ip.interfaces['veth0'].net_ns_fd = vns.nl.netns
        ip.interfaces['veth0'].commit()
        with vns.interfaces['veth0'] as dev:
            dev.address = 'e0:00:00:00:00:00'
            dev.add_ip('10.0.1.{}/8'.format(i))  # gonna break if > 253 threads
            dev.up()
        vns.routes.add({'dst': '0.0.0.0', 'mask': 0, 'gateway': '10.255.255.254'}).commit()
        vnets.append(vns)
    return vnets
예제 #10
0
    def test_connect_netns(self):
        nsname = str(uuid.uuid4())
        with self.ndb.schema.db_lock:
            s = len(self.ndb.interfaces.summary()) - 1
            assert self.count_interfaces(nsname) == 0
            assert self.count_interfaces('localhost') == s

        # connect RTNL source
        event = threading.Event()
        self.ndb.connect_source(nsname, NetNS(nsname), event)
        assert event.wait(5)

        with self.ndb.schema.db_lock:
            s = len(self.ndb.interfaces.summary()) - 1
            assert self.count_interfaces(nsname) > 0
            assert self.count_interfaces('localhost') < s

        # disconnect the source
        self.ndb.disconnect_source(nsname)
        with self.ndb.schema.db_lock:
            s = len(self.ndb.interfaces.summary()) - 1
            assert self.count_interfaces(nsname) == 0
            assert self.count_interfaces('localhost') == s

        netns.remove(nsname)
예제 #11
0
    def test_multithread(self):
        require_user('root')

        parallel_count = 5
        test_count = 10

        ns_names = ['testns%i' % i for i in range(parallel_count)]

        success = [True]

        for ns_name in ns_names:
            NetNS(ns_name)

        for _t in range(test_count):
            threads = [
                Thread(target=_ns_worker,
                       args=(netnsmod._get_netnspath(ns_name), i, success))
                for i, ns_name in enumerate(ns_names)
            ]
            for thread in threads:
                thread.start()
            for thread in threads:
                thread.join()

        for ns_name in ns_names:
            netnsmod.remove(ns_name)

        assert success[0]
예제 #12
0
    def test_move_ns_fd(self):
        foo = str(uuid4())
        bar = str(uuid4())
        ifA = uifname()
        ifB = uifname()
        netnsmod.create(foo)
        netnsmod.create(bar)

        with IPDB(nl=NetNS(foo)) as ip:
            ip.create(ifname=ifA, kind='veth', peer=ifB).commit()
            assert ifA in ip.interfaces.keys()
            assert ifB in ip.interfaces.keys()
            with ip.interfaces[ifB] as intf:
                intf.net_ns_fd = bar
            assert ifA in ip.interfaces.keys()
            assert ifB not in ip.interfaces.keys()

        with IPDB(nl=NetNS(bar)) as ip:
            assert ifA not in ip.interfaces.keys()
            assert ifB in ip.interfaces.keys()
            ip.interfaces[ifB].remove().commit()
            assert ifA not in ip.interfaces.keys()
            assert ifB not in ip.interfaces.keys()

        with IPDB(nl=NetNS(foo)) as ip:
            assert ifA not in ip.interfaces.keys()
            assert ifB not in ip.interfaces.keys()

        netnsmod.remove(foo)
        netnsmod.remove(bar)
예제 #13
0
    def test_multithread(self):
        require_user('root')

        parallel_count = 5
        test_count = 10

        ns_names = ['testns%i' % i for i in range(parallel_count)]

        success = [True]

        for ns_name in ns_names:
            NetNS(ns_name)

        for _t in range(test_count):
            threads = [
                Thread(target=_ns_worker,
                       args=(netnsmod._get_netnspath(ns_name), i, success))
                for i, ns_name in enumerate(ns_names)]
            for thread in threads:
                thread.start()
            for thread in threads:
                thread.join()

        for ns_name in ns_names:
            netnsmod.remove(ns_name)

        assert success[0]
예제 #14
0
    def test_create_peer_attrs(self):
        foo = str(uuid4())
        bar = str(uuid4())
        ifA = uifname()
        ifB = uifname()
        netnsmod.create(foo)
        netnsmod.create(bar)

        with IPDB(nl=NetNS(foo)) as ip:
            ip.create(ifname=ifA,
                      kind='veth',
                      peer={
                          'ifname': ifB,
                          'net_ns_fd': bar
                      }).commit()
            assert ifA in ip.interfaces.keys()
            assert ifB not in ip.interfaces.keys()

        with IPDB(nl=NetNS(bar)) as ip:
            assert ifA not in ip.interfaces.keys()
            assert ifB in ip.interfaces.keys()
            ip.interfaces[ifB].remove().commit()
            assert ifA not in ip.interfaces.keys()
            assert ifB not in ip.interfaces.keys()

        with IPDB(nl=NetNS(foo)) as ip:
            assert ifA not in ip.interfaces.keys()
            assert ifB not in ip.interfaces.keys()

        netnsmod.remove(foo)
        netnsmod.remove(bar)
예제 #15
0
    def test_move_ns_pid(self):
        foo = str(uuid4())
        bar = str(uuid4())
        ifA = uifname()
        netnsmod.create(foo)
        netnsmod.create(bar)

        ns_foo = IPDB(nl=NetNS(foo))
        ns_bar = IPDB(nl=NetNS(bar))

        try:
            ns_foo.create(ifname=ifA, kind='dummy').commit()
            with ns_foo.interfaces[ifA] as iface:
                iface.net_ns_pid = ns_bar.nl.server.pid

            assert ifA in ns_bar.interfaces.keys()
            assert ifA not in ns_foo.interfaces.keys()

            with ns_bar.interfaces[ifA] as iface:
                iface.net_ns_pid = ns_foo.nl.server.pid

            assert ifA not in ns_bar.interfaces.keys()
            assert ifA in ns_foo.interfaces.keys()

        finally:
            ns_foo.release()
            ns_bar.release()
            netnsmod.remove(foo)
            netnsmod.remove(bar)
예제 #16
0
    def test_veth_spec(self):
        ifname = uifname()
        peername = uifname()
        nsname = str(uuid.uuid4())

        (self
         .ndb
         .sources
         .add(netns=nsname))

        spec = self.getspec(**{'ifname': ifname,
                               'kind': 'veth',
                               'peer': {'ifname': peername,
                                        'address': '00:11:22:33:44:55',
                                        'net_ns_fd': nsname}})
        (self
         .ndb
         .interfaces
         .create(**spec)
         .commit())

        (self
         .ndb
         .interfaces
         .wait(target=nsname, ifname=peername))

        iflink = (self
                  .ndb
                  .interfaces[self.getspec(ifname=ifname)]['link'])
        plink = (self
                 .ndb
                 .interfaces[{'target': nsname,
                              'ifname': peername}]['link'])

        assert iflink == (self
                          .ndb
                          .interfaces[{'target': nsname,
                                       'ifname': peername}]['index'])
        assert plink == (self
                         .ndb
                         .interfaces[self.getspec(ifname=ifname)]['index'])
        assert grep('%s ip link show' % self.ssh, pattern=ifname)
        assert not grep('%s ip link show' % self.ssh, pattern=peername)

        (self
         .ndb
         .interfaces[self.getspec(ifname=ifname)]
         .remove()
         .commit())

        assert not grep('%s ip link show' % self.ssh, pattern=ifname)
        assert not grep('%s ip link show' % self.ssh, pattern=peername)

        (self
         .ndb
         .sources
         .remove(nsname))

        netns.remove(nsname)
예제 #17
0
    def remove(self):
        '''
        Try to remove this network namespace from the system.

        This call be be ran only after `NetNS.close()`, otherwise
        it will fail.
        '''
        remove(self.netns)
예제 #18
0
    def _delete_namespace(self, namespace):
        ns = NetNS(namespace)

        bridge = ns.link_lookup(ifname='shoutbr0')[0]
        ns.link('set', index=bridge, state='down')
        ns.link('del', index=bridge)

        ns.close()
        netns.remove(namespace)
예제 #19
0
 def destroy(self):
     """
     Removes all objects created for the virtual node.
     """
     try:
         netns.remove(self.namespace)
     except:
         # Namespace doesn't exist. Return silently.
         pass
예제 #20
0
파일: ip_lib.py 프로젝트: igordcard/neutron
def remove_netns(name, **kwargs):
    """Remove a network namespace.

    :param name: The name of the namespace to remove
    """
    try:
        netns.remove(name, **kwargs)
    except OSError as e:
        if e.errno != errno.ENOENT:
            raise
예제 #21
0
 def _remove_namespace_if_exists(self, name):
     """
     If the given namespace exists, removes it. Otherwise just returns
     silently.
     """
     try:
         netns.remove(name)
     except:
         # Namespace doesn't exist. Return silently.
         pass
예제 #22
0
 def destroy(self):
     """
     Removes all objects created for the virtual node.
     """
     _remove_interface_if_exists(self.vethPeer)
     try:
         netns.remove(self.namespace)
     except:
         # Namespace doesn't exist. Return silently.
         pass
예제 #23
0
 def test_auto_netns(self):
     newns = str(uuid.uuid4())
     assert self.ndb.interfaces.count() > 0
     assert len(tuple(self
                      .ndb
                      .interfaces
                      .summary(match={'target': 'netns/%s' % newns}))) == 0
     netns.create(newns)
     self.ndb.interfaces.wait(**{'target': 'netns/%s' % newns})
     netns.remove(newns)
예제 #24
0
파일: ip_lib.py 프로젝트: jahau/neutron
def remove_netns(name, **kwargs):
    """Remove a network namespace.

    :param name: The name of the namespace to remove
    """
    try:
        netns.remove(name, libc=_get_cdll())
    except OSError as e:
        if e.errno != errno.ENOENT:
            raise
예제 #25
0
def remove_netns(name, **kwargs):
    """Remove a network namespace.

    :param name: The name of the namespace to remove
    """
    try:
        netns.remove(name, libc=priv_linux.get_cdll())
    except OSError as e:
        if e.errno != errno.ENOENT:
            raise
    LOG.debug("Namespace %s deleted.", name)
예제 #26
0
파일: ppServer.py 프로젝트: Inmarsat/tcc
def deleteService(data):
    name = data['name']
    customer = data['customer']
    vr = data['virtualrouter']
    svcId = data['Id']
    if 'move' in data:
        move = data['move']
    else:
        move = False
    if 'delvn' in data:
        delvn = data['delvn']
    else:
        delvn = False
    print vr
    print name + '_' + str(svcId)
    lif = getLogicalInterface(vr, name + '_' + str(svcId))
    if lif.get_virtual_machine_interface_refs() and not move:
        for vmInt in lif.get_virtual_machine_interface_refs():
            vmIntObj = vnc_client.virtual_machine_interface_read(id = vmInt['uuid'])
            if vmIntObj.get_instance_ip_back_refs():
                for instIp in vmIntObj.get_instance_ip_back_refs():
                    instIpObj = vnc_client.instance_ip_read(id = instIp['uuid'])
                    vnc_client.instance_ip_delete(id = instIp['uuid'])
            if vmIntObj.get_logical_interface_back_refs():
                for logicalInterface in vmIntObj.get_logical_interface_back_refs():
                    logInt = vnc_client.logical_interface_read(id = logicalInterface['uuid'])
                logInt.del_virtual_machine_interface(vmIntObj)
                vnc_client.logical_interface_update(logInt)
            vnc_client.virtual_machine_interface_delete(id = vmIntObj.get_uuid())
    vnc_client.logical_interface_delete(id = lif.get_uuid())
    if not move:
        vn = getVirtualNetwork(customer, name)
        if delvn:
            vnc_client.virtual_network_delete(id = vn.get_uuid())
    p = subprocess.Popen(['ip','netns','pids',name + '_' + str(svcId)], stdout=subprocess.PIPE)
    out, err = p.communicate()
    for line in out.splitlines():
        print line
        pid = int(line)
        try:
            os.kill(pid, signal.SIGKILL) 
        except:
            print 'nothing to kill'
    netns.remove(name + '_' + str(svcId))
    ip_host = IPDB()
    if name + '_' + str(svcId) in ip_host.interfaces:
        with ip_host.interfaces[name + '_' + str(svcId)] as veth:
            veth.remove()
    subprocess.call(["ovs-vsctl", "del-port", "br0", name + '_' + str(svcId)])
    if not move:
        if delvn:
            os.remove('/mnt/' + name + '.lease')
    return json.dumps({ 'status' : 'deleted service'})
예제 #27
0
 def test_create_from_path(self):
     ns_dir = tempfile.mkdtemp()
     # Create namespace
     ns_name = str(uuid4())
     nspath = '%s/%s' % (ns_dir, ns_name)
     temp_ns = NetNS(nspath)
     temp_ns.close()
     fd = open(nspath)
     self._test_create(nspath, fd.fileno())
     fd.close()
     netnsmod.remove(nspath)
     assert ns_name not in netnsmod.listnetns()
     assert ns_name not in netnsmod.listnetns(ns_dir)
예제 #28
0
 def test_create_from_path(self):
     ns_dir = tempfile.mkdtemp()
     # Create namespace
     ns_name = str(uuid4())
     nspath = '%s/%s' % (ns_dir, ns_name)
     temp_ns = NetNS(nspath)
     temp_ns.close()
     fd = open(nspath)
     self._test_create(nspath, fd.fileno())
     fd.close()
     netnsmod.remove(nspath)
     assert ns_name not in netnsmod.listnetns()
     assert ns_name not in netnsmod.listnetns(ns_dir)
예제 #29
0
    def test_create(self):
        require_user('root')

        nsid = str(uuid4())
        ipdb_main = IPDB()
        ipdb_test = IPDB(nl=NetNS(nsid))
        if1 = uifname()
        if2 = uifname()

        # create VETH pair
        ipdb_main.create(ifname=if1, kind='veth', peer=if2).commit()

        # move the peer to netns
        with ipdb_main.interfaces[if2] as veth:
            veth.net_ns_fd = nsid

        # assign addresses
        with ipdb_main.interfaces[if1] as veth:
            veth.add_ip('172.16.200.1/24')
            veth.up()

        with ipdb_test.interfaces[if2] as veth:
            veth.add_ip('172.16.200.2/24')
            veth.up()

        # ping peer
        try:
            with open('/dev/null', 'w') as fnull:
                subprocess.check_call(['ping', '-c', '1', '172.16.200.2'],
                                      stdout=fnull,
                                      stderr=fnull)
            ret_ping = True
        except Exception:
            ret_ping = False

        # check ARP
        time.sleep(0.5)
        ret_arp = '172.16.200.1' in list(ipdb_test.interfaces[if2].neighbours)
        # ret_arp = list(ipdb_test.interfaces.v0p1.neighbours)

        # cleanup
        ipdb_main.interfaces[if1].remove().commit()
        ipdb_main.release()
        ipdb_test.release()
        netnsmod.remove(nsid)

        assert ret_ping
        assert ret_arp
        assert nsid not in netnsmod.listnetns()
예제 #30
0
 def remove(self, path):
     netnspath = netns._get_netnspath(path)
     info = None
     try:
         info = self.ipr._dump_one_ns(netnspath, set())
     except SkipInode:
         raise NetlinkError(errno.EEXIST)
     info['header']['type'] = RTM_DELNETNS
     info['event'] = 'RTM_DELNETNS'
     del info['value']
     try:
         netns.remove(netnspath, self.libc)
     except OSError as e:
         raise NetlinkError(e.errno)
     return info,
예제 #31
0
파일: nssetup.py 프로젝트: tum-lkn/appaware
def destroy_ns(ns_name):
    """
    Deletes a network namespace

    :param ns_name: The name of the network
    :return: Returns True of the namespace was deleted or did not exist.
    """

    if ns_name not in netns.listnetns():
        log.warning("Namespace %s not found! Doing nothing." % ns_name)
        return True

    netns.remove(ns_name)

    return True
예제 #32
0
    def test_create(self):
        require_user('root')

        nsid = str(uuid4())
        ipdb_main = IPDB()
        ipdb_test = IPDB(nl=NetNS(nsid))
        if1 = uifname()
        if2 = uifname()

        # create VETH pair
        ipdb_main.create(ifname=if1, kind='veth', peer=if2).commit()

        # move the peer to netns
        with ipdb_main.interfaces[if2] as veth:
            veth.net_ns_fd = nsid

        # assign addresses
        with ipdb_main.interfaces[if1] as veth:
            veth.add_ip('172.16.200.1/24')
            veth.up()

        with ipdb_test.interfaces[if2] as veth:
            veth.add_ip('172.16.200.2/24')
            veth.up()

        # ping peer
        try:
            with open('/dev/null', 'w') as fnull:
                subprocess.check_call(['ping', '-c', '1', '172.16.200.2'],
                                      stdout=fnull, stderr=fnull)
            ret_ping = True
        except Exception:
            ret_ping = False

        # check ARP
        time.sleep(0.5)
        ret_arp = '172.16.200.1' in list(ipdb_test.interfaces[if2].neighbours)
        # ret_arp = list(ipdb_test.interfaces.v0p1.neighbours)

        # cleanup
        ipdb_main.interfaces[if1].remove().commit()
        ipdb_main.release()
        ipdb_test.release()
        netnsmod.remove(nsid)

        assert ret_ping
        assert ret_arp
        assert nsid not in netnsmod.listnetns()
예제 #33
0
 def test_attach(self):
     ns_name = str(uuid4())
     pid = os.fork()
     if pid == 0:
         # child
         while True:
             time.sleep(.1)
     else:
         # parent
         try:
             self._test_create(ns_name, pid=pid)
         finally:
             os.kill(int(pid), signal.SIGTERM)
             os.waitpid(pid, 0)
     netnsmod.remove(ns_name)
     assert ns_name not in netnsmod.listnetns()
예제 #34
0
 def remove(self):
     """
     Removes the Namespace and all included Network-Interfaces.
     """
     logging.debug("%sDelete Namespace ...", LoggerSetup.get_log_deep(2))
     try:
         netns.remove(self.nsp_name)
         self.ipdb_netns.release()
         logging.debug("%s[+] Namespace(" + self.nsp_name + ") successfully deleted", LoggerSetup.get_log_deep(3))
     except Exception as e:
         if re.match("\[Errno 2\]*", str(e)):
             logging.debug("%s[+] Namespace(" + self.nsp_name + ") is already deleted", LoggerSetup.get_log_deep(3))
             return
         logging.error("%s[-] Namespace(" + self.nsp_name +
                       ") couldn't be deleted. Try 'ip netns delete <namespace_name>'", LoggerSetup.get_log_deep(3))
         logging.error("%s" + str(e), LoggerSetup.get_log_deep(3))
예제 #35
0
def deleteEndpoint(name, svcName, endpointtype):
    if endpointtype == 'ns':
        nsp = NSPopen(name, ['dhclient', '-r', name], stdout=subprocess.PIPE)
        nsp.wait()
        nsp.release()
        netns.remove(name)
        ip_host = IPDB()
        if name + '_' + svcName in ip_host.interfaces:
            with ip_host.interfaces[name + '_' + svcName] as veth:
                veth.remove()
        subprocess.call(["ovs-vsctl", "del-port", "vs-" + svcName, name + '_' + svcName])
    if endpointtype == 'lxc':
        subprocess.call(['/usr/bin/lxc-stop','-n',name])
        subprocess.call(['/usr/bin/lxc-destroy','-n',name])
        pass
    return json.dumps({ 'status' : 'deleted endpoint'})
예제 #36
0
    def delete_container(self,compute):

        inspect = self.client.inspect_container(compute.get_compute_name())
        PID = inspect['State']['Pid']
        self.client.stop(compute.get_compute_name())
        self.client.remove_container(compute.get_compute_name())
        netns.remove(str(PID))

        id_veth=0

        """Remove veth interfaces to OpenvSwitch bridges"""

        for ipaddress in compute.get_compute_ipaddresses():
            veth1='vl-'+str(id_veth)+'-'+str(PID)
            subprocess.check_output(["sudo", "ovs-vsctl", "del-port", "br-" + ipaddress.get_net_name(), veth1])
            id_veth = id_veth + 1
        return 1
예제 #37
0
  def __removePvd(self, phyIfaceName, pvdId):
    pvd = self.pvds.get((phyIfaceName, pvdId))
    if (pvd):
      # remove the network namespace associated with the PvD (this in turn removes the PvD network configuration as well)
      if (pvd.netnsName in netns.listnetns()):
        netns.remove(pvd.netnsName)
      # remove the directory containing PvD-related DNS information
      (dnsConfDir, dnsConfFile) = self.__getDnsConfPath(pvd.netnsName)
      if (os.path.exists(dnsConfDir)):
        shutil.rmtree(dnsConfDir, True)
      # remove the PvD record from the PvD manager's log
      del self.pvds[(phyIfaceName, pvdId)]
      LOG.info('PvD {0} received through {1} REMOVED, network namespace {2} deleted, DNS directory {3} deleted, type {4}'.format(pvd.pvdId, pvd.phyIfaceName, pvd.netnsName, dnsConfDir, pvd.pvdInfo.pvdType))
      self.pvdserver.stateChanged ("deleted", pvdId)

    else:
      raise Exception('There is no PvD {0} configured on {1}'.format(pvdInfo.pvdId, phyIfaceName))
예제 #38
0
 def setup(self):
     require_user('root')
     try:
         netns.create(NS_NAME)
     except OSError as e:
         if e.errno == errno.EEXIST:
             netns.remove(NS_NAME)
             netns.create(NS_NAME)
         else:
             raise
     try:
         check_output([NFT_BIN_PATH, "-f", "nftables.ruleset"])
     except OSError as e:
         if e.errno == errno.ENOENT:
             raise SkipTest("You must install nftables for the test")
         else:
             raise
예제 #39
0
 def setup(self):
     require_user('root')
     try:
         netns.create(NS_NAME)
     except OSError as e:
         if e.errno == errno.EEXIST:
             netns.remove(NS_NAME)
             netns.create(NS_NAME)
         else:
             raise
     try:
         check_output([NFT_BIN_PATH, "-f", "nftables.ruleset"])
     except OSError as e:
         if e.errno == errno.ENOENT:
             raise SkipTest("You must install nftables for the test")
         else:
             raise
예제 #40
0
파일: mocker.py 프로젝트: Nikeliza/pr1
def mocker_rm(uuid1):
    '''+
    rm <container_id> - удаляет ранее
    созданный контейнер
    '''
    if uuid1[0:3] == "ps_":
        if mocker_check(uuid1) == 1:
            print('No container named ' + str(uuid1))
            return
        btrfsutil.delete_subvolume(btrfs_path + '/' + str(uuid1))
        cg = Cgroup(uuid1)
        cg.delete()
        netns_name = 'netns_' + str(uuid1)
        netns.remove(netns_name)
        print('Removed ' + str(uuid1))
    else:
        print('This is not container')
예제 #41
0
def deleteEndpoint(name, svcName, endpointtype):
    if endpointtype == 'ns':
        nsp = NSPopen(name, ['dhclient', '-r', name], stdout=subprocess.PIPE)
        nsp.wait()
        nsp.release()
        netns.remove(name)
        ip_host = IPDB()
        if name + '_' + svcName in ip_host.interfaces:
            with ip_host.interfaces[name + '_' + svcName] as veth:
                veth.remove()
        subprocess.call(
            ["ovs-vsctl", "del-port", "vs-" + svcName, name + '_' + svcName])
    if endpointtype == 'lxc':
        subprocess.call(['/usr/bin/lxc-stop', '-n', name])
        subprocess.call(['/usr/bin/lxc-destroy', '-n', name])
        pass
    return json.dumps({'status': 'deleted endpoint'})
예제 #42
0
    def test_create_tuntap(self):
        # actually this test checks the nlsocket plugin feedback
        # in a pair of remote client/server
        foo = str(uuid4())
        tun = uifname()
        tap = uifname()

        with IPDB(nl=NetNS(foo)) as ip:
            ip.create(ifname=tun, kind='tuntap', mode='tun').commit()
            ip.create(ifname=tap, kind='tuntap', mode='tap').commit()
            assert tun in ip.interfaces.keys()
            assert tap in ip.interfaces.keys()
            ip.interfaces[tun].remove().commit()
            ip.interfaces[tap].remove().commit()
            assert tun not in ip.interfaces.keys()
            assert tap not in ip.interfaces.keys()

        netnsmod.remove(foo)
예제 #43
0
    def test_rename_plus_ipv6(self):
        require_user('root')

        mtu = 1280  # mtu must be >= 1280 if you plan to use IPv6
        txqlen = 2000
        nsid = str(uuid4())
        ipdb_main = IPDB()
        ipdb_test = IPDB(nl=NetNS(nsid))
        if1 = uifname()
        if2 = uifname()
        if3 = uifname()

        # create
        ipdb_main.create(kind='veth',
                         ifname=if1,
                         peer=if2,
                         mtu=mtu,
                         txqlen=txqlen).commit()

        # move
        with ipdb_main.interfaces[if2] as veth:
            veth.net_ns_fd = nsid

        # set it up
        with ipdb_test.interfaces[if2] as veth:
            veth.add_ip('fdb3:84e5:4ff4:55e4::1/64')
            veth.add_ip('fdff:ffff:ffff:ffc0::1/64')
            veth.mtu = mtu
            veth.txqlen = txqlen
            veth.up()
            veth.ifname = if3

        veth = ipdb_test.interfaces.get(if3, None)
        ipdb_main.release()
        ipdb_test.release()
        netnsmod.remove(nsid)

        # check everything
        assert ('fdb3:84e5:4ff4:55e4::1', 64) in veth.ipaddr
        assert ('fdff:ffff:ffff:ffc0::1', 64) in veth.ipaddr
        assert veth.flags & 1
        assert veth.mtu == mtu
        assert veth.txqlen == txqlen
예제 #44
0
 def remove(self):
     """
     Removes the virtual namespace and interface.
     """
     Logger().debug("Delete Namespace ...", 2)
     try:
         if self.ipdb_netns is None:
             netns.remove(self.nsp_name)
         else:
             self.ipdb_netns.interfaces[self.vlan_iface_name].nl.remove()
             self.ipdb_netns.release()
         Logger().debug("[+] Namespace(" + self.nsp_name + ") successfully deleted", 3)
     except Exception as e:
         if re.match("\[Errno 2\]*",str(e)):
             Logger().debug("[+] Namespace(" + self.nsp_name + ") is already deleted", 3)
             return
         Logger().debug("[-] Namespace(" + self.nsp_name +
                        ") couldn't be deleted. Try 'ip netns delete <namespace_name>'", 3)
         Logger().error(str(e), 3)
예제 #45
0
    def test_rename_plus_ipv6(self):
        require_user('root')

        mtu = 1280  # mtu must be >= 1280 if you plan to use IPv6
        txqlen = 2000
        nsid = str(uuid4())
        ipdb_main = IPDB()
        ipdb_test = IPDB(nl=NetNS(nsid))
        if1 = uifname()
        if2 = uifname()
        if3 = uifname()

        # create
        ipdb_main.create(kind='veth',
                         ifname=if1,
                         peer=if2,
                         mtu=mtu,
                         txqlen=txqlen).commit()

        # move
        with ipdb_main.interfaces[if2] as veth:
            veth.net_ns_fd = nsid

        # set it up
        with ipdb_test.interfaces[if2] as veth:
            veth.add_ip('fdb3:84e5:4ff4:55e4::1/64')
            veth.add_ip('fdff:ffff:ffff:ffc0::1/64')
            veth.mtu = mtu
            veth.txqlen = txqlen
            veth.up()
            veth.ifname = if3

        veth = ipdb_test.interfaces.get(if3, None)
        ipdb_main.release()
        ipdb_test.release()
        netnsmod.remove(nsid)

        # check everything
        assert ('fdb3:84e5:4ff4:55e4::1', 64) in veth.ipaddr
        assert ('fdff:ffff:ffff:ffc0::1', 64) in veth.ipaddr
        assert veth.flags & 1
        assert veth.mtu == mtu
        assert veth.txqlen == txqlen
예제 #46
0
    def test_pushns(self):
        require_user('root')
        foo = str(uuid4())
        ifA = uifname()

        with IPRoute() as ipr:
            ipr.link('add', ifname=ifA, kind='dummy')

        netnsmod.pushns(foo)
        with IPRoute() as ipr:
            assert ifA not in [x.get_attr('IFLA_IFNAME') for x
                               in ipr.link('dump')]
        netnsmod.popns()
        with IPRoute() as ipr:
            assert ifA in [x.get_attr('IFLA_IFNAME') for x
                           in ipr.link('dump')]

            ipr.link('del', index=ipr.link_lookup(ifname=ifA)[0])

        netnsmod.remove(foo)
예제 #47
0
    def test_ns_pids(self):
        def waiting_child(fd):
            while True:
                if not os.read(fd, 32):
                    exit(0)

        require_user('root')
        foo = str(uuid4())
        netnsmod.create(foo)
        netnsmod.pushns(foo)
        foo_pid, foo_fd = os.forkpty()
        if not foo_pid:
            waiting_child(foo_fd)
        netnsmod.popns()

        pids = netnsmod.ns_pids()
        try:
            assert pids[foo] == [foo_pid]
        finally:
            os.close(foo_fd)
            netnsmod.remove(foo)
예제 #48
0
    def test_create_tuntap(self):
        # on CentOS 6.5 this test causes kernel panic
        if platform.linux_distribution()[:2] == ('CentOS', '6.5'):
            raise SkipTest('to avoid possible kernel panic')
        # actually this test checks the nlsocket plugin feedback
        # in a pair of remote client/server
        foo = str(uuid4())
        tun = uifname()
        tap = uifname()

        with IPDB(nl=NetNS(foo)) as ip:
            ip.create(ifname=tun, kind='tuntap', mode='tun').commit()
            ip.create(ifname=tap, kind='tuntap', mode='tap').commit()
            assert tun in ip.interfaces.keys()
            assert tap in ip.interfaces.keys()
            ip.interfaces[tun].remove().commit()
            ip.interfaces[tap].remove().commit()
            assert tun not in ip.interfaces.keys()
            assert tap not in ip.interfaces.keys()

        netnsmod.remove(foo)
예제 #49
0
파일: test_ipdb.py 프로젝트: abn/pyroute2
    def test_global_netns(self):
        require_user("root")

        ifA = self.get_ifname()
        ifB = self.get_ifname()
        ns = str(uuid.uuid4())

        with IPDB(nl=NetNS(ns)) as nsdb:
            v1 = self.ip.create(ifname="x" + ifA, kind="veth", peer=ifA)
            v2 = self.ip.create(ifname="x" + ifB, kind="veth", peer=ifB)
            if v1._mode == "explicit":
                v1.begin()
                v2.begin()
            v1.net_ns_fd = ns
            v2.net_ns_fd = ns
            self.ip.commit()
            nsdb.interfaces["x" + ifA].ifname = "eth0"
            nsdb.interfaces["x" + ifB].ifname = "eth1"
            nsdb.commit()
            if self.ip.interfaces[ifA]._mode == "explicit":
                self.ip.interfaces[ifA].begin()
                self.ip.interfaces[ifB].begin()
            self.ip.interfaces[ifA].up()
            self.ip.interfaces[ifB].up()
            self.ip.commit()

        assert "x" + ifA not in self.ip.interfaces
        assert "x" + ifB not in self.ip.interfaces
        assert ifA in self.ip.interfaces
        assert ifB in self.ip.interfaces
        assert self.ip.interfaces[ifA].flags & 1
        assert self.ip.interfaces[ifB].flags & 1

        if self.ip.interfaces[ifA]._mode == "explicit":
            self.ip.interfaces[ifA].begin()
            self.ip.interfaces[ifB].begin()
        self.ip.interfaces[ifA].remove()
        self.ip.interfaces[ifB].remove()
        self.ip.commit()
        netns.remove(ns)
예제 #50
0
 def test_there_and_back(self):
     require_user('root')
     # wait until the previous test's side effects are gone
     time.sleep(2)
     #
     fd = open('/proc/self/ns/net', 'r')
     foo = str(uuid4())
     #
     # please notice, that IPRoute / IPDB, started in a netns, will continue
     # to work in a given netns even if the process changes to another netns
     #
     with IPRoute() as ip:
         links_main1 = set([x.get('index', None) for x in ip.get_links()])
     netnsmod.setns(foo)
     with IPRoute() as ip:
         links_foo = set([x.get('index', None) for x in ip.get_links()])
     netnsmod.setns(fd)
     with IPRoute() as ip:
         links_main2 = set([x.get('index', None) for x in ip.get_links()])
     assert links_main1 == links_main2
     assert links_main1 != links_foo
     netnsmod.remove(foo)
     fd.close()
예제 #51
0
파일: run.py 프로젝트: jasondenning/mocker
    def run(self, *args, **kwargs):
        images = ImagesCommand().list_images()
        image_name = kwargs['<name>']
        ip_last_octet = 103 # TODO : configurable

        match = [i[3] for i in images if i[0] == image_name][0]

        target_file = os.path.join(_base_dir_, match)
        with open(target_file) as tf:
            image_details = json.loads(tf.read())
        # setup environment details
        state = json.loads(image_details['history'][0]['v1Compatibility'])

        # Extract information about this container
        env_vars = state['config']['Env']
        start_cmd = subprocess.list2cmdline(state['config']['Cmd'])
        working_dir = state['config']['WorkingDir']

        id = uuid.uuid1()

        # unique-ish name
        name = 'c_' + str(id.fields[5])[:4]

        # unique-ish mac
        mac = str(id.fields[5])[:2]

        layer_dir = os.path.join(_base_dir_, match.replace('.json', ''), 'layers', 'contents')

        with IPDB() as ipdb:
            veth0_name = 'veth0_'+name
            veth1_name = 'veth1_'+name
            netns_name = 'netns_'+name
            bridge_if_name = 'bridge0'

            existing_interfaces = ipdb.interfaces.keys()

            # Create a new virtual interface
            with ipdb.create(kind='veth', ifname=veth0_name, peer=veth1_name) as i1:
                i1.up()
                if bridge_if_name not in existing_interfaces:
                    ipdb.create(kind='bridge', ifname=bridge_if_name).commit()
                i1.set_target('master', bridge_if_name)

            # Create a network namespace
            netns.create(netns_name)

            # move the bridge interface into the new namespace
            with ipdb.interfaces[veth1_name] as veth1:
                veth1.net_ns_fd = netns_name

            # Use this network namespace as the database
            ns = IPDB(nl=NetNS(netns_name))
            with ns.interfaces.lo as lo:
                lo.up()
            with ns.interfaces[veth1_name] as veth1:
                veth1.address = "02:42:ac:11:00:{0}".format(mac)
                veth1.add_ip('10.0.0.{0}/24'.format(ip_last_octet))
                veth1.up()
            ns.routes.add({
                'dst': 'default',
                'gateway': '10.0.0.1'}).commit()

            try:
                # setup cgroup directory for this user
                user = os.getlogin()
                create_user_cgroups(user)

                # First we create the cgroup and we set it's cpu and memory limits
                cg = Cgroup(name)
                cg.set_cpu_limit(50)  # TODO : get these as command line options
                cg.set_memory_limit(500)

                # Then we a create a function to add a process in the cgroup
                def in_cgroup():
                    try:
                        pid = os.getpid()
                        cg = Cgroup(name)
                        for env in env_vars:
                            log.info('Setting ENV %s' % env)
                            os.putenv(*env.split('=', 1))

                        # Set network namespace
                        netns.setns(netns_name)

                        # add process to cgroup
                        cg.add(pid)

                        os.chroot(layer_dir)
                        if working_dir != '':
                            log.info("Setting working directory to %s" % working_dir)
                            os.chdir(working_dir)
                    except Exception as e:
                        traceback.print_exc()
                        log.error("Failed to preexecute function")
                        log.error(e)
                cmd = start_cmd
                log.info('Running "%s"' % cmd)
                process = subprocess.Popen(cmd, preexec_fn=in_cgroup, shell=True)
                process.wait()
                print(process.stdout)
                log.error(process.stderr)
            except Exception as e:
                traceback.print_exc()
                log.error(e)
            finally:
                log.info('Finalizing')
                NetNS(netns_name).close()
                netns.remove(netns_name)
                ipdb.interfaces[veth0_name].remove()
                log.info('done')
예제 #52
0
def remove_netns(name, **kwargs):
    """Remove a network namespace.

    :param name: The name of the namespace to remove
    """
    netns.remove(name, **kwargs)
예제 #53
0
 def teardown(self):
     netns.remove(NS_NAME)
예제 #54
0
 def remove(self):
     '''
     Try to remove this network namespace from the system.
     '''
     remove(self.netns)
예제 #55
0
 def teardown(self):
     self.ip.close()
     for ns in self.names:
         netnsmod.remove(ns)
예제 #56
0
 def test_create(self):
     ns_name = str(uuid4())
     self._test_create(ns_name)
     netnsmod.remove(ns_name)
     assert ns_name not in netnsmod.listnetns()