pvl.hosts-dns: enumerate --reverse-zone with support for --unknown-host and duplicate checking
authorTero Marttila <terom@paivola.fi>
Mon, 16 Dec 2013 19:27:22 +0200
changeset 272 5755f9c54135
parent 271 4dfa1a939153
child 273 c8deaa9a2746
pvl.hosts-dns: enumerate --reverse-zone with support for --unknown-host and duplicate checking
bin/pvl.hosts-dns
--- a/bin/pvl.hosts-dns	Mon Dec 16 19:11:58 2013 +0200
+++ b/bin/pvl.hosts-dns	Mon Dec 16 19:27:22 2013 +0200
@@ -23,9 +23,9 @@
         for alias in host.alias :
             yield pvl.dns.zone.ZoneRecord.CNAME(alias, host)
 
-def process_hosts_reverse (options, hosts, prefix) :
+def process_hosts_ips (options, hosts, prefix) :
     """
-        Generate DNS ZoneRecords within the given prefix's reverse-dns zone for hosts.
+        Yield (ip, fqnd) for hosts within given prefix.
     """
 
     for host in hosts :
@@ -34,12 +34,33 @@
 
         if host.ip not in prefix :
             continue
+
+        yield host.ip, pvl.dns.zone.fqdn(host, host.domain)
+ 
+def process_hosts_reverse (options, hosts, prefix) :
+    """
+        Generate DNS ZoneRecords within the given prefix's reverse-dns zone for hosts.
+    """
+    
+    # collect data for records
+    by_ip = dict()
+    for ip, fqdn in process_hosts_ips(options, hosts, prefix) :
+        if ip in by_ip :
+            raise ValueError("%s: duplicate ip: %s: %s" % (fqdn, ip, by_ip[ip]))
+        else :
+            by_ip[ip] = fqdn
+
+    for ip in prefix.iterhosts() :
+        if ip in by_ip :
+            fqdn = by_ip[ip]
+        elif options.unknown_host :
+            fqdn = pvl.dns.zone.fqdn(options.unknown_host, options.hosts_domain)
+        else :
+            fqdn = None
         
-        # reverse against the reverse-dns zone origin
-        yield pvl.dns.zone.ZoneRecord.PTR(
-                pvl.dns.zone.reverse_label(prefix, host.ip),
-                pvl.dns.zone.fqdn(host, host.domain)
-        )
+        if fqdn :
+            # reverse against the reverse-dns zone origin
+            yield pvl.dns.zone.ZoneRecord.PTR(pvl.dns.zone.reverse_label(prefix, ip), fqdn)
 
 def apply_zone (options, zone) :
     """
@@ -64,6 +85,9 @@
     parser.add_option('--reverse-zone',         metavar='PREFIX',
             help="Generate reverse zone for prefx")
 
+    parser.add_option('--unknown-host',         metavar='NAME',
+            help="Generate records for unused IPs")
+
     options, args = parser.parse_args(argv[1:])
     pvl.args.apply(options)