pvl/hosts/dhcp.py
author Tero Marttila <tero.marttila@aalto.fi>
Mon, 02 Mar 2015 19:45:06 +0200
changeset 697 3c3ac207ce3f
parent 689 c258e3ff6d32
child 698 656178fb8607
permissions -rw-r--r--
pvl.hosts.dhcp: use pvl.dhcp.config.Field() to format non-string field values
import pvl.dhcp.config
import pvl.hosts.host

class HostDHCPError(pvl.hosts.host.HostError):
    pass

def dhcp_host_options (host, ethernet):
    """
        Yield specific dhcp.conf host { ... } items.
    """

    yield 'option', 'host-name', host.name
    yield 'hardware', 'ethernet', pvl.dhcp.config.Field(ethernet)

    if host.ip:
        yield 'fixed-address', pvl.dhcp.config.Field(str(host.ip))
      
    for bootopt in ('next-server', 'filename'):
        if bootopt in host.boot:
            yield bootopt, host.boot[bootopt]

def dhcp_host (host):
    """
        Yield pvl.dhcp.config.Block's
    """

    if set(host.ethernet) == set([None]) :
        host_fmt = "{host.name}"
    elif host.ethernet :
        host_fmt = "{host.name}-{index}"
    else :
        # nothing to be seen here
        return
 
    if host.owner :
        comment = u"Owner: {host.owner}".format(host=host)
    else:
        comment = None

    for index, ethernet in host.ethernet.iteritems() :
        name = host_fmt.format(host=host, index=index)

        yield pvl.dhcp.config.Block(('host', name), list(dhcp_host_options(host, ethernet)), comment=comment)
    
def dhcp_hosts (hosts):
    """

        Verifies that there are no dupliate hosts.
    """

    blocks = { }

    for host in hosts:
        for block in dhcp_host(host):
            if block.key in blocks:
                raise HostDHCPError(host, "dhcp {block} conflict with {other}; hosts on multiple networks must use unique ethernet.XXX=... naming".format(block=block, other=blocks[block.key]))

            blocks[block.key] = host

            yield block