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 """Carry out alarming requests via Aodh API."""
30 from osm_mon
.core
.auth
import AuthManager
31 from osm_mon
.core
.database
import DatabaseManager
32 from osm_mon
.core
.message_bus
.producer
import KafkaProducer
33 from osm_mon
.core
.settings
import Config
34 from osm_mon
.plugins
.OpenStack
.Gnocchi
.metrics
import METRIC_MAPPINGS
35 from osm_mon
.plugins
.OpenStack
.common
import Common
36 from osm_mon
.plugins
.OpenStack
.response
import OpenStack_Response
38 log
= logging
.getLogger(__name__
)
44 "critical": "critical",
45 "indeterminate": "critical"}
55 class Alarming(object):
56 """Carries out alarming requests and responses via Aodh API."""
59 """Create the OpenStack alarming instance."""
60 self
._database
_manager
= DatabaseManager()
61 self
._auth
_manager
= AuthManager()
63 # Use the Response class to generate valid json response messages
64 self
._response
= OpenStack_Response()
66 # Initializer a producer to send responses back to SO
67 self
._producer
= KafkaProducer("alarm_response")
69 def alarming(self
, message
, vim_uuid
):
71 Processes alarm request message depending on it's key
72 :param message: Message containing key and value attributes. This last one can be in JSON or YAML format.
73 :param vim_uuid: UUID of the VIM to handle the alarm request.
77 values
= json
.loads(message
.value
)
79 values
= yaml
.safe_load(message
.value
)
81 log
.info("OpenStack alarm action required.")
83 verify_ssl
= self
._auth
_manager
.is_verify_ssl(vim_uuid
)
85 auth_token
= Common
.get_auth_token(vim_uuid
, verify_ssl
=verify_ssl
)
87 alarm_endpoint
= Common
.get_endpoint("alarming", vim_uuid
, verify_ssl
=verify_ssl
)
88 metric_endpoint
= Common
.get_endpoint("metric", vim_uuid
, verify_ssl
=verify_ssl
)
90 vim_account
= self
._auth
_manager
.get_credentials(vim_uuid
)
91 vim_config
= json
.loads(vim_account
.config
)
93 if message
.key
== "create_alarm_request":
94 alarm_details
= values
['alarm_create_request']
98 metric_name
= alarm_details
['metric_name'].lower()
99 resource_id
= alarm_details
['resource_uuid']
101 self
.check_for_metric(auth_token
, metric_endpoint
, metric_name
, resource_id
, verify_ssl
)
103 alarm_id
= self
.configure_alarm(
104 alarm_endpoint
, auth_token
, alarm_details
, vim_config
, verify_ssl
)
106 log
.info("Alarm successfully created")
107 self
._database
_manager
.save_alarm(alarm_id
,
109 alarm_details
['threshold_value'],
110 alarm_details
['operation'].lower(),
111 alarm_details
['metric_name'].lower(),
112 alarm_details
['vdu_name'].lower(),
113 alarm_details
['vnf_member_index'],
114 alarm_details
['ns_id'].lower()
117 except Exception as e
:
118 log
.exception("Error creating alarm")
121 self
._generate
_and
_send
_response
('create_alarm_response',
122 alarm_details
['correlation_id'],
126 elif message
.key
== "list_alarm_request":
127 list_details
= values
['alarm_list_request']
130 alarm_list
= self
.list_alarms(
131 alarm_endpoint
, auth_token
, list_details
, verify_ssl
)
132 except Exception as e
:
133 log
.exception("Error listing alarms")
136 self
._generate
_and
_send
_response
('list_alarm_response',
137 list_details
['correlation_id'],
138 alarm_list
=alarm_list
)
140 elif message
.key
== "delete_alarm_request":
141 request_details
= values
['alarm_delete_request']
142 alarm_id
= request_details
['alarm_uuid']
146 alarm_endpoint
, auth_token
, alarm_id
, verify_ssl
)
148 except Exception as e
:
149 log
.exception("Error deleting alarm")
152 self
._generate
_and
_send
_response
('delete_alarm_response',
153 request_details
['correlation_id'],
157 elif message
.key
== "acknowledge_alarm":
159 alarm_id
= values
['ack_details']['alarm_uuid']
161 self
.update_alarm_state(
162 alarm_endpoint
, auth_token
, alarm_id
, verify_ssl
)
164 log
.info("Acknowledged the alarm and cleared it.")
165 except Exception as e
:
166 log
.exception("Error acknowledging alarm")
169 elif message
.key
== "update_alarm_request":
170 # Update alarm configurations
171 alarm_details
= values
['alarm_update_request']
175 alarm_id
= self
.update_alarm(
176 alarm_endpoint
, auth_token
, alarm_details
, vim_config
, verify_ssl
)
178 except Exception as e
:
179 log
.exception("Error updating alarm")
182 self
._generate
_and
_send
_response
('update_alarm_response',
183 alarm_details
['correlation_id'],
188 log
.debug("Unknown key, no action will be performed")
190 def configure_alarm(self
, alarm_endpoint
, auth_token
, values
, vim_config
, verify_ssl
):
191 """Create requested alarm in Aodh."""
192 url
= "{}/v2/alarms/".format(alarm_endpoint
)
194 # Check if the desired alarm is supported
195 alarm_name
= values
['alarm_name'].lower()
196 metric_name
= values
['metric_name'].lower()
197 resource_id
= values
['resource_uuid']
199 if metric_name
not in METRIC_MAPPINGS
.keys():
200 raise KeyError("Metric {} is not supported.".format(metric_name
))
202 if 'granularity' in vim_config
and 'granularity' not in values
:
203 values
['granularity'] = vim_config
['granularity']
204 payload
= self
.check_payload(values
, metric_name
, resource_id
,
206 new_alarm
= Common
.perform_request(
207 url
, auth_token
, req_type
="post", payload
=payload
, verify_ssl
=verify_ssl
)
208 return json
.loads(new_alarm
.text
)['alarm_id']
210 def delete_alarm(self
, endpoint
, auth_token
, alarm_id
, verify_ssl
):
211 """Delete alarm function."""
212 url
= "{}/v2/alarms/%s".format(endpoint
) % alarm_id
214 result
= Common
.perform_request(
215 url
, auth_token
, req_type
="delete", verify_ssl
=verify_ssl
)
216 if str(result
.status_code
) == "404":
217 raise ValueError("Alarm {} doesn't exist".format(alarm_id
))
219 def list_alarms(self
, endpoint
, auth_token
, list_details
, verify_ssl
):
220 """Generate the requested list of alarms."""
221 url
= "{}/v2/alarms/".format(endpoint
)
222 a_list
, name_list
, sev_list
, res_list
= [], [], [], []
224 # TODO(mcgoughh): for now resource_id is a mandatory field
225 # Check for a resource id
227 resource
= list_details
['resource_uuid']
228 name
= list_details
['alarm_name'].lower()
229 severity
= list_details
['severity'].lower()
230 sev
= SEVERITIES
[severity
]
231 except KeyError as e
:
232 log
.warning("Missing parameter for alarm list request: %s", e
)
235 # Perform the request to get the desired list
237 result
= Common
.perform_request(
238 url
, auth_token
, req_type
="get", verify_ssl
=verify_ssl
)
240 if result
is not None:
241 # Get list based on resource id
242 for alarm
in json
.loads(result
.text
):
243 rule
= alarm
['gnocchi_resources_threshold_rule']
244 if resource
== rule
['resource_id']:
245 res_list
.append(alarm
['alarm_id'])
247 # Generate specified listed if requested
248 if name
is not None and sev
is not None:
249 log
.info("Return a list of %s alarms with %s severity.",
251 for alarm
in json
.loads(result
.text
):
252 if name
== alarm
['name']:
253 name_list
.append(alarm
['alarm_id'])
254 for alarm
in json
.loads(result
.text
):
255 if sev
== alarm
['severity']:
256 sev_list
.append(alarm
['alarm_id'])
257 name_sev_list
= list(set(name_list
).intersection(sev_list
))
258 a_list
= list(set(name_sev_list
).intersection(res_list
))
259 elif name
is not None:
260 log
.info("Returning a %s list of alarms.", name
)
261 for alarm
in json
.loads(result
.text
):
262 if name
== alarm
['name']:
263 name_list
.append(alarm
['alarm_id'])
264 a_list
= list(set(name_list
).intersection(res_list
))
265 elif sev
is not None:
266 log
.info("Returning %s severity alarm list.", sev
)
267 for alarm
in json
.loads(result
.text
):
268 if sev
== alarm
['severity']:
269 sev_list
.append(alarm
['alarm_id'])
270 a_list
= list(set(sev_list
).intersection(res_list
))
272 log
.info("Returning an entire list of alarms.")
275 log
.info("There are no alarms!")
277 for alarm
in json
.loads(result
.text
):
278 if alarm
['alarm_id'] in a_list
:
279 response_list
.append(alarm
)
282 except Exception as e
:
283 log
.exception("Failed to generate alarm list: ")
286 def update_alarm_state(self
, endpoint
, auth_token
, alarm_id
, verify_ssl
):
287 """Set the state of an alarm to ok when ack message is received."""
288 url
= "{}/v2/alarms/%s/state".format(endpoint
) % alarm_id
289 payload
= json
.dumps("ok")
291 Common
.perform_request(
292 url
, auth_token
, req_type
="put", payload
=payload
, verify_ssl
=verify_ssl
)
294 def update_alarm(self
, endpoint
, auth_token
, values
, vim_config
, verify_ssl
):
295 """Get alarm name for an alarm configuration update."""
296 # Get already existing alarm details
297 url
= "{}/v2/alarms/%s".format(endpoint
) % values
['alarm_uuid']
299 # Gets current configurations about the alarm
300 result
= Common
.perform_request(
301 url
, auth_token
, req_type
="get")
302 alarm_name
= json
.loads(result
.text
)['name']
303 rule
= json
.loads(result
.text
)['gnocchi_resources_threshold_rule']
304 alarm_state
= json
.loads(result
.text
)['state']
305 resource_id
= rule
['resource_id']
306 metric_name
= [key
for key
, value
in six
.iteritems(METRIC_MAPPINGS
) if value
== rule
['metric']][0]
308 # Generates and check payload configuration for alarm update
309 if 'granularity' in vim_config
and 'granularity' not in values
:
310 values
['granularity'] = vim_config
['granularity']
311 payload
= self
.check_payload(values
, metric_name
, resource_id
,
312 alarm_name
, alarm_state
=alarm_state
)
314 # Updates the alarm configurations with the valid payload
315 update_alarm
= Common
.perform_request(
316 url
, auth_token
, req_type
="put", payload
=payload
, verify_ssl
=verify_ssl
)
318 return json
.loads(update_alarm
.text
)['alarm_id']
320 def check_payload(self
, values
, metric_name
, resource_id
,
321 alarm_name
, alarm_state
=None):
322 """Check that the payload is configuration for update/create alarm."""
323 cfg
= Config
.instance()
324 # Check state and severity
326 severity
= 'critical'
327 if 'severity' in values
:
328 severity
= values
['severity'].lower()
330 if severity
== "indeterminate":
331 alarm_state
= "insufficient data"
332 if alarm_state
is None:
335 statistic
= values
['statistic'].lower()
337 granularity
= cfg
.OS_DEFAULT_GRANULARITY
338 if 'granularity' in values
:
339 granularity
= values
['granularity']
341 resource_type
= 'generic'
342 if 'resource_type' in values
:
343 resource_type
= values
['resource_type'].lower()
345 # Try to configure the payload for the update/create request
346 # Can only update: threshold, operation, statistic and
347 # the severity of the alarm
348 rule
= {'threshold': values
['threshold_value'],
349 'comparison_operator': values
['operation'].lower(),
350 'metric': METRIC_MAPPINGS
[metric_name
],
351 'resource_id': resource_id
,
352 'resource_type': resource_type
,
353 'aggregation_method': STATISTICS
[statistic
],
354 'granularity': granularity
, }
355 payload
= json
.dumps({'state': alarm_state
,
357 'severity': SEVERITIES
[severity
],
358 'type': 'gnocchi_resources_threshold',
359 'gnocchi_resources_threshold_rule': rule
,
360 'alarm_actions': [cfg
.OS_NOTIFIER_URI
],
361 'repeat_actions': True}, sort_keys
=True)
364 def get_alarm_state(self
, endpoint
, auth_token
, alarm_id
):
365 """Get the state of the alarm."""
366 url
= "{}/v2/alarms/%s/state".format(endpoint
) % alarm_id
368 alarm_state
= Common
.perform_request(
369 url
, auth_token
, req_type
="get")
370 return json
.loads(alarm_state
.text
)
372 def check_for_metric(self
, auth_token
, metric_endpoint
, metric_name
, resource_id
, verify_ssl
):
374 Checks if resource has a specific metric. If not, throws exception.
375 :param auth_token: OpenStack auth token
376 :param metric_endpoint: OpenStack metric endpoint
377 :param metric_name: Metric name
378 :param resource_id: Resource UUID
379 :return: Metric details from resource
380 :raise Exception: Could not retrieve metric from resource
383 url
= "{}/v1/resource/generic/{}".format(metric_endpoint
, resource_id
)
384 result
= Common
.perform_request(
385 url
, auth_token
, req_type
="get", verify_ssl
=verify_ssl
)
386 resource
= json
.loads(result
.text
)
387 metrics_dict
= resource
['metrics']
388 return metrics_dict
[METRIC_MAPPINGS
[metric_name
]]
389 except Exception as e
:
390 log
.exception("Desired Gnocchi metric not found:", e
)
393 def _generate_and_send_response(self
, key
, correlation_id
, **kwargs
):
395 resp_message
= self
._response
.generate_response(
396 key
, cor_id
=correlation_id
, **kwargs
)
397 log
.info("Response Message: %s", resp_message
)
398 self
._producer
.publish_alarm_response(
400 except Exception as e
:
401 log
.exception("Response creation failed:")