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


Python AddrPool.alloc方法代码示例

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


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

示例1: test_alloc_aligned

# 需要导入模块: from pyroute2.common import AddrPool [as 别名]
# 或者: from pyroute2.common.AddrPool import alloc [as 别名]
    def test_alloc_aligned(self):

        ap = AddrPool(minaddr=1, maxaddr=1024)
        for i in range(1024):
            ap.alloc()

        try:
            ap.alloc()
        except KeyError:
            pass
开发者ID:0x90,项目名称:pyroute2,代码行数:12,代码来源:test_addrpool.py

示例2: test_locate

# 需要导入模块: from pyroute2.common import AddrPool [as 别名]
# 或者: from pyroute2.common.AddrPool import alloc [as 别名]
    def test_locate(self):

        ap = AddrPool()
        f = ap.alloc()
        base1, bit1, is_allocated1 = ap.locate(f)
        base2, bit2, is_allocated2 = ap.locate(f + 1)

        assert base1 == base2
        assert bit2 == bit1 + 1
        assert is_allocated1
        assert not is_allocated2
        assert ap.allocated == 1
开发者ID:nazarewk,项目名称:pyroute2,代码行数:14,代码来源:test_addrpool.py

示例3: test_setaddr_allocated

# 需要导入模块: from pyroute2.common import AddrPool [as 别名]
# 或者: from pyroute2.common.AddrPool import alloc [as 别名]
    def test_setaddr_allocated(self):

        ap = AddrPool()
        f = ap.alloc()
        base, bit, is_allocated = ap.locate(f + 1)
        assert not is_allocated
        assert ap.allocated == 1
        ap.setaddr(f + 1, 'allocated')
        base, bit, is_allocated = ap.locate(f + 1)
        assert is_allocated
        assert ap.allocated == 2
        ap.free(f + 1)
        base, bit, is_allocated = ap.locate(f + 1)
        assert not is_allocated
        assert ap.allocated == 1
开发者ID:nazarewk,项目名称:pyroute2,代码行数:17,代码来源:test_addrpool.py

示例4: test_setaddr_free

# 需要导入模块: from pyroute2.common import AddrPool [as 别名]
# 或者: from pyroute2.common.AddrPool import alloc [as 别名]
    def test_setaddr_free(self):

        ap = AddrPool()
        f = ap.alloc()
        base, bit, is_allocated = ap.locate(f + 1)
        assert not is_allocated
        assert ap.allocated == 1
        ap.setaddr(f + 1, 'free')
        base, bit, is_allocated = ap.locate(f + 1)
        assert not is_allocated
        assert ap.allocated == 1
        ap.setaddr(f, 'free')
        base, bit, is_allocated = ap.locate(f)
        assert not is_allocated
        assert ap.allocated == 0
        try:
            ap.free(f)
        except KeyError:
            pass
开发者ID:nazarewk,项目名称:pyroute2,代码行数:21,代码来源:test_addrpool.py

示例5: NetlinkMixin

# 需要导入模块: from pyroute2.common import AddrPool [as 别名]
# 或者: from pyroute2.common.AddrPool import alloc [as 别名]

#.........这里部分代码省略.........
                        # for every turn separately
                        ctime = time.time()
                        #
                        current = self.buffer_queue.qsize()
                        delta = current - self.qsize
                        if delta > 10:
                            delay = min(3, max(0.01, float(current) / 60000))
                            message = ("Packet burst: the reader thread "
                                       "priority is increased, beware of "
                                       "delays on netlink calls\n\tCounters: "
                                       "delta=%s qsize=%s delay=%s "
                                       % (delta, current, delay))
                            if delay < 1:
                                log.debug(message)
                            else:
                                log.warning(message)
                            time.sleep(delay)
                        self.qsize = current

                        # We've got the data, lock the backlog again
                        self.backlog_lock.acquire()
                        for msg in msgs:
                            seq = msg['header']['sequence_number']
                            if seq not in self.backlog:
                                if msg['header']['type'] == NLMSG_ERROR:
                                    # Drop orphaned NLMSG_ERROR messages
                                    continue
                                seq = 0
                            # 8<-----------------------------------------------
                            # Callbacks section
                            for cr in self.callbacks:
                                try:
                                    if cr[0](msg):
                                        cr[1](msg, *cr[2])
                                except:
                                    log.warning("Callback fail: %s" % (cr))
                                    log.warning(traceback.format_exc())
                            # 8<-----------------------------------------------
                            self.backlog[seq].append(msg)
                        # We finished with the backlog, so release the lock
                        self.backlog_lock.release()

                        # Now wake up other threads
                        self.change_master.set()

                        # Finally, release the read lock: all data processed
                        self.read_lock.release()
                    else:
                        # If the socket is occupied and there is still no
                        # data for us, wait for the next master change or
                        # for a timeout
                        self.change_master.wait(1)
                    # 8<-------------------------------------------------------
                    #
                    # Stage 2. END
                    #
                    # 8<-------------------------------------------------------

            return ret

    def nlm_request(self, msg, msg_type,
                    msg_flags=NLM_F_REQUEST | NLM_F_DUMP,
                    terminate=None,
                    exception_catch=Exception,
                    exception_handler=None):

        def do_try():
            msg_seq = self.addr_pool.alloc()
            with self.lock[msg_seq]:
                try:
                    msg.reset()
                    self.put(msg, msg_type, msg_flags, msg_seq=msg_seq)
                    ret = self.get(msg_seq=msg_seq, terminate=terminate)
                    return ret
                except Exception:
                    raise
                finally:
                    # Ban this msg_seq for 0xff rounds
                    #
                    # It's a long story. Modern kernels for RTM_SET.*
                    # operations always return NLMSG_ERROR(0) == success,
                    # even not setting NLM_F_MULTY flag on other response
                    # messages and thus w/o any NLMSG_DONE. So, how to detect
                    # the response end? One can not rely on NLMSG_ERROR on
                    # old kernels, but we have to support them too. Ty, we
                    # just ban msg_seq for several rounds, and NLMSG_ERROR,
                    # being received, will become orphaned and just dropped.
                    #
                    # Hack, but true.
                    self.addr_pool.free(msg_seq, ban=0xff)

        while True:
            try:
                return do_try()
            except exception_catch as e:
                if exception_handler and not exception_handler(e):
                    continue
                raise
            except Exception:
                raise
