terom@738: import collections terom@735: import ipaddress, ipaddr # XXX: conversion terom@735: import pvl.hosts terom@738: import pvl.hosts.host terom@735: terom@738: class HostInterface(object): terom@738: """ terom@738: A single host-interface. terom@738: """ terom@735: terom@738: ip4 = None terom@738: terom@738: def __init__(self, name): terom@738: self.name = name terom@738: terom@738: def __str__(self): terom@738: return self.name terom@738: terom@735: @pvl.hosts.extension terom@738: class HostInterfaces(object): terom@738: """ terom@738: A host with multiple sub-interfaces. terom@738: terom@738: Typically used for point-to-point interfaces between routers. For multi-homed hosts, it might make terom@738: more sense to use multiple hosts in different domains. terom@738: terom@738: [foo] terom@738: interface:ip.eth0 = 10.255.1.1/30 terom@738: terom@738: [bar] terom@738: interface:ip.eth1 = 10.255.1.2/30 terom@738: """ terom@738: terom@735: EXTENSION = 'interface' terom@735: terom@735: @classmethod terom@738: def build (cls, ip={}): terom@738: interfaces = collections.defaultdict(HostInterface) terom@738: terom@738: for iface, ip in pvl.hosts.host.parse_dict(ip, parse=ipaddress.ip_interface).iteritems(): terom@738: if iface in interfaces: terom@738: iface = interfaces[iface] terom@738: else: terom@738: iface = interfaces[iface] = HostInterface(iface) terom@738: terom@738: interfaces[iface].ip4 = ip terom@738: terom@738: return cls(interfaces) terom@735: terom@735: def __init__ (self, interfaces): terom@735: self.interfaces = interfaces terom@735: terom@735: def addresses (self): terom@738: """ terom@738: Yield additional sub-addresses for host interfaces. terom@738: """ terom@738: terom@738: for iface in self: terom@738: if iface.ip4: terom@738: # XXX: convert terom@738: yield iface.name, ipaddr.IPv4Address(str(iface.ip4.ip)) terom@738: terom@738: def __iter__(self): terom@738: """ terom@738: HostInterface's with stable ordering. terom@738: """ terom@738: terom@738: return iter(sorted(self.interfaces.itervalues(), key=str)) terom@738: