| Benjamin Diaz | a97bdb3 | 2019-04-10 15:22:22 -0300 | [diff] [blame] | 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 | |
| 25 | import requests |
| 26 | |
| 27 | from osm_mon.core.config import Config |
| 28 | from osm_mon.evaluator.backends.base import BaseBackend |
| 29 | |
| 30 | log = logging.getLogger(__name__) |
| 31 | |
| 32 | OSM_METRIC_PREFIX = 'osm_' |
| 33 | |
| 34 | |
| 35 | class PrometheusBackend(BaseBackend): |
| 36 | |
| 37 | def __init__(self, config: Config): |
| 38 | super().__init__(config) |
| 39 | self.conf = config |
| 40 | |
| 41 | def get_metric_value(self, metric_name, nsr_id, vdur_name, vnf_member_index): |
| 42 | query_section = "query={0}{{ns_id=\"{1}\",vdu_name=\"{2}\",vnf_member_index=\"{3}\"}}".format( |
| 43 | OSM_METRIC_PREFIX + metric_name, nsr_id, vdur_name, vnf_member_index) |
| 44 | request_url = self.conf.get('prometheus', 'url') + "/api/v1/query?" + query_section |
| 45 | log.info("Querying Prometheus: %s", request_url) |
| 46 | r = requests.get(request_url, timeout=int(self.conf.get('global', 'request_timeout'))) |
| 47 | if r.status_code == 200: |
| 48 | json_response = r.json() |
| 49 | if json_response['status'] == 'success': |
| 50 | result = json_response['data']['result'] |
| 51 | if len(result): |
| 52 | metric_value = float(result[0]['value'][1]) |
| 53 | log.info("Metric value: %s", metric_value) |
| 54 | return metric_value |
| 55 | else: |
| 56 | return None |
| 57 | else: |
| 58 | log.warning("Prometheus response is not success. Got status %s", json_response['status']) |
| 59 | else: |
| 60 | log.warning("Error contacting Prometheus. Got status code %s: %s", r.status_code, r.text) |
| 61 | return None |