pvl/hosts/interface.py
author Tero Marttila <terom@paivola.fi>
Tue, 10 Mar 2015 00:11:43 +0200
changeset 739 5149c39f3dfc
parent 738 3104fdf7ea26
child 740 74352351d6f5
permissions -rw-r--r--
pvl.hosts: improve HostExtension support enough to move boot= into pvl.hosts.dhcp
import collections
import ipaddress, ipaddr # XXX: conversion
import pvl.hosts
import pvl.hosts.host

class HostInterface(object):
    """
        A single host-interface.
    """

    ip4 = None

    def __init__(self, name):
        self.name = name

    def __str__(self):
        return self.name
    
@pvl.hosts.host.register_extension
class HostInterfaces(pvl.hosts.host.HostExtension):
    """
        A host with multiple sub-interfaces.

        Typically used for point-to-point interfaces between routers. For multi-homed hosts, it might make
        more sense to use multiple hosts in different domains.

            [foo]
                interface:ip.eth0 = 10.255.1.1/30

            [bar]
                interface:ip.eth1 = 10.255.1.2/30
    """

    EXTENSION = 'interface'

    @classmethod
    def build (cls, ip={}):
        interfaces = collections.defaultdict(HostInterface)
        
        for iface, ip in pvl.hosts.host.parse_dict(ip, parse=ipaddress.ip_interface).iteritems():
            if iface in interfaces:
                iface = interfaces[iface]
            else:
                iface = interfaces[iface] = HostInterface(iface)

            interfaces[iface].ip4 = ip
        
        return cls(interfaces)

    def __init__ (self, interfaces):
        self.interfaces = interfaces

    def addresses (self):
        """
            Yield additional sub-addresses for host interfaces.
        """

        for iface in self:
            if iface.ip4:
                # XXX: convert
                yield iface.name, ipaddr.IPv4Address(str(iface.ip4.ip))
    
    def __iter__(self):
        """
            HostInterface's with stable ordering.
        """

        return iter(sorted(self.interfaces.itervalues(), key=str))