rrdweb/rrd.py
author Tero Marttila <terom@fixme.fi>
Sun, 31 Jan 2010 01:32:48 +0200
branchoo-graphs
changeset 19 58df27d54d2e
parent 5 e716718482c3
permissions -rw-r--r--
start restructuring graph definitions as a class hierarchy...
import rrdtool

"""
    Friendly wrapper around the rrdtool python interface
"""

def normalize_option_key (key) :
    """
        Normalize the given option key.

        A -- is prepended, and _'s are converted to -
    """

    return '--' + str(key).replace('_', '-')

def normalize_option_multi (key, values) :
    """
        Normalize a list of option values, returning a series of --opt, val1, --opt, val2, ...
    """

    for value in values :
        yield key
        yield str(value)

def normalize_option (key, value) :
    """
        Normalize the given option to a series of cmd-args.

        If value is None or False, no cmd-args are emitted. If value is True, only --opt is emitted. If value is a list,
        --opt and value are emitted for each item.
        
        Otherwise, both --opt and str(value) are emitted.
    """

    key = normalize_option_key(key)

    if value is None or value is False :
        # omit
        return ()

    elif value is True :
        # flag
        return (key, )
    
    elif isinstance(value, list) :
        # list of option values
        return normalize_option_multi(key, value)

    else :
        # option value
        return (key, str(value))

def merge_opts (*all_opts) :
    """
        Merge the given series of opt dicts
    """

    out = dict()

    for opts in all_opts :
        # XXX: not strictly true, merge lists
        out.update(opts)

    return out

def normalize_args (args) :
    """
        Flatten the given nested iterables list into a flat one
    """

    for arg in args :
        # naasty type-checks :)
        if isinstance(arg, (list, tuple, types.GeneratorType)) :
            # recurse -> flatten
            for subarg in normalize_args(arg) :
                yield subarg

        else :
            # flat
            yield str(arg)

def run_cmd (func, pre_args, opts, post_args) :
    """
        Run the given rrdtool.* function, formatting the given positional arguments and options.
    """
    
    # series of (cmd-arg, cmd-arg, ...) tuples
    opt_items = (normalize_option(key, value) for key, value in opts.iteritems())

    # decomposed series of cmd-args
    opt_args = [item for items in opt_items for item in items]

    # positional arguments
    pre_args = normalize_args(pre_args)
    post_args = normalize_args(post_args)

    # full arguments
    args = pre_args + opt_args + post_args

    return func(*args)

def graph (out_path, *args, **opts) :
    return run_cmd(rrdtool.graph, (out_path, ), opts, args)