本文整理汇总了Python中pyroute2.common.AddrPool类的典型用法代码示例。如果您正苦于以下问题:Python AddrPool类的具体用法?Python AddrPool怎么用?Python AddrPool使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了AddrPool类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_free_reverse_fail
def test_free_reverse_fail(self):
ap = AddrPool(minaddr=1, maxaddr=1024, reverse=True)
try:
ap.free(0)
except KeyError:
pass
示例2: test_alloc_aligned
def test_alloc_aligned(self):
ap = AddrPool(minaddr=1, maxaddr=1024)
for i in range(1024):
ap.alloc()
try:
ap.alloc()
except KeyError:
pass
示例3: test_locate
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
示例4: setup
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)
示例5: __init__
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)
示例6: setup
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
示例7: test_setaddr_allocated
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
示例8: __init__
def __init__(self,
family=NETLINK_GENERIC,
port=None,
pid=None,
fileno=None):
#
# That's a trick. Python 2 is not able to construct
# sockets from an open FD.
#
# So raise an exception, if the major version is < 3
# and fileno is not None.
#
# Do NOT use fileno in a core pyroute2 functionality,
# since the core should be both Python 2 and 3
# compatible.
#
super(NetlinkMixin, self).__init__()
if fileno is not None and sys.version_info[0] < 3:
raise NotImplementedError('fileno parameter is not supported '
'on Python < 3.2')
# 8<-----------------------------------------
self.addr_pool = AddrPool(minaddr=0x000000ff, maxaddr=0x0000ffff)
self.epid = None
self.port = 0
self.fixed = True
self.family = family
self._fileno = fileno
self.backlog = {0: []}
self.callbacks = [] # [(predicate, callback, args), ...]
self.pthread = None
self.closed = False
self.capabilities = {'create_bridge': True,
'create_bond': True,
'create_dummy': True,
'provide_master': config.kernel[0] > 2}
self.backlog_lock = threading.Lock()
self.read_lock = threading.Lock()
self.change_master = threading.Event()
self.lock = LockFactory()
self._sock = None
self._ctrl_read, self._ctrl_write = os.pipe()
self.buffer_queue = Queue()
self.qsize = 0
self.log = []
self.get_timeout = 30
self.get_timeout_exception = None
if pid is None:
self.pid = os.getpid() & 0x3fffff
self.port = port
self.fixed = self.port is not None
elif pid == 0:
self.pid = os.getpid()
else:
self.pid = pid
# 8<-----------------------------------------
self.groups = 0
self.marshal = Marshal()
# 8<-----------------------------------------
# Set defaults
self.post_init()
示例9: NetlinkMixin
class NetlinkMixin(object):
'''
Generic netlink socket
'''
def __init__(self,
family=NETLINK_GENERIC,
port=None,
pid=None,
fileno=None):
#
# That's a trick. Python 2 is not able to construct
# sockets from an open FD.
#
# So raise an exception, if the major version is < 3
# and fileno is not None.
#
# Do NOT use fileno in a core pyroute2 functionality,
# since the core should be both Python 2 and 3
# compatible.
#
super(NetlinkMixin, self).__init__()
if fileno is not None and sys.version_info[0] < 3:
raise NotImplementedError('fileno parameter is not supported '
'on Python < 3.2')
# 8<-----------------------------------------
self.addr_pool = AddrPool(minaddr=0x000000ff, maxaddr=0x0000ffff)
self.epid = None
self.port = 0
self.fixed = True
self.family = family
self._fileno = fileno
self.backlog = {0: []}
self.callbacks = [] # [(predicate, callback, args), ...]
self.pthread = None
self.closed = False
self.capabilities = {'create_bridge': True,
'create_bond': True,
'create_dummy': True,
'provide_master': config.kernel[0] > 2}
self.backlog_lock = threading.Lock()
self.read_lock = threading.Lock()
self.change_master = threading.Event()
self.lock = LockFactory()
self._sock = None
self._ctrl_read, self._ctrl_write = os.pipe()
self.buffer_queue = Queue()
self.qsize = 0
self.log = []
self.get_timeout = 30
self.get_timeout_exception = None
if pid is None:
self.pid = os.getpid() & 0x3fffff
self.port = port
self.fixed = self.port is not None
elif pid == 0:
self.pid = os.getpid()
else:
self.pid = pid
# 8<-----------------------------------------
self.groups = 0
self.marshal = Marshal()
# 8<-----------------------------------------
# Set defaults
self.post_init()
def clone(self):
return type(self)(family=self.family)
def close(self):
try:
os.close(self._ctrl_write)
os.close(self._ctrl_read)
except OSError:
# ignore the case when it is closed already
pass
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, traceback):
self.close()
def release(self):
log.warning("The `release()` call is deprecated")
log.warning("Use `close()` instead")
self.close()
def register_callback(self, callback,
predicate=lambda x: True, args=None):
'''
Register a callback to run on a message arrival.
Callback is the function that will be called with the
message as the first argument. Predicate is the optional
callable object, that returns True or False. Upon True,
the callback will be called. Upon False it will not.
Args is a list or tuple of arguments.
#.........这里部分代码省略.........
示例10: TestIPRoute
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:
#.........这里部分代码省略.........
示例11: TestExplicit
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 --
#.........这里部分代码省略.........
示例12: test_free
def test_free(self):
ap = AddrPool(minaddr=1, maxaddr=1024)
f = ap.alloc()
ap.free(f)
示例13: test_reverse
def test_reverse(self):
ap = AddrPool(minaddr=1, maxaddr=1024, reverse=True)
for i in range(512):
assert ap.alloc() > ap.alloc()
示例14: test_setaddr_free
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
示例15: DHCP4Socket
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)
#.........这里部分代码省略.........