Commit 467e5031 authored by kaiyou's avatar kaiyou

Provide basic hooks and move the state to a separate module

parent f308b2e2
import celery
def populate(context, args, key, table):
""" Populate items in context and arguments from a reference table
Useful to populate accounts, services, and other items that repeat
across a configuration file.
"""
conf = celery.current_app.scheduler.config
for item in (context, args):
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]
}
return (context, args)
def postcheck(context, result):
""" Basic post-check hooks
"""
return merge_result(*recurrence(context, result))
def recurrence(context, result, field="recurrence", reference=["up"]):
""" Compute the recurrence of a check state in a field
"""
recurring = all(
context.get(key, None) is result.get(key, None)
for key in reference
)
context[field] = (context.get(field, 0) + 1) if recurring else 0
return context, result
def merge_result(context, result):
""" Merge the result of a check back into the context
"""
return dict(context, **result), result
import json
import redis
class State(object):
""" Stores the check state in a redis backend
"""
DEFAULT_STATE = {"up": True, "recurrence": 0}
def __init__(self, redis_url):
self.storage = redis.Redis.from_url(redis_url)
def __getitem__(self, key):
value = self.storage.get(key)
return json.loads(value) if value else State.DEFAULT_STATE.copy()
def __setitem__(self, key, value):
self.storage.set(key, json.dumps(value))
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment