hooks.py 1.86 KB
Newer Older
1 2 3
import celery


4
def populate(context, args, key, table, replace=True):
5 6 7
    """ Populate items in context and arguments from a reference table
    Useful to populate accounts, services, and other items that repeat
    across a configuration file.
8 9 10 11 12

    The default behavior is to replace the entry with the match in the
    reference table. If this is disabled, the entry is deleted and the
    match is expected to be a dict, it is then merged in the context or
    args.
13 14 15
    """
    conf = celery.current_app.scheduler.config
    for item in (context, args):
16 17 18 19 20 21 22 23 24 25 26 27 28
        if replace:
            if key in item and type(item[key]) is str:
                item[key] = conf[table].get(item[key], item[key])
            elif key in item and type(item[key]) is list:
                item[key] = {
                    entry: conf[table].get(entry, entry)
                    for entry in context[key]
                }
        else:
            if key in item and type(item[key]) is str:
                item.update(conf[table][item[key]])
                del item[key]

29 30 31
    return (context, args)


kaiyou's avatar
kaiyou committed
32 33
def recurrence(context, result, fields=["up"], dest="stable", dest_prev=None):
    """ Compute the recurrence of a the value of given fields
34
    """
kaiyou's avatar
kaiyou committed
35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
    recur = {}
    prev = {}
    if dest in context:
        fields = fields + list(context[dest])
        if type(context[dest]) is dict:
            recur.update(context[dest])
    for field in fields:
        recur[field] = (
            recur.get(field, 0) + 1
            if context.get(field, None) == result.get(field, -1)
            else 0
        )
        prev[field] = context.get(field, None)
    context[dest] = recur
    if prev is not None:
        context[dest_prev] = prev
51 52 53 54 55 56 57
    return context, result


def merge_result(context, result):
    """ Merge the result of a check back into the context
    """
    return dict(context, **result), result