diff --git a/generateZonefiles.py b/generateZonefiles.py index 3093a82..eb3c481 100644 --- a/generateZonefiles.py +++ b/generateZonefiles.py @@ -1,7 +1,11 @@ #!/usr/bin/env python3 # -*- coding: utf-8 -*- +import difflib +import hashlib import os +import os.path +import sys # Third-party imports import dns.resolver @@ -9,6 +13,7 @@ import dns.rdatatype import jinja2 import yaml +BLOCKSIZE = 65536 DEFAULT_TTL = 3600 @@ -18,6 +23,33 @@ def default(d, key, default=None): return default +def diff_files(file1, file2): + fromlines = [] + tolines = [] + if os.path.isfile(file1): + with open(file1) as ff: + fromlines = ff.readlines() + if os.path.isfile(file2): + with open(file2) as tf: + tolines = tf.readlines() + + print(''.join(difflib.unified_diff( + fromlines, tolines, file1, file2))) + + +def hash_file(filename): + if not os.path.isfile(filename): + return "" + + hasher = hashlib.sha1() + with open(filename, 'rb') as afile: + buf = afile.read(BLOCKSIZE) + while len(buf) > 0: + hasher.update(buf) + buf = afile.read(BLOCKSIZE) + return hasher.hexdigest() + + def resolve_alias(entry): result = [] @@ -31,6 +63,8 @@ def resolve_alias(entry): raise Exception( "Alias {} was not resolvable: No answers!".format(entry['alias'])) + answers.sort() + for rdata in answers: new_entry = entry.copy() del new_entry['alias'] @@ -77,8 +111,10 @@ def write_zone(zone, ttl, soa, nameserver, mailserver, entries): with open("zones/tmp.{}".format(zone), 'w') as zf: zf.write(zone_content) - # FIXME (kahlers): Check if contents changed - os.rename("zones/tmp.{}".format(zone), "zones/db.{}".format(zone)) + if hash_file("zones/tmp.{}".format(zone)) != hash_file("zones/db.{}".format(zone)): + print("Generated and replaced zone file for {}".format(zone)) + diff_files("zones/db.{}".format(zone), "zones/tmp.{}".format(zone)) + os.rename("zones/tmp.{}".format(zone), "zones/db.{}".format(zone)) def main():