Reformat MON to standardized format
[osm/MON.git] / osm_mon / evaluator / service.py
1 # -*- coding: utf-8 -*-
2
3 # Copyright 2018 Whitestack, LLC
4 # *************************************************************
5
6 # This file is part of OSM Monitoring module
7 # All Rights Reserved to Whitestack, LLC
8
9 # Licensed under the Apache License, Version 2.0 (the "License"); you may
10 # not use this file except in compliance with the License. You may obtain
11 # a copy of the License at
12
13 # http://www.apache.org/licenses/LICENSE-2.0
14
15 # Unless required by applicable law or agreed to in writing, software
16 # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
17 # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
18 # License for the specific language governing permissions and limitations
19 # under the License.
20 # For those usages not covered by the Apache License, Version 2.0 please
21 # contact: bdiaz@whitestack.com or glavado@whitestack.com
22 ##
23 import logging
24 import multiprocessing
25 from enum import Enum
26 from typing import Tuple, List
27
28 from osm_mon.core.common_db import CommonDbClient
29 from osm_mon.core.config import Config
30 from osm_mon.core.models import Alarm
31 from osm_mon.evaluator.backends.prometheus import PrometheusBackend
32
33 log = logging.getLogger(__name__)
34
35 BACKENDS = {"prometheus": PrometheusBackend}
36
37
38 class AlarmStatus(Enum):
39 ALARM = "alarm"
40 OK = "ok"
41 INSUFFICIENT = "insufficient-data"
42
43
44 class EvaluatorService:
45 def __init__(self, config: Config):
46 self.conf = config
47 self.common_db = CommonDbClient(self.conf)
48 self.queue = multiprocessing.Queue()
49
50 def _get_metric_value(self, metric_name: str, tags: dict):
51 return BACKENDS[self.conf.get("evaluator", "backend")](
52 self.conf
53 ).get_metric_value(metric_name, tags)
54
55 def _evaluate_metric(self, alarm: Alarm):
56 log.debug("_evaluate_metric")
57 metric_value = self._get_metric_value(alarm.metric, alarm.tags)
58 if metric_value is None:
59 log.warning("No metric result for alarm %s", alarm.uuid)
60 self.queue.put((alarm, AlarmStatus.INSUFFICIENT))
61 else:
62 if alarm.operation.upper() == "GT":
63 if metric_value > alarm.threshold:
64 self.queue.put((alarm, AlarmStatus.ALARM))
65 else:
66 self.queue.put((alarm, AlarmStatus.OK))
67 elif alarm.operation.upper() == "LT":
68 if metric_value < alarm.threshold:
69 self.queue.put((alarm, AlarmStatus.ALARM))
70 else:
71 self.queue.put((alarm, AlarmStatus.OK))
72
73 def evaluate_alarms(self) -> List[Tuple[Alarm, AlarmStatus]]:
74 log.debug("evaluate_alarms")
75 processes = []
76 for alarm in self.common_db.get_alarms():
77 p = multiprocessing.Process(target=self._evaluate_metric, args=(alarm,))
78 processes.append(p)
79 p.start()
80
81 for process in processes:
82 process.join(timeout=10)
83 alarms_tuples = []
84 while not self.queue.empty():
85 alarms_tuples.append(self.queue.get())
86 return alarms_tuples