pvl/dns/process.py
author Tero Marttila <tero.marttila@aalto.fi>
Tue, 03 Mar 2015 12:14:22 +0200
changeset 716 4fecd0d1cf23
parent 648 8e3e6be9ac70
child 717 e37b0a857a5d
permissions -rw-r--r--
pvl.dns.process: merge --include-trace into pvl.dns-process, replacing pvl.dns-includes
import logging
import optparse
import os.path
import pvl.args

from pvl.dns import zone

log = logging.getLogger('pvl.dns.process')

def optparser (parser):
    group = optparse.OptionGroup(parser, "Hosts config files")
    group.add_option('--input-charset',        metavar='CHARSET',  default='utf-8', 
            help="Encoding used for input files")

    group.add_option('-o', '--output',         metavar='FILE',     default=None,
            help="Write to output file; default stdout")

    group.add_option('--output-charset',       metavar='CHARSET',  default='utf-8', 
            help="Encoding used for output files")

    return group

def zone_serial (rrs, serial) :
    """
        Update the serial in the SOA record.
    """

    for rr in rrs:
        if isinstance(rr, zone.ZoneRecordSOA) and rr.type == 'SOA':
            yield zone.ZoneRecordSOA.build(rr.name, rr.type,
                    rr.master, rr.contact,
                    serial, rr.refresh, rr.retry, rr.expire, rr.nxttl,
                    line=rr.line, origin=rr.origin, comment=rr.comment,
            )
        else:
            yield rr

def zone_includes (rrs, includes_path,
        include_trace=None,
):
    """
        Rewrite include paths in zones.

            include_trace           - append included paths to given list
    """

    for rr in rrs:
        if isinstance(rr, zone.ZoneDirective) and rr.directive == 'INCLUDE':
            include_path, = rr.arguments

            include = os.path.join(includes_path, include_path)

            if include_trace is not None:
                include_trace.append(include)

            yield zone.ZoneDirective.INCLUDE(include)
        else:
            yield rr

def apply_zone_output (options, zone):
    """
        Output given ZoneDirective/ZoneRecord items to the output file/stdout.
    """

    file = pvl.args.apply_file(options.output, 'w', options.output_charset)

    for item in zone:
        file.write(unicode(item))
        file.write('\n')

def apply_zone (options, args):
    """
        ZoneLine.load() in given zones.

        Yields ZoneDirective/ZoneRecord items.
    """

    for file in pvl.args.apply_files(args, 'r', options.input_charset) :
        log.info("%s: reading zone", file.name)

        for item in zone.ZoneLine.load(file):
            yield item

def apply_zone_records (options, origin, args) :
    """
        ZoneRecord.load() in given zones.

        Yields expanded ZoneRecord items.
    """

    for file in pvl.args.apply_files(args, 'r', options.input_charset) :
        log.info("%s: expanding zone", file.name)

        for item in zone.ZoneRecord.load(file, origin):
            yield item