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 OpenStack metric requests via Gnocchi API."""
32 from osm_mon
.core
.message_bus
.producer
import KafkaProducer
33 from osm_mon
.plugins
.OpenStack
.common
import Common
35 from osm_mon
.plugins
.OpenStack
.response
import OpenStack_Response
36 from osm_mon
.plugins
.OpenStack
.settings
import Config
38 log
= logging
.getLogger(__name__
)
41 "average_memory_utilization": "memory.percent",
42 "disk_read_ops": "disk.read.requests",
43 "disk_write_ops": "disk.write.requests",
44 "disk_read_bytes": "disk.read.bytes",
45 "disk_write_bytes": "disk.write.bytes",
46 "packets_dropped": "interface.if_dropped",
47 "packets_received": "interface.if_packets",
48 "packets_sent": "interface.if_packets",
49 "cpu_utilization": "cpu_util",
61 class Metrics(object):
62 """OpenStack metric requests performed via the Gnocchi API."""
65 """Initialize the metric actions."""
66 # Configure an instance of the OpenStack metric plugin
67 config
= Config
.instance()
70 # Initialise authentication for API requests
71 self
._common
= Common()
73 # Use the Response class to generate valid json response messages
74 self
._response
= OpenStack_Response()
76 # Initializer a producer to send responses back to SO
77 self
._producer
= KafkaProducer("metric_response")
79 def metric_calls(self
, message
):
80 """Consume info from the message bus to manage metric requests."""
81 values
= json
.loads(message
.value
)
82 log
.info("OpenStack metric action required.")
84 auth_token
= Common
.get_auth_token(values
['vim_uuid'])
86 endpoint
= Common
.get_endpoint("metric", values
['vim_uuid'])
88 if message
.key
== "create_metric_request":
90 metric_details
= values
['metric_create']
91 metric_id
, resource_id
, status
= self
.configure_metric(
92 endpoint
, auth_token
, metric_details
)
94 # Generate and send a create metric response
96 resp_message
= self
._response
.generate_response(
97 'create_metric_response', status
=status
,
98 cor_id
=values
['correlation_id'],
99 metric_id
=metric_id
, r_id
=resource_id
)
100 log
.info("Response messages: %s", resp_message
)
101 self
._producer
.create_metrics_resp(
102 'create_metric_response', resp_message
,
104 except Exception as exc
:
105 log
.warn("Failed to create response: %s", exc
)
107 elif message
.key
== "read_metric_data_request":
108 # Read all metric data related to a specified metric
109 timestamps
, metric_data
= self
.read_metric_data(
110 endpoint
, auth_token
, values
)
112 # Generate and send a response message
114 resp_message
= self
._response
.generate_response(
115 'read_metric_data_response',
116 m_id
=values
['metric_uuid'],
117 m_name
=values
['metric_name'],
118 r_id
=values
['resource_uuid'],
119 cor_id
=values
['correlation_id'],
120 times
=timestamps
, metrics
=metric_data
)
121 log
.info("Response message: %s", resp_message
)
122 self
._producer
.read_metric_data_response(
123 'read_metric_data_response', resp_message
,
125 except Exception as exc
:
126 log
.warn("Failed to send read metric response:%s", exc
)
128 elif message
.key
== "delete_metric_request":
129 # delete the specified metric in the request
130 metric_id
= values
['metric_uuid']
131 status
= self
.delete_metric(
132 endpoint
, auth_token
, metric_id
)
134 # Generate and send a response message
136 resp_message
= self
._response
.generate_response(
137 'delete_metric_response', m_id
=metric_id
,
138 m_name
=values
['metric_name'],
139 status
=status
, r_id
=values
['resource_uuid'],
140 cor_id
=values
['correlation_id'])
141 log
.info("Response message: %s", resp_message
)
142 self
._producer
.delete_metric_response(
143 'delete_metric_response', resp_message
,
145 except Exception as exc
:
146 log
.warn("Failed to send delete response:%s", exc
)
148 elif message
.key
== "update_metric_request":
149 # Gnocchi doesn't support configuration updates
150 # Log and send a response back to this effect
151 log
.warn("Gnocchi doesn't support metric configuration\
153 req_details
= values
['metric_create']
154 metric_name
= req_details
['metric_name']
155 resource_id
= req_details
['resource_uuid']
156 metric_id
= self
.get_metric_id(
157 endpoint
, auth_token
, metric_name
, resource_id
)
159 # Generate and send a response message
161 resp_message
= self
._response
.generate_response(
162 'update_metric_response', status
=False,
163 cor_id
=values
['correlation_id'],
164 r_id
=resource_id
, m_id
=metric_id
)
165 log
.info("Response message: %s", resp_message
)
166 self
._producer
.update_metric_response(
167 'update_metric_response', resp_message
,
169 except Exception as exc
:
170 log
.warn("Failed to send an update response:%s", exc
)
172 elif message
.key
== "list_metric_request":
173 list_details
= values
['metrics_list_request']
175 metric_list
= self
.list_metrics(
176 endpoint
, auth_token
, list_details
)
178 # Generate and send a response message
180 resp_message
= self
._response
.generate_response(
181 'list_metric_response', m_list
=metric_list
,
182 cor_id
=list_details
['correlation_id'])
183 log
.info("Response message: %s", resp_message
)
184 self
._producer
.list_metric_response(
185 'list_metric_response', resp_message
,
187 except Exception as exc
:
188 log
.warn("Failed to send a list response:%s", exc
)
191 log
.warn("Unknown key, no action will be performed.")
195 def configure_metric(self
, endpoint
, auth_token
, values
):
196 """Create the new metric in Gnocchi."""
198 resource_id
= values
['resource_uuid']
200 log
.warn("Resource is not defined correctly.")
201 return None, None, False
203 # Check/Normalize metric name
204 norm_name
, metric_name
= self
.get_metric_name(values
)
205 if metric_name
is None:
206 log
.warn("This metric is not supported by this plugin.")
207 return None, resource_id
, False
209 # Check for an existing metric for this resource
210 metric_id
= self
.get_metric_id(
211 endpoint
, auth_token
, metric_name
, resource_id
)
213 if metric_id
is None:
214 # Try appending metric to existing resource
216 base_url
= "{}/v1/resource/generic/%s/metric"
217 res_url
= base_url
.format(endpoint
) % resource_id
218 payload
= {metric_name
: {'archive_policy_name': 'high',
219 'unit': values
['metric_unit']}}
220 result
= Common
.perform_request(
221 res_url
, auth_token
, req_type
="post",
222 payload
=json
.dumps(payload
))
223 # Get id of newly created metric
224 for row
in json
.loads(result
.text
):
225 if row
['name'] == metric_name
:
226 metric_id
= row
['id']
227 log
.info("Appended metric to existing resource.")
229 return metric_id
, resource_id
, True
230 except Exception as exc
:
231 # Gnocchi version of resource does not exist creating a new one
232 log
.info("Failed to append metric to existing resource:%s",
235 url
= "{}/v1/resource/generic".format(endpoint
)
236 metric
= {'name': metric_name
,
237 'archive_policy_name': 'high',
238 'unit': values
['metric_unit'], }
240 resource_payload
= json
.dumps({'id': resource_id
,
242 metric_name
: metric
}})
244 resource
= Common
.perform_request(
245 url
, auth_token
, req_type
="post",
246 payload
=resource_payload
)
248 # Return the newly created resource_id for creating alarms
249 new_resource_id
= json
.loads(resource
.text
)['id']
250 log
.info("Created new resource for metric: %s",
253 metric_id
= self
.get_metric_id(
254 endpoint
, auth_token
, metric_name
, new_resource_id
)
256 return metric_id
, new_resource_id
, True
257 except Exception as exc
:
258 log
.warn("Failed to create a new resource:%s", exc
)
259 return None, None, False
262 log
.info("This metric already exists for this resource.")
264 return metric_id
, resource_id
, False
266 def delete_metric(self
, endpoint
, auth_token
, metric_id
):
268 url
= "{}/v1/metric/%s".format(endpoint
) % metric_id
271 result
= Common
.perform_request(
272 url
, auth_token
, req_type
="delete")
273 if str(result
.status_code
) == "404":
274 log
.warn("Failed to delete the metric.")
278 except Exception as exc
:
279 log
.warn("Failed to carry out delete metric request:%s", exc
)
282 def list_metrics(self
, endpoint
, auth_token
, values
):
283 """List all metrics."""
285 # Check for a specified list
287 # Check if the metric_name was specified for the list
288 metric_name
= values
['metric_name'].lower()
289 if metric_name
not in METRIC_MAPPINGS
.keys():
290 log
.warn("This metric is not supported, won't be listed.")
292 except KeyError as exc
:
293 log
.info("Metric name is not specified: %s", exc
)
297 resource
= values
['resource_uuid']
298 except KeyError as exc
:
299 log
.info("Resource is not specified:%s", exc
)
303 url
= "{}/v1/metric?sort=name:asc".format(endpoint
)
304 result
= Common
.perform_request(
305 url
, auth_token
, req_type
="get")
307 metrics_partial
= json
.loads(result
.text
)
308 for metric
in metrics_partial
:
309 metrics
.append(metric
)
311 while len(json
.loads(result
.text
)) > 0:
312 last_metric_id
= metrics_partial
[-1]['id']
313 url
= "{}/v1/metric?sort=name:asc&marker={}".format(endpoint
, last_metric_id
)
314 result
= Common
.perform_request(
315 url
, auth_token
, req_type
="get")
316 if len(json
.loads(result
.text
)) > 0:
317 metrics_partial
= json
.loads(result
.text
)
318 for metric
in metrics_partial
:
319 metrics
.append(metric
)
321 if metrics
is not None:
322 # Format the list response
323 if metric_name
is not None and resource
is not None:
324 metric_list
= self
.response_list(
325 metrics
, metric_name
=metric_name
, resource
=resource
)
326 log
.info("Returning an %s resource list for %s metrics",
327 metric_name
, resource
)
328 elif metric_name
is not None:
329 metric_list
= self
.response_list(
330 metrics
, metric_name
=metric_name
)
331 log
.info("Returning a list of %s metrics", metric_name
)
332 elif resource
is not None:
333 metric_list
= self
.response_list(
334 metrics
, resource
=resource
)
335 log
.info("Return a list of %s resource metrics", resource
)
337 metric_list
= self
.response_list(metrics
)
338 log
.info("Returning a complete list of metrics")
342 log
.info("There are no metrics available")
344 except Exception as exc
:
345 log
.warn("Failed to generate any metric list. %s", exc
)
348 def get_metric_id(self
, endpoint
, auth_token
, metric_name
, resource_id
):
349 """Check if the desired metric already exists for the resource."""
350 url
= "{}/v1/resource/generic/%s".format(endpoint
) % resource_id
353 # Try return the metric id if it exists
354 result
= Common
.perform_request(
355 url
, auth_token
, req_type
="get")
356 return json
.loads(result
.text
)['metrics'][metric_name
]
358 log
.info("Metric doesn't exist. No metric_id available")
361 def get_metric_name(self
, values
):
362 """Check metric name configuration and normalize."""
365 # Normalize metric name
366 metric_name
= values
['metric_name'].lower()
367 return metric_name
, METRIC_MAPPINGS
[metric_name
]
369 log
.info("Metric name %s is invalid.", metric_name
)
370 return metric_name
, None
372 def read_metric_data(self
, endpoint
, auth_token
, values
):
373 """Collect metric measures over a specified time period."""
377 # Try and collect measures
378 metric_id
= values
['metric_uuid']
379 collection_unit
= values
['collection_unit'].upper()
380 collection_period
= values
['collection_period']
382 # Define the start and end time based on configurations
383 # FIXME: Local timezone may differ from timezone set in Gnocchi, causing discrepancies in measures
384 stop_time
= time
.strftime("%Y-%m-%d") + "T" + time
.strftime("%X")
385 end_time
= int(round(time
.time() * 1000))
386 if collection_unit
== 'YEAR':
387 diff
= PERIOD_MS
[collection_unit
]
389 diff
= collection_period
* PERIOD_MS
[collection_unit
]
390 s_time
= (end_time
- diff
) / 1000.0
391 start_time
= datetime
.datetime
.fromtimestamp(s_time
).strftime(
392 '%Y-%m-%dT%H:%M:%S.%f')
393 base_url
= "{}/v1/metric/%(0)s/measures?start=%(1)s&stop=%(2)s"
394 url
= base_url
.format(endpoint
) % {
395 "0": metric_id
, "1": start_time
, "2": stop_time
}
397 # Perform metric data request
398 metric_data
= Common
.perform_request(
399 url
, auth_token
, req_type
="get")
401 # Generate a list of the requested timestamps and data
402 for r
in json
.loads(metric_data
.text
):
403 timestamp
= r
[0].replace("T", " ")
404 timestamps
.append(timestamp
)
407 return timestamps
, data
408 except Exception as exc
:
409 log
.warn("Failed to gather specified measures: %s", exc
)
410 return timestamps
, data
412 def response_list(self
, metric_list
, metric_name
=None, resource
=None):
413 """Create the appropriate lists for a list response."""
414 resp_list
, name_list
, res_list
= [], [], []
416 # Create required lists
417 for row
in metric_list
:
418 # Only list OSM metrics
420 if row
['name'] in METRIC_MAPPINGS
.values():
421 for k
,v
in six
.iteritems(METRIC_MAPPINGS
):
424 metric
= {"metric_name": name
,
425 "metric_uuid": row
['id'],
426 "metric_unit": row
['unit'],
427 "resource_uuid": row
['resource_id']}
428 resp_list
.append(metric
)
429 # Generate metric_name specific list
430 if metric_name
is not None and name
is not None:
431 if metric_name
in METRIC_MAPPINGS
.keys() and row
['name'] == METRIC_MAPPINGS
[metric_name
]:
432 metric
= {"metric_name": metric_name
,
433 "metric_uuid": row
['id'],
434 "metric_unit": row
['unit'],
435 "resource_uuid": row
['resource_id']}
436 name_list
.append(metric
)
437 # Generate resource specific list
438 if resource
is not None and name
is not None:
439 if row
['resource_id'] == resource
:
440 metric
= {"metric_name": name
,
441 "metric_uuid": row
['id'],
442 "metric_unit": row
['unit'],
443 "resource_uuid": row
['resource_id']}
444 res_list
.append(metric
)
446 # Join required lists
447 if metric_name
is not None and resource
is not None:
448 # Return intersection of res_list and name_list
449 return [i
for i
in res_list
for j
in name_list
if i
['metric_uuid'] == j
['metric_uuid']]
450 elif metric_name
is not None:
452 elif resource
is not None: