import statistics import requests from cronitor import monitor from tracker import terminal_colors, config cronitor = monitor.Monitor(api_key=config.cronitor_api_key) class rules: @staticmethod def ran_less_than(seconds): return dict( rule_type="ran_less_than", value=seconds, time_unit="seconds", ) @staticmethod def not_on_schedule(expr): return dict( rule_type="not_on_schedule", value=expr, ) def list_cronitors(): return requests.get(cronitor.api_endpoint, timeout=10, auth=(cronitor.api_key, ''), headers={'content-type': 'application/json'} ).json() def list_cronitors_with_durations(): all_cronitors = list_cronitors()['monitors'] for mon in all_cronitors: durations = cronitor.get(mon['code'] + '/durations').json()[mon['code']] seconds = [d['total_seconds'] for d in durations] mon['durations'] = { 'recent': durations, 'median': statistics.median(seconds), 'mean': statistics.mean(seconds), } import time; time.sleep(0.5) return all_cronitors def find_cronitor_by_name(name): res = cronitor.get(code=name) if res.status_code == 200: return res.json() return None def upsert_cronitor(name, cron_sched, min_seconds_allowed=None, note=None): cron_sched = _to_cronitor_sched(cron_sched) the_rules = [rules.not_on_schedule(cron_sched)] if min_seconds_allowed is not None: the_rules.append(rules.ran_less_than(min_seconds_allowed)) notifications = {'emails': ['ops@whtlst.in']} existing = find_cronitor_by_name(name) if existing: kw = dict( name=existing['name'], code=existing['code'], note=(note or existing.get('note')), rules=the_rules, notifications=notifications, tags=['cron-job']) return cronitor.update(**kw).json() else: return cronitor.create( name=name, note=note, rules=the_rules, notifications=notifications, tags=['cron-job'] ).json() def _to_cronitor_sched(cron_sched): if cron_sched.startswith('cron'): cron_sched = cron_sched.strip('cron(').strip(")") if " ? " in cron_sched: parts = [s.strip() for s in cron_sched.split(" ")] cron_sched = " ".join(parts[0:4] + [parts[5]]) return cron_sched def _to_cloudwatch_event_sched(cron_sched): if cron_sched.startswith('cron'): return cron_sched if " ? " not in cron_sched: parts = [s.strip() for s in cron_sched.split(" ")] cron_sched = " ".join(parts[0:4] + ["?", parts[4]]) return "cron(" + cron_sched + ")"