ofproto: Allow CIDR notation for ipv[46]_{src, dst}

This hack allows CIDR notations for OFPMatch. For example:
    ofpp.OFPMatch(ipv4_src="198.51.100.0/24")

Signed-off-by: IWAMOTO Toshihiro <iwamoto@valinux.co.jp>
Signed-off-by: FUJITA Tomonori <fujita.tomonori@lab.ntt.co.jp>
This commit is contained in:
IWAMOTO Toshihiro 2017-05-09 11:00:27 +09:00 committed by FUJITA Tomonori
parent a197d87375
commit 607f4d8276
2 changed files with 19 additions and 4 deletions

View File

@ -18,20 +18,32 @@ import netaddr
class AddressConverter(object): class AddressConverter(object):
def __init__(self, addr, strat, **kwargs): def __init__(self, addr, strat, fallback=None, **kwargs):
self._addr = addr self._addr = addr
self._strat = strat self._strat = strat
self._fallback = fallback
self._addr_kwargs = kwargs self._addr_kwargs = kwargs
def text_to_bin(self, text): def text_to_bin(self, text):
try:
return self._addr(text, **self._addr_kwargs).packed return self._addr(text, **self._addr_kwargs).packed
except Exception as e:
if self._fallback is None:
raise e
# text_to_bin is expected to return binary string under
# normal circumstances. See ofproto.oxx_fields._from_user.
ip = self._fallback(text, **self._addr_kwargs)
return ip.ip.packed, ip.netmask.packed
def bin_to_text(self, bin): def bin_to_text(self, bin):
return str(self._addr(self._strat.packed_to_int(bin), return str(self._addr(self._strat.packed_to_int(bin),
**self._addr_kwargs)) **self._addr_kwargs))
ipv4 = AddressConverter(netaddr.IPAddress, netaddr.strategy.ipv4, version=4) ipv4 = AddressConverter(netaddr.IPAddress, netaddr.strategy.ipv4,
ipv6 = AddressConverter(netaddr.IPAddress, netaddr.strategy.ipv6, version=6) fallback=netaddr.IPNetwork, version=4)
ipv6 = AddressConverter(netaddr.IPAddress, netaddr.strategy.ipv6,
fallback=netaddr.IPNetwork, version=6)
class mac_mydialect(netaddr.mac_unix): class mac_mydialect(netaddr.mac_unix):

View File

@ -72,6 +72,9 @@ def _from_user(oxx, name_to_field, name, user_value):
value = t.from_user(value) value = t.from_user(value)
if mask is not None: if mask is not None:
mask = t.from_user(mask) mask = t.from_user(mask)
elif isinstance(value, tuple):
# This hack is to accomodate CIDR notations with IPv[46]Addr.
value, mask = value
return num, value, mask return num, value, mask