# Path: moira/api/request.py
# def check_trigger(f):
#     @defer.inlineCallbacks
#     def decorator(*args, **kwargs):
#         request = args[1]
#         json = request.body_json
#         request.graphite_patterns = []
#         for field, alt in [("targets", None), ("warn_value", "expression"), ("error_value", "expression")]:
#             if json.get(field) is None and json.get(alt) is None:
#                 defer.returnValue(bad_request(request, "%s is required" % field))
#         if type(json["targets"]) is not list:
#             defer.returnValue(bad_request(request, "Invalid trigger targets"))
#         try:
#             request.body_json = trigger_reformat(json, json.get("id"), json.get("tags", []))
#         except Exception as e:
#             log.error("Invalid trigger format [{json}]: {e}", json=json, e=e)
#             defer.returnValue(bad_request(request, "Invalid trigger format"))
#         expression_values = {'warn_value': json.get('warn_value'),
#                              'error_value': json.get('error_value'),
#                              'PREV_STATE': state.NODATA}
#         try:
#             yield resolve_patterns(request, expression_values)
#         except Exception as e:
#             log.error("Invalid graphite targets [{targets}]: {e}", targets=request.body_json["targets"], e=e)
#             defer.returnValue(bad_request(request, "Invalid graphite targets"))
#         try:
#             getExpression(json.get("expression"), **expression_values)
#         except Exception as e:
#             log.error("Invalid expression [{expression}]: {e}", expression=json.get("expression"), e=e)
#             defer.returnValue(bad_request(request, "Invalid expression"))
#         yield f(*args, **kwargs)
#     return decorator
# 
# def check_json(f):
#     @defer.inlineCallbacks
#     def decorator(*args, **kwargs):
#         request = args[1]
#         try:
#             request.body = request.content.getvalue()
#             request.body_json = anyjson.deserialize(request.body)
#         except Exception as e:
#             log.error("Invalid trigger json [{json}]: {e}", json=request.body, e=e)
#             defer.returnValue(bad_request(request, "Content is not json"))
#         yield f(*args, **kwargs)
#     return decorator
# 
# Path: moira/checker/state.py
# OK = "OK"
# WARN = "WARN"
# ERROR = "ERROR"
# NODATA = "NODATA"
# EXCEPTION = "EXCEPTION"
# DEL = "DEL"
# SCORES = {
#     "OK": 0,
#     "DEL": 0,
#     "WARN": 1,
#     "ERROR": 100,
#     "NODATA": 1000,
#     "EXCEPTION": 100000
# }
# def to_metric_state(state):


import anyjson
from twisted.internet import defer
from twisted.web.resource import Resource
from moira.api.request import check_trigger, check_json
from moira.checker import state
        request.finish()

    def write_dumped_json(self, request, result):
        request.setHeader("Content-Type", "application/json")
        request.write(str(result))
        request.finish()

    @check_json
    @check_trigger
    @defer.inlineCallbacks
    def save_trigger(self, request, trigger_id, message):
        _, existing = yield self.db.getTrigger(trigger_id)

        yield self.db.acquireTriggerCheckLock(trigger_id, 10)
        last_check = yield self.db.getTriggerLastCheck(trigger_id)
        if last_check:
            for metric in list(last_check.get('metrics', {})):
                if metric not in request.context['time_series_names']:
                    del last_check['metrics'][metric]
        else:
            last_check = {
                "metrics": {},
                "state": state.NODATA,
                "score": 0
            }

        yield self.db.setTriggerLastCheck(trigger_id, last_check)

        yield self.db.delTriggerCheckLock(trigger_id)


# Path: moira/api/request.py
# def check_trigger(f):
#     @defer.inlineCallbacks
#     def decorator(*args, **kwargs):
#         request = args[1]
#         json = request.body_json
#         request.graphite_patterns = []
#         for field, alt in [("targets", None), ("warn_value", "expression"), ("error_value", "expression")]:
#             if json.get(field) is None and json.get(alt) is None:
#                 defer.returnValue(bad_request(request, "%s is required" % field))
#         if type(json["targets"]) is not list:
#             defer.returnValue(bad_request(request, "Invalid trigger targets"))
#         try:
#             request.body_json = trigger_reformat(json, json.get("id"), json.get("tags", []))
#         except Exception as e:
#             log.error("Invalid trigger format [{json}]: {e}", json=json, e=e)
#             defer.returnValue(bad_request(request, "Invalid trigger format"))
#         expression_values = {'warn_value': json.get('warn_value'),
#                              'error_value': json.get('error_value'),
#                              'PREV_STATE': state.NODATA}
#         try:
#             yield resolve_patterns(request, expression_values)
#         except Exception as e:
#             log.error("Invalid graphite targets [{targets}]: {e}", targets=request.body_json["targets"], e=e)
#             defer.returnValue(bad_request(request, "Invalid graphite targets"))
#         try:
#             getExpression(json.get("expression"), **expression_values)
#         except Exception as e:
#             log.error("Invalid expression [{expression}]: {e}", expression=json.get("expression"), e=e)
#             defer.returnValue(bad_request(request, "Invalid expression"))
#         yield f(*args, **kwargs)
#     return decorator
# 
# def check_json(f):
#     @defer.inlineCallbacks
#     def decorator(*args, **kwargs):
#         request = args[1]
#         try:
#             request.body = request.content.getvalue()
#             request.body_json = anyjson.deserialize(request.body)
#         except Exception as e:
#             log.error("Invalid trigger json [{json}]: {e}", json=request.body, e=e)
#             defer.returnValue(bad_request(request, "Content is not json"))
#         yield f(*args, **kwargs)
#     return decorator
# 
# Path: moira/checker/state.py
# OK = "OK"
# WARN = "WARN"
# ERROR = "ERROR"
# NODATA = "NODATA"
# EXCEPTION = "EXCEPTION"
# DEL = "DEL"
# SCORES = {
#     "OK": 0,
#     "DEL": 0,
#     "WARN": 1,
#     "ERROR": 100,
#     "NODATA": 1000,
#     "EXCEPTION": 100000
# }
# def to_metric_state(state):


# Path: moira/api/resources/redis.py
import anyjson
from twisted.internet import defer
from twisted.web.resource import Resource
from moira.api.request import check_trigger, check_json
from moira.checker import state

        request.finish()

    def write_dumped_json(self, request, result):
        request.setHeader("Content-Type", "application/json")
        request.write(str(result))
        request.finish()

    @check_json
    @check_trigger
    @defer.inlineCallbacks
    def save_trigger(self, request, trigger_id, message):
        _, existing = yield self.db.getTrigger(trigger_id)

        yield self.db.acquireTriggerCheckLock(trigger_id, 10)
        last_check = yield self.db.getTriggerLastCheck(trigger_id)
        if last_check:
            for metric in list(last_check.get('metrics', {})):
                if metric not in request.context['time_series_names']:
                    del last_check['metrics'][metric]
        else:
            last_check = {
                "metrics": {},
                "state": state.NODATA,
                "score": 0
            }

        yield self.db.setTriggerLastCheck(trigger_id, last_check)

        yield self.db.delTriggerCheckLock(trigger_id)


        yield self.db.saveTrigger(trigger_id, request.body_json,