Adds OSMMON_LOG_LEVEL env var to config log level
[osm/MON.git] / osm_mon / plugins / OpenStack / Aodh / notifier.py
1 # Copyright 2017 Intel Research and Development Ireland Limited
2 # *************************************************************
3
4 # This file is part of OSM Monitoring module
5 # All Rights Reserved to Intel Corporation
6
7 # Licensed under the Apache License, Version 2.0 (the "License"); you may
8 # not use this file except in compliance with the License. You may obtain
9 # a copy of the License at
10
11 # http://www.apache.org/licenses/LICENSE-2.0
12
13 # Unless required by applicable law or agreed to in writing, software
14 # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
15 # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
16 # License for the specific language governing permissions and limitations
17 # under the License.
18
19 # For those usages not covered by the Apache License, Version 2.0 please
20 # contact: helena.mcgough@intel.com or adrian.hoban@intel.com
21 ##
22 # __author__ = Helena McGough
23 #
24 """A Webserver to send alarm notifications from Aodh to the SO."""
25 import json
26 import logging
27 import os
28 import sys
29 import time
30
31 from six.moves.BaseHTTPServer import BaseHTTPRequestHandler
32 from six.moves.BaseHTTPServer import HTTPServer
33
34 # Initialise a logger for alarm notifier
35 from osm_mon.core.settings import Config
36
37 cfg = Config.instance()
38
39 logging.basicConfig(stream=sys.stdout,
40 format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
41 datefmt='%m/%d/%Y %I:%M:%S %p',
42 level=logging.getLevelName(cfg.OSMMON_LOG_LEVEL))
43 log = logging.getLogger(__name__)
44
45 sys.path.append(os.path.abspath(os.path.join(os.path.realpath(__file__), '..', '..', '..', '..', '..')))
46
47 from osm_mon.core.database import DatabaseManager
48 from osm_mon.core.message_bus.producer import KafkaProducer
49
50 from osm_mon.plugins.OpenStack.response import OpenStack_Response
51
52
53 class NotifierHandler(BaseHTTPRequestHandler):
54 """Handler class for alarm_actions triggered by OSM alarms."""
55
56 def _set_headers(self):
57 """Set the headers for a request."""
58 self.send_response(200)
59 self.send_header('Content-type', 'text/html')
60 self.end_headers()
61
62 def do_GET(self):
63 """Get request functionality."""
64 self._set_headers()
65
66 def do_POST(self):
67 """POST request function."""
68 # Gets header and data from the post request and records info
69 self._set_headers()
70 # Gets the size of data
71 content_length = int(self.headers['Content-Length'])
72 post_data = self.rfile.read(content_length)
73 # Python 2/3 string compatibility
74 try:
75 post_data = post_data.decode()
76 except AttributeError:
77 pass
78 log.info("This alarm was triggered: %s", post_data)
79
80 # Send alarm notification to message bus
81 try:
82 self.notify_alarm(json.loads(post_data))
83 except Exception:
84 log.exception("Error notifying alarm")
85
86 def notify_alarm(self, values):
87 """Sends alarm notification message to bus."""
88
89 # Initialise configuration and authentication for response message
90 response = OpenStack_Response()
91 producer = KafkaProducer('alarm_response')
92
93 database_manager = DatabaseManager()
94
95 alarm_id = values['alarm_id']
96 alarm = database_manager.get_alarm(alarm_id, 'openstack')
97 # Process an alarm notification if resource_id is valid
98 # Get date and time for response message
99 a_date = time.strftime("%d-%m-%Y") + " " + time.strftime("%X")
100 # Generate and send response
101 resp_message = response.generate_response(
102 'notify_alarm',
103 a_id=alarm_id,
104 vdu_name=alarm.vdu_name,
105 vnf_member_index=alarm.vnf_member_index,
106 ns_id=alarm.ns_id,
107 metric_name=alarm.metric_name,
108 operation=alarm.operation,
109 threshold_value=alarm.threshold,
110 sev=values['severity'],
111 date=a_date,
112 state=values['current'])
113 producer.publish_alarm_response(
114 'notify_alarm', resp_message)
115 log.info("Sent alarm notification: %s", resp_message)
116
117
118 def run(server_class=HTTPServer, handler_class=NotifierHandler, port=8662):
119 """Run the webserver application to retrieve alarm notifications."""
120 try:
121 server_address = ('', port)
122 httpd = server_class(server_address, handler_class)
123 print('Starting alarm notifier...')
124 log.info("Starting alarm notifier server on port: %s", port)
125 httpd.serve_forever()
126 except Exception as exc:
127 log.warning("Failed to start webserver, %s", exc)
128
129
130 if __name__ == "__main__":
131 from sys import argv
132
133 # Runs the webserver
134 if len(argv) == 2:
135 run(port=int(argv[1]))
136 else:
137 run()