Updated plugins with new directory structure
[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
27 import logging
28
29 import os
30
31 import sys
32
33 import time
34
35 from BaseHTTPServer import BaseHTTPRequestHandler
36 from BaseHTTPServer import HTTPServer
37
38 # Initialise a logger for alarm notifier
39 logging.basicConfig(filename='aodh_notify.log',
40 format='%(asctime)s %(message)s',
41 datefmt='%m/%d/%Y %I:%M:%S %p', filemode='a',
42 level=logging.INFO)
43 log = logging.getLogger(__name__)
44
45 sys.path.insert(0, os.path.abspath('../'))
46
47 from osm_mon.core.message_bus.producer import KafkaProducer
48
49 from osm_mon.plugins.OpenStack.Aodh.alarming import Alarming
50 from osm_mon.plugins.OpenStack.common import Common
51 from osm_mon.plugins.OpenStack.response import OpenStack_Response
52 from osm_mon.plugins.OpenStack.settings import Config
53
54
55 class NotifierHandler(BaseHTTPRequestHandler):
56 """Handler class for alarm_actions triggered by OSM alarms."""
57
58 def _set_headers(self):
59 """Set the headers for a request."""
60 self.send_response(200)
61 self.send_header('Content-type', 'text/html')
62 self.end_headers()
63
64 def do_GET(self):
65 """Get request functionality."""
66 self._set_headers()
67 self.wfile.write("<html><body><h1>hi!</h1></body></html>")
68
69 def do_POST(self):
70 """POST request function."""
71 # Gets header and data from the post request and records info
72 self._set_headers()
73 # Gets the size of data
74 content_length = int(self.headers['Content-Length'])
75 post_data = self.rfile.read(content_length)
76 self.wfile.write("<html><body><h1>POST!</h1></body></tml>")
77 log.info("This alarm was triggered: %s", json.loads(post_data))
78
79 # Generate a notify_alarm response for the SO
80 self.notify_alarm(json.loads(post_data))
81
82 def notify_alarm(self, values):
83 """Send a notifcation repsonse message to the SO."""
84 # Initialiase configuration and authentication for response message
85 config = Config.instance()
86 config.read_environ("aodh")
87 self._alarming = Alarming()
88 self._common = Common()
89 self._response = OpenStack_Response()
90 self._producer = KafkaProducer('alarm_response')
91
92 alarm_id = values['alarm_id']
93 auth_token = self._common._authenticate()
94 endpoint = self._common.get_endpoint("alarming")
95
96 # If authenticated generate and send response message
97 if (auth_token is not None and endpoint is not None):
98 url = "{}/v2/alarms/%s".format(endpoint) % alarm_id
99
100 # Get the resource_id of the triggered alarm
101 result = self._common._perform_request(
102 url, auth_token, req_type="get")
103 alarm_details = json.loads(result.text)
104 gnocchi_rule = alarm_details['gnocchi_resources_threshold_rule']
105 resource_id = gnocchi_rule['resource_id']
106
107 # Process an alarm notification if resource_id is valid
108 if resource_id is not None:
109 # Get date and time for response message
110 a_date = time.strftime("%d-%m-%Y") + " " + time.strftime("%X")
111 # Try generate and send response
112 try:
113 resp_message = self._response.generate_response(
114 'notify_alarm', a_id=alarm_id,
115 r_id=resource_id,
116 sev=values['severity'], date=a_date,
117 state=values['current'], vim_type="OpenStack")
118 self._producer.notify_alarm(
119 'notify_alarm', resp_message, 'alarm_response')
120 log.info("Sent an alarm response to SO: %s", resp_message)
121 except Exception as exc:
122 log.warn("Couldn't notify SO of the alarm: %s", exc)
123 else:
124 log.warn("No resource_id for alarm; no SO response sent.")
125 else:
126 log.warn("Authentication failure; SO notification not sent.")
127
128
129 def run(server_class=HTTPServer, handler_class=NotifierHandler, port=8662):
130 """Run the webserver application to retreive alarm notifications."""
131 try:
132 server_address = ('', port)
133 httpd = server_class(server_address, handler_class)
134 print('Starting alarm notifier...')
135 log.info("Starting alarm notifier server on port: %s", port)
136 httpd.serve_forever()
137 except Exception as exc:
138 log.warn("Failed to start webserver, %s", exc)
139
140 if __name__ == "__main__":
141 from sys import argv
142
143 # Runs the webserver
144 if len(argv) == 2:
145 run(port=int(argv[1]))
146 else:
147 run()