开发者ID:kinhvan017,项目名称:pyroute2,代码行数:104,代码来源:nlsocket.py

示例6: TestIPRoute

# 需要导入模块: from pyroute2.common import AddrPool [as 别名]
# 或者: from pyroute2.common.AddrPool import alloc [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: TestExplicit

# 需要导入模块: from pyroute2.common import AddrPool [as 别名]
# 或者: from pyroute2.common.AddrPool import alloc [as 别名]
class TestExplicit(object):
    ip = None
    mode = 'explicit'

    def setup(self):
        self.ap = AddrPool()
        self.iftmp = 'pr2x{0}'
        self.ifaces = []
        self.ifd = self.get_ifname()
        create_link(self.ifd, kind='dummy')
        self.ip = IPDB(mode=self.mode)

    def get_ifname(self):
        naddr = self.ap.alloc()
        ifname = self.iftmp.format(naddr)
        self.ifaces.append(ifname)
        return ifname

    def teardown(self):
        for name in self.ifaces:
            try:
                with self.ip.interfaces[name] as i:
                    i.remove()
            except:
                pass
        self.ip.release()
        self.ifaces = []

    def test_simple(self):
        assert len(list(self.ip.interfaces.keys())) > 0

    def test_empty_transaction(self):
        assert 'lo' in self.ip.interfaces
        with self.ip.interfaces.lo as i:
            assert isinstance(i.mtu, int)

    def test_idx_len(self):
        assert len(self.ip.by_name.keys()) == len(self.ip.by_index.keys())

    def test_idx_set(self):
        assert set(self.ip.by_name.values()) == set(self.ip.by_index.values())

    def test_idx_types(self):
        assert all(isinstance(i, int) for i in self.ip.by_index.keys())
        assert all(isinstance(i, basestring) for i in self.ip.by_name.keys())

    def test_ips(self):
        for name in self.ip.by_name:
            assert len(self.ip.interfaces[name]['ipaddr']) == \
                len(get_ip_addr(name))

    def test_reprs(self):
        assert isinstance(repr(self.ip.interfaces.lo.ipaddr), basestring)
        assert isinstance(repr(self.ip.interfaces.lo), basestring)

    def test_dotkeys(self):
        # self.ip.lo hint for ipython
        assert 'lo' in dir(self.ip.interfaces)
        assert 'lo' in self.ip.interfaces
        assert self.ip.interfaces.lo == self.ip.interfaces['lo']
        # create attribute
        self.ip.interfaces['newitem'] = True
        self.ip.interfaces.newattr = True
        self.ip.interfaces.newitem = None
        assert self.ip.interfaces.newitem == self.ip.interfaces['newitem']
        assert self.ip.interfaces.newitem is None
        # delete attribute
        del self.ip.interfaces.newitem
        del self.ip.interfaces.newattr
        assert 'newattr' not in dir(self.ip.interfaces)

    def test_vlan_slave_bridge(self):
        # https://github.com/svinota/pyroute2/issues/58
        # based on the code by Petr Horáček
        dXname = self.get_ifname()
        vXname = self.get_ifname()
        vYname = self.get_ifname()
        brname = self.get_ifname()

        require_user('root')
        dX = self.ip.create(ifname=dXname, kind='dummy').commit()
        vX = self.ip.create(ifname=vXname, kind='vlan',
                            link=dX, vlan_id=101).commit()
        vY = self.ip.create(ifname=vYname, kind='vlan',
                            link=dX, vlan_id=102).commit()
        with self.ip.create(ifname=brname, kind='bridge') as i:
            i.add_port(vX)
            i.add_port(vY['index'])

        assert vX['index'] in self.ip.interfaces[brname]['ports']
        assert vY['index'] in self.ip.interfaces[brname].ports
        assert vX['link'] == dX['index']
        assert vY['link'] == dX['index']
        assert vX['master'] == self.ip.interfaces[brname]['index']
        assert vY['master'] == self.ip.interfaces[brname].index

    def _test_commit_hook_positive(self):
        require_user('root')

        # test callback, that adds an address by itself --
#.........这里部分代码省略.........
开发者ID:0x90,项目名称:pyroute2,代码行数:103,代码来源:test_ipdb.py

示例8: test_free

# 需要导入模块: from pyroute2.common import AddrPool [as 别名]
# 或者: from pyroute2.common.AddrPool import alloc [as 别名]
    def test_free(self):

        ap = AddrPool(minaddr=1, maxaddr=1024)
        f = ap.alloc()
        ap.free(f)
开发者ID:0x90,项目名称:pyroute2,代码行数:7,代码来源:test_addrpool.py

示例9: test_reverse

# 需要导入模块: from pyroute2.common import AddrPool [as 别名]
# 或者: from pyroute2.common.AddrPool import alloc [as 别名]
    def test_reverse(self):

        ap = AddrPool(minaddr=1, maxaddr=1024, reverse=True)
        for i in range(512):
            assert ap.alloc() > ap.alloc()
开发者ID:0x90,项目名称:pyroute2,代码行数:7,代码来源:test_addrpool.py

示例10: DHCP4Socket

# 需要导入模块: from pyroute2.common import AddrPool [as 别名]
# 或者: from pyroute2.common.AddrPool import alloc [as 别名]
class DHCP4Socket(RawSocket):
    '''
    Parameters:

    * ifname -- interface name to work on

    This raw socket binds to an interface and installs BPF filter
    to get only its UDP port. It can be used in poll/select and
    provides also the context manager protocol, so can be used in
    `with` statements.

    It does not provide any DHCP state machine, and does not inspect
    DHCP packets, it is totally up to you. No default values are
    provided here, except `xid` -- DHCP transaction ID. If `xid` is
    not provided, DHCP4Socket generates it for outgoing messages.
    '''

    def __init__(self, ifname, port=68):
        RawSocket.__init__(self, ifname, listen_udp_port(port))
        self.port = port
        # Create xid pool
        #
        # Every allocated xid will be released automatically after 1024
        # alloc() calls, there is no need to call free(). Minimal xid == 16
        self.xid_pool = AddrPool(minaddr=16, release=1024)

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_value, traceback):
        self.close()

    def put(self, msg=None, dport=67):
        '''
        Put DHCP message. Parameters:

        * msg -- dhcp4msg instance
        * dport -- DHCP server port

        If `msg` is not provided, it is constructed as default
        BOOTREQUEST + DHCPDISCOVER.

        Examples::

            sock.put(dhcp4msg({'op': BOOTREQUEST,
                               'chaddr': 'ff:11:22:33:44:55',
                               'options': {'message_type': DHCPREQUEST,
                                           'parameter_list': [1, 3, 6, 12, 15],
                                           'requested_ip': '172.16.101.2',
                                           'server_id': '172.16.101.1'}}))

        The method returns dhcp4msg that was sent, so one can get from
        there `xid` (transaction id) and other details.
        '''
        # DHCP layer
        dhcp = msg or dhcp4msg({'chaddr': self.l2addr})

        # dhcp transaction id
        if dhcp['xid'] is None:
            dhcp['xid'] = self.xid_pool.alloc()

        data = dhcp.encode().buf

        # UDP layer
        udp = udpmsg({'sport': self.port,
                      'dport': dport,
                      'len': 8 + len(data)})
        udph = udp4_pseudo_header({'dst': '255.255.255.255',
                                   'len': 8 + len(data)})
        udp['csum'] = self.csum(udph.encode().buf + udp.encode().buf + data)
        udp.reset()

        # IPv4 layer
        ip4 = ip4msg({'len': 20 + 8 + len(data),
                      'proto': 17,
                      'dst': '255.255.255.255'})
        ip4['csum'] = self.csum(ip4.encode().buf)
        ip4.reset()

        # MAC layer
        eth = ethmsg({'dst': 'ff:ff:ff:ff:ff:ff',
                      'src': self.l2addr,
                      'type': 0x800})

        data = eth.encode().buf +\
            ip4.encode().buf +\
            udp.encode().buf +\
            data
        self.send(data)
        dhcp.reset()
        return dhcp

    def get(self):
        '''
        Get the next incoming packet from the socket and try
        to decode it as IPv4 DHCP. No analysis is done here,
        only MAC/IPv4/UDP headers are stripped out, and the
        rest is interpreted as DHCP.
        '''
        (data, addr) = self.recvfrom(4096)
#.........这里部分代码省略.........
开发者ID:0x90,项目名称:pyroute2,代码行数:103,代码来源:dhcp4socket.py


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