Adds vdu, ns, threshold and operation info to alarm notification
[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
36 logging.basicConfig(stream=sys.stdout,
37 format='%(asctime)s %(message)s',
38 datefmt='%m/%d/%Y %I:%M:%S %p',
39 level=logging.INFO)
40 log = logging.getLogger(__name__)
41
42 sys.path.append(os.path.abspath(os.path.join(os.path.realpath(__file__), '..', '..', '..', '..', '..')))
43
44 from osm_mon.core.database import DatabaseManager
45 from osm_mon.core.message_bus.producer import KafkaProducer
46
47 from osm_mon.plugins.OpenStack.response import OpenStack_Response
48 from osm_mon.core.settings import Config
49
50
51 class NotifierHandler(BaseHTTPRequestHandler):
52 """Handler class for alarm_actions triggered by OSM alarms."""
53
54 def _set_headers(self):
55 """Set the headers for a request."""
56 self.send_response(200)
57 self.send_header('Content-type', 'text/html')
58 self.end_headers()
59
60 def do_GET(self):
61 """Get request functionality."""
62 self._set_headers()
63
64 def do_POST(self):
65 """POST request function."""
66 # Gets header and data from the post request and records info
67 self._set_headers()
68 # Gets the size of data
69 content_length = int(self.headers['Content-Length'])
70 post_data = self.rfile.read(content_length)
71 try:
72 post_data = post_data.decode()
73 except AttributeError:
74 pass
75 log.info("This alarm was triggered: %s", json.loads(post_data))
76
77 # Generate a notify_alarm response for the SO
78 self.notify_alarm(json.loads(post_data))
79
80 def notify_alarm(self, values):
81 """Send a notification response message to the SO."""
82
83 try:
84 # Initialise configuration and authentication for response message
85 config = Config.instance()
86 config.read_environ()
87 response = OpenStack_Response()
88 producer = KafkaProducer('alarm_response')
89
90 database_manager = DatabaseManager()
91
92 alarm_id = values['alarm_id']
93 alarm = database_manager.get_alarm(alarm_id, 'openstack')
94 # Process an alarm notification if resource_id is valid
95 # Get date and time for response message
96 a_date = time.strftime("%d-%m-%Y") + " " + time.strftime("%X")
97 # Try generate and send response
98 try:
99 resp_message = response.generate_response(
100 'notify_alarm', a_id=alarm_id,
101 vdu_name=alarm.vdu_name,
102 vnf_member_index=alarm.vnf_member_index,
103 ns_id=alarm.ns_id,
104 metric_name=alarm.metric_name,
105 operation=alarm.operation,
106 threshold_value=alarm.threshold,
107 sev=values['severity'],
108 date=a_date,
109 state=values['current'])
110 producer.notify_alarm(
111 'notify_alarm', resp_message)
112 log.info("Sent an alarm response to SO: %s", resp_message)
113 except Exception as exc:
114 log.exception("Couldn't notify SO of the alarm:")
115
116 except:
117 log.exception("Could not notify alarm.")
118
119
120 def run(server_class=HTTPServer, handler_class=NotifierHandler, port=8662):
121 """Run the webserver application to retrieve alarm notifications."""
122 try:
123 server_address = ('', port)
124 httpd = server_class(server_address, handler_class)
125 print('Starting alarm notifier...')
126 log.info("Starting alarm notifier server on port: %s", port)
127 httpd.serve_forever()
128 except Exception as exc:
129 log.warning("Failed to start webserver, %s", exc)
130
131
132 if __name__ == "__main__":
133 from sys import argv
134
135 # Runs the webserver
136 if len(argv) == 2:
137 run(port=int(argv[1]))
138 else:
139 run()