ad12adaefceedb5d368abe72dd52e3e0562f11ad
1 # Copyright 2017 Intel Research and Development Ireland Limited
2 # *************************************************************
4 # This file is part of OSM Monitoring module
5 # All Rights Reserved to Intel Corporation
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
11 # http://www.apache.org/licenses/LICENSE-2.0
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
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
22 # __author__ = Helena McGough
24 """A Webserver to send alarm notifications from Aodh to the SO."""
35 from BaseHTTPServer
import BaseHTTPRequestHandler
36 from BaseHTTPServer
import HTTPServer
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',
43 log
= logging
.getLogger(__name__
)
45 sys
.path
.insert(0, os
.path
.abspath('../'))
47 from osm_mon
.core
.message_bus
.producer
import KafkaProducer
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
55 class NotifierHandler(BaseHTTPRequestHandler
):
56 """Handler class for alarm_actions triggered by OSM alarms."""
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')
65 """Get request functionality."""
67 self
.wfile
.write("<html><body><h1>hi!</h1></body></html>")
70 """POST request function."""
71 # Gets header and data from the post request and records info
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
))
79 # Generate a notify_alarm response for the SO
80 self
.notify_alarm(json
.loads(post_data
))
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')
92 alarm_id
= values
['alarm_id']
93 auth_token
= self
._common
._authenticate
()
94 endpoint
= self
._common
.get_endpoint("alarming")
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
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']
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
113 resp_message
= self
._response
.generate_response(
114 'notify_alarm', a_id
=alarm_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
)
124 log
.warn("No resource_id for alarm; no SO response sent.")
126 log
.warn("Authentication failure; SO notification not sent.")
129 def run(server_class
=HTTPServer
, handler_class
=NotifierHandler
, port
=8662):
130 """Run the webserver application to retreive alarm notifications."""
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
)
140 if __name__
== "__main__":
145 run(port
=int(argv
[1]))