f380b4e59c38566d1efe195a4c6e2b623371eaac
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 auth_token
= Common
.get_auth_token(vim_uuid
)
85 alarm_endpoint
= Common
.get_endpoint("alarming", vim_uuid
)
86 metric_endpoint
= Common
.get_endpoint("metric", vim_uuid
)
88 vim_account
= self
._auth
_manager
.get_credentials(vim_uuid
)
89 vim_config
= json
.loads(vim_account
.config
)
91 if message
.key
== "create_alarm_request":
92 alarm_details
= values
['alarm_create_request']
96 metric_name
= alarm_details
['metric_name'].lower()
97 resource_id
= alarm_details
['resource_uuid']
99 self
.check_for_metric(auth_token
, metric_endpoint
, metric_name
, resource_id
)
101 alarm_id
= self
.configure_alarm(
102 alarm_endpoint
, auth_token
, alarm_details
, vim_config
)
104 log
.info("Alarm successfully created")
105 self
._database
_manager
.save_alarm(alarm_id
,
107 alarm_details
['threshold_value'],
108 alarm_details
['operation'].lower(),
109 alarm_details
['metric_name'].lower(),
110 alarm_details
['vdu_name'].lower(),
111 alarm_details
['vnf_member_index'].lower(),
112 alarm_details
['ns_id'].lower()
115 except Exception as e
:
116 log
.exception("Error creating alarm")
119 self
._generate
_and
_send
_response
('create_alarm_response',
120 alarm_details
['correlation_id'],
124 elif message
.key
== "list_alarm_request":
125 list_details
= values
['alarm_list_request']
128 alarm_list
= self
.list_alarms(
129 alarm_endpoint
, auth_token
, list_details
)
130 except Exception as e
:
131 log
.exception("Error listing alarms")
134 self
._generate
_and
_send
_response
('list_alarm_response',
135 list_details
['correlation_id'],
136 alarm_list
=alarm_list
)
138 elif message
.key
== "delete_alarm_request":
139 request_details
= values
['alarm_delete_request']
140 alarm_id
= request_details
['alarm_uuid']
144 alarm_endpoint
, auth_token
, alarm_id
)
146 except Exception as e
:
147 log
.exception("Error deleting alarm")
150 self
._generate
_and
_send
_response
('delete_alarm_response',
151 request_details
['correlation_id'],
155 elif message
.key
== "acknowledge_alarm":
157 alarm_id
= values
['ack_details']['alarm_uuid']
159 self
.update_alarm_state(
160 alarm_endpoint
, auth_token
, alarm_id
)
162 log
.info("Acknowledged the alarm and cleared it.")
163 except Exception as e
:
164 log
.exception("Error acknowledging alarm")
167 elif message
.key
== "update_alarm_request":
168 # Update alarm configurations
169 alarm_details
= values
['alarm_update_request']
173 alarm_id
= self
.update_alarm(
174 alarm_endpoint
, auth_token
, alarm_details
, vim_config
)
176 except Exception as e
:
177 log
.exception("Error updating alarm")
180 self
._generate
_and
_send
_response
('update_alarm_response',
181 alarm_details
['correlation_id'],
186 log
.debug("Unknown key, no action will be performed")
188 def configure_alarm(self
, alarm_endpoint
, auth_token
, values
, vim_config
):
189 """Create requested alarm in Aodh."""
190 url
= "{}/v2/alarms/".format(alarm_endpoint
)
192 # Check if the desired alarm is supported
193 alarm_name
= values
['alarm_name'].lower()
194 metric_name
= values
['metric_name'].lower()
195 resource_id
= values
['resource_uuid']
197 if metric_name
not in METRIC_MAPPINGS
.keys():
198 raise KeyError("Metric {} is not supported.".format(metric_name
))
200 if 'granularity' in vim_config
and 'granularity' not in values
:
201 values
['granularity'] = vim_config
['granularity']
202 payload
= self
.check_payload(values
, metric_name
, resource_id
,
204 new_alarm
= Common
.perform_request(
205 url
, auth_token
, req_type
="post", payload
=payload
)
206 return json
.loads(new_alarm
.text
)['alarm_id']
208 def delete_alarm(self
, endpoint
, auth_token
, alarm_id
):
209 """Delete alarm function."""
210 url
= "{}/v2/alarms/%s".format(endpoint
) % alarm_id
212 result
= Common
.perform_request(
213 url
, auth_token
, req_type
="delete")
214 if str(result
.status_code
) == "404":
215 raise ValueError("Alarm {} doesn't exist".format(alarm_id
))
217 def list_alarms(self
, endpoint
, auth_token
, list_details
):
218 """Generate the requested list of alarms."""
219 url
= "{}/v2/alarms/".format(endpoint
)
220 a_list
, name_list
, sev_list
, res_list
= [], [], [], []
222 # TODO(mcgoughh): for now resource_id is a mandatory field
223 # Check for a resource id
225 resource
= list_details
['resource_uuid']
226 name
= list_details
['alarm_name'].lower()
227 severity
= list_details
['severity'].lower()
228 sev
= SEVERITIES
[severity
]
229 except KeyError as e
:
230 log
.warning("Missing parameter for alarm list request: %s", e
)
233 # Perform the request to get the desired list
235 result
= Common
.perform_request(
236 url
, auth_token
, req_type
="get")
238 if result
is not None:
239 # Get list based on resource id
240 for alarm
in json
.loads(result
.text
):
241 rule
= alarm
['gnocchi_resources_threshold_rule']
242 if resource
== rule
['resource_id']:
243 res_list
.append(alarm
['alarm_id'])
245 # Generate specified listed if requested
246 if name
is not None and sev
is not None:
247 log
.info("Return a list of %s alarms with %s severity.",
249 for alarm
in json
.loads(result
.text
):
250 if name
== alarm
['name']:
251 name_list
.append(alarm
['alarm_id'])
252 for alarm
in json
.loads(result
.text
):
253 if sev
== alarm
['severity']:
254 sev_list
.append(alarm
['alarm_id'])
255 name_sev_list
= list(set(name_list
).intersection(sev_list
))
256 a_list
= list(set(name_sev_list
).intersection(res_list
))
257 elif name
is not None:
258 log
.info("Returning a %s list of alarms.", name
)
259 for alarm
in json
.loads(result
.text
):
260 if name
== alarm
['name']:
261 name_list
.append(alarm
['alarm_id'])
262 a_list
= list(set(name_list
).intersection(res_list
))
263 elif sev
is not None:
264 log
.info("Returning %s severity alarm list.", sev
)
265 for alarm
in json
.loads(result
.text
):
266 if sev
== alarm
['severity']:
267 sev_list
.append(alarm
['alarm_id'])
268 a_list
= list(set(sev_list
).intersection(res_list
))
270 log
.info("Returning an entire list of alarms.")
273 log
.info("There are no alarms!")
275 for alarm
in json
.loads(result
.text
):
276 if alarm
['alarm_id'] in a_list
:
277 response_list
.append(alarm
)
280 except Exception as e
:
281 log
.exception("Failed to generate alarm list: ")
284 def update_alarm_state(self
, endpoint
, auth_token
, alarm_id
):
285 """Set the state of an alarm to ok when ack message is received."""
286 url
= "{}/v2/alarms/%s/state".format(endpoint
) % alarm_id
287 payload
= json
.dumps("ok")
289 Common
.perform_request(
290 url
, auth_token
, req_type
="put", payload
=payload
)
292 def update_alarm(self
, endpoint
, auth_token
, values
, vim_config
):
293 """Get alarm name for an alarm configuration update."""
294 # Get already existing alarm details
295 url
= "{}/v2/alarms/%s".format(endpoint
) % values
['alarm_uuid']
297 # Gets current configurations about the alarm
298 result
= Common
.perform_request(
299 url
, auth_token
, req_type
="get")
300 alarm_name
= json
.loads(result
.text
)['name']
301 rule
= json
.loads(result
.text
)['gnocchi_resources_threshold_rule']
302 alarm_state
= json
.loads(result
.text
)['state']
303 resource_id
= rule
['resource_id']
304 metric_name
= [key
for key
, value
in six
.iteritems(METRIC_MAPPINGS
) if value
== rule
['metric']][0]
306 # Generates and check payload configuration for alarm update
307 if 'granularity' in vim_config
and 'granularity' not in values
:
308 values
['granularity'] = vim_config
['granularity']
309 payload
= self
.check_payload(values
, metric_name
, resource_id
,
310 alarm_name
, alarm_state
=alarm_state
)
312 # Updates the alarm configurations with the valid payload
313 update_alarm
= Common
.perform_request(
314 url
, auth_token
, req_type
="put", payload
=payload
)
316 return json
.loads(update_alarm
.text
)['alarm_id']
318 def check_payload(self
, values
, metric_name
, resource_id
,
319 alarm_name
, alarm_state
=None):
320 """Check that the payload is configuration for update/create alarm."""
321 cfg
= Config
.instance()
322 # Check state and severity
324 severity
= 'critical'
325 if 'severity' in values
:
326 severity
= values
['severity'].lower()
328 if severity
== "indeterminate":
329 alarm_state
= "insufficient data"
330 if alarm_state
is None:
333 statistic
= values
['statistic'].lower()
335 granularity
= cfg
.OS_DEFAULT_GRANULARITY
336 if 'granularity' in values
:
337 granularity
= values
['granularity']
339 resource_type
= 'generic'
340 if 'resource_type' in values
:
341 resource_type
= values
['resource_type'].lower()
343 # Try to configure the payload for the update/create request
344 # Can only update: threshold, operation, statistic and
345 # the severity of the alarm
346 rule
= {'threshold': values
['threshold_value'],
347 'comparison_operator': values
['operation'].lower(),
348 'metric': METRIC_MAPPINGS
[metric_name
],
349 'resource_id': resource_id
,
350 'resource_type': resource_type
,
351 'aggregation_method': STATISTICS
[statistic
],
352 'granularity': granularity
, }
353 payload
= json
.dumps({'state': alarm_state
,
355 'severity': SEVERITIES
[severity
],
356 'type': 'gnocchi_resources_threshold',
357 'gnocchi_resources_threshold_rule': rule
,
358 'alarm_actions': [cfg
.OS_NOTIFIER_URI
], }, sort_keys
=True)
361 def get_alarm_state(self
, endpoint
, auth_token
, alarm_id
):
362 """Get the state of the alarm."""
363 url
= "{}/v2/alarms/%s/state".format(endpoint
) % alarm_id
365 alarm_state
= Common
.perform_request(
366 url
, auth_token
, req_type
="get")
367 return json
.loads(alarm_state
.text
)
369 def check_for_metric(self
, auth_token
, metric_endpoint
, metric_name
, resource_id
):
371 Checks if resource has a specific metric. If not, throws exception.
372 :param auth_token: OpenStack auth token
373 :param metric_endpoint: OpenStack metric endpoint
374 :param metric_name: Metric name
375 :param resource_id: Resource UUID
376 :return: Metric details from resource
377 :raise Exception: Could not retrieve metric from resource
380 url
= "{}/v1/resource/generic/{}".format(metric_endpoint
, resource_id
)
381 result
= Common
.perform_request(
382 url
, auth_token
, req_type
="get")
383 resource
= json
.loads(result
.text
)
384 metrics_dict
= resource
['metrics']
385 return metrics_dict
[METRIC_MAPPINGS
[metric_name
]]
386 except Exception as e
:
387 log
.exception("Desired Gnocchi metric not found:", e
)
390 def _generate_and_send_response(self
, key
, correlation_id
, **kwargs
):
392 resp_message
= self
._response
.generate_response(
393 key
, cor_id
=correlation_id
, **kwargs
)
394 log
.info("Response Message: %s", resp_message
)
395 self
._producer
.publish_alarm_response(
397 except Exception as e
:
398 log
.exception("Response creation failed:")