Adds use of CustomCollector in Prometheus exporter
[osm/MON.git] / osm_mon / collector / prometheus_exporter.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 threading
25 import time
26 from http.server import HTTPServer
27
28 from prometheus_client import MetricsHandler
29 from prometheus_client.core import REGISTRY
30
31 from osm_mon.collector.collector import MonCollector
32 from osm_mon.core.settings import Config
33
34 log = logging.getLogger(__name__)
35
36
37 class MonPrometheusExporter:
38
39 def __init__(self):
40 self.mon_collector = MonCollector()
41 self.custom_collector = CustomCollector()
42
43 def _run_exporter(self):
44 log.debug('_run_exporter')
45 REGISTRY.register(self.custom_collector)
46 server_address = ('', 8000)
47 httpd = HTTPServer(server_address, MetricsHandler)
48 log.info("Starting MON Prometheus exporter at port %s", 8000)
49 httpd.serve_forever()
50
51 def run(self):
52 log.debug('_run')
53 self._run_exporter()
54 self._run_collector()
55
56 def _run_collector(self):
57 log.debug('_run_collector')
58 t = threading.Thread(target=self._collect_metrics_forever)
59 t.setDaemon(True)
60 t.start()
61
62 def _collect_metrics_forever(self):
63 log.debug('_collect_metrics_forever')
64 cfg = Config.instance()
65 while True:
66 time.sleep(cfg.OSMMON_COLLECTOR_INTERVAL)
67 metrics = self.mon_collector.collect_metrics()
68 self.custom_collector.metrics = metrics
69
70
71 class CustomCollector(object):
72
73 def __init__(self):
74 self.mon_collector = MonCollector()
75 self.metrics = []
76
77 def describe(self):
78 log.debug('describe')
79 return []
80
81 def collect(self):
82 log.debug("collect")
83 metrics = self.mon_collector.collect_metrics()
84 return metrics
85
86
87 if __name__ == '__main__':
88 MonPrometheusExporter().run()