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."""
31 from six
.moves
.BaseHTTPServer
import BaseHTTPRequestHandler
32 from six
.moves
.BaseHTTPServer
import HTTPServer
34 # Initialise a logger for alarm notifier
36 logging
.basicConfig(stream
=sys
.stdout
,
37 format
='%(asctime)s %(message)s',
38 datefmt
='%m/%d/%Y %I:%M:%S %p',
40 log
= logging
.getLogger(__name__
)
42 sys
.path
.append(os
.path
.abspath(os
.path
.join(os
.path
.realpath(__file__
), '..', '..', '..', '..', '..')))
44 from osm_mon
.core
.database
import DatabaseManager
45 from osm_mon
.core
.message_bus
.producer
import KafkaProducer
47 from osm_mon
.plugins
.OpenStack
.common
import Common
48 from osm_mon
.plugins
.OpenStack
.response
import OpenStack_Response
49 from osm_mon
.core
.settings
import Config
52 class NotifierHandler(BaseHTTPRequestHandler
):
53 """Handler class for alarm_actions triggered by OSM alarms."""
55 def _set_headers(self
):
56 """Set the headers for a request."""
57 self
.send_response(200)
58 self
.send_header('Content-type', 'text/html')
62 """Get request functionality."""
66 """POST request function."""
67 # Gets header and data from the post request and records info
69 # Gets the size of data
70 content_length
= int(self
.headers
['Content-Length'])
71 post_data
= self
.rfile
.read(content_length
)
73 post_data
= post_data
.decode()
74 except AttributeError:
76 log
.info("This alarm was triggered: %s", json
.loads(post_data
))
78 # Generate a notify_alarm response for the SO
79 self
.notify_alarm(json
.loads(post_data
))
81 def notify_alarm(self
, values
):
82 """Send a notification response message to the SO."""
85 # Initialise configuration and authentication for response message
86 config
= Config
.instance()
88 response
= OpenStack_Response()
89 producer
= KafkaProducer('alarm_response')
91 database_manager
= DatabaseManager()
93 alarm_id
= values
['alarm_id']
94 # Get vim_uuid associated to alarm
95 creds
= database_manager
.get_credentials_for_alarm_id(alarm_id
, 'openstack')
96 auth_token
= Common
.get_auth_token(creds
.uuid
)
97 endpoint
= Common
.get_endpoint("alarming", creds
.uuid
)
99 # If authenticated generate and send response message
100 if auth_token
is not None and endpoint
is not None:
101 url
= "{}/v2/alarms/%s".format(endpoint
) % alarm_id
103 # Get the resource_id of the triggered alarm
104 result
= Common
.perform_request(
105 url
, auth_token
, req_type
="get")
106 alarm_details
= json
.loads(result
.text
)
107 gnocchi_rule
= alarm_details
['gnocchi_resources_threshold_rule']
108 resource_id
= gnocchi_rule
['resource_id']
110 # Process an alarm notification if resource_id is valid
111 if resource_id
is not None:
112 # Get date and time for response message
113 a_date
= time
.strftime("%d-%m-%Y") + " " + time
.strftime("%X")
114 # Try generate and send response
116 resp_message
= response
.generate_response(
117 'notify_alarm', a_id
=alarm_id
,
119 sev
=values
['severity'], date
=a_date
,
120 state
=values
['current'], vim_type
="openstack")
121 producer
.notify_alarm(
122 'notify_alarm', resp_message
)
123 log
.info("Sent an alarm response to SO: %s", resp_message
)
124 except Exception as exc
:
125 log
.exception("Couldn't notify SO of the alarm:")
127 log
.warning("No resource_id for alarm; no SO response sent.")
129 log
.warning("Authentication failure; SO notification not sent.")
131 log
.exception("Could not notify alarm.")
134 def run(server_class
=HTTPServer
, handler_class
=NotifierHandler
, port
=8662):
135 """Run the webserver application to retrieve alarm notifications."""
137 server_address
= ('', port
)
138 httpd
= server_class(server_address
, handler_class
)
139 print('Starting alarm notifier...')
140 log
.info("Starting alarm notifier server on port: %s", port
)
141 httpd
.serve_forever()
142 except Exception as exc
:
143 log
.warning("Failed to start webserver, %s", exc
)
146 if __name__
== "__main__":
151 run(port
=int(argv
[1]))