be2bdb7078e70608a85bf45a4d6c891ecaedac5f
[osm/MON.git] / osm_mon / collector / vnf_collectors / openstack.py
1 # Copyright 2018 Whitestack, LLC
2 # *************************************************************
3
4 # This file is part of OSM Monitoring module
5 # All Rights Reserved to Whitestack, LLC
6
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
10
11 # http://www.apache.org/licenses/LICENSE-2.0
12
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
17 # under the License.
18
19 # For those usages not covered by the Apache License, Version 2.0 please
20 # contact: bdiaz@whitestack.com or glavado@whitestack.com
21 ##
22 from enum import Enum
23 import logging
24 import time
25 from typing import List
26
27 from ceilometerclient import client as ceilometer_client
28 from ceilometerclient.exc import HTTPException
29 import gnocchiclient.exceptions
30 from gnocchiclient.v1 import client as gnocchi_client
31 from keystoneauth1.exceptions.catalog import EndpointNotFound
32 from keystoneclient.v3 import client as keystone_client
33 from neutronclient.v2_0 import client as neutron_client
34 from prometheus_api_client import PrometheusConnect as prometheus_client
35
36 from osm_mon.collector.metric import Metric
37 from osm_mon.collector.utils.openstack import OpenstackUtils
38 from osm_mon.collector.vnf_collectors.base_vim import BaseVimCollector
39 from osm_mon.collector.vnf_metric import VnfMetric
40 from osm_mon.core.common_db import CommonDbClient
41 from osm_mon.core.config import Config
42
43
44 log = logging.getLogger(__name__)
45
46 METRIC_MAPPINGS = {
47 "average_memory_utilization": "memory.usage",
48 "disk_read_ops": "disk.read.requests.rate",
49 "disk_write_ops": "disk.write.requests.rate",
50 "disk_read_bytes": "disk.read.bytes.rate",
51 "disk_write_bytes": "disk.write.bytes.rate",
52 "packets_in_dropped": "network.outgoing.packets.drop",
53 "packets_out_dropped": "network.incoming.packets.drop",
54 "packets_received": "network.incoming.packets.rate",
55 "packets_sent": "network.outgoing.packets.rate",
56 "cpu_utilization": "cpu",
57 }
58
59 # Metrics which have new names in Rocky and higher releases
60 METRIC_MAPPINGS_FOR_ROCKY_AND_NEWER_RELEASES = {
61 "disk_read_ops": "disk.device.read.requests",
62 "disk_write_ops": "disk.device.write.requests",
63 "disk_read_bytes": "disk.device.read.bytes",
64 "disk_write_bytes": "disk.device.write.bytes",
65 "packets_received": "network.incoming.packets",
66 "packets_sent": "network.outgoing.packets",
67 }
68
69 METRIC_MULTIPLIERS = {"cpu": 0.0000001}
70
71 METRIC_AGGREGATORS = {"cpu": "rate:mean"}
72
73 INTERFACE_METRICS = [
74 "packets_in_dropped",
75 "packets_out_dropped",
76 "packets_received",
77 "packets_sent",
78 ]
79
80 INSTANCE_DISK = [
81 "disk_read_ops",
82 "disk_write_ops",
83 "disk_read_bytes",
84 "disk_write_bytes",
85 ]
86
87
88 class MetricType(Enum):
89 INSTANCE = "instance"
90 INTERFACE_ALL = "interface_all"
91 INTERFACE_ONE = "interface_one"
92 INSTANCEDISK = "instancedisk"
93
94
95 class OpenstackCollector(BaseVimCollector):
96 def __init__(self, config: Config, vim_account_id: str, vim_session: object):
97 super().__init__(config, vim_account_id)
98 self.common_db = CommonDbClient(config)
99 vim_account = self.common_db.get_vim_account(vim_account_id)
100 self.backend = self._get_backend(vim_account, vim_session)
101
102 def _build_keystone_client(self, vim_account: dict) -> keystone_client.Client:
103 sess = OpenstackUtils.get_session(vim_account)
104 return keystone_client.Client(session=sess)
105
106 def _get_resource_uuid(
107 self, nsr_id: str, vnf_member_index: str, vdur_name: str
108 ) -> str:
109 vdur = self.common_db.get_vdur(nsr_id, vnf_member_index, vdur_name)
110 return vdur["vim-id"]
111
112 def collect(self, vnfr: dict) -> List[Metric]:
113 nsr_id = vnfr["nsr-id-ref"]
114 vnf_member_index = vnfr["member-vnf-index-ref"]
115 vnfd = self.common_db.get_vnfd(vnfr["vnfd-id"])
116 # Populate extra tags for metrics
117 tags = {}
118 tags["ns_name"] = self.common_db.get_nsr(nsr_id)["name"]
119 if vnfr["_admin"]["projects_read"]:
120 tags["project_id"] = vnfr["_admin"]["projects_read"][0]
121 else:
122 tags["project_id"] = ""
123
124 metrics = []
125
126 for vdur in vnfr["vdur"]:
127 # This avoids errors when vdur records have not been completely filled
128 if "name" not in vdur:
129 continue
130 vdu = next(filter(lambda vdu: vdu["id"] == vdur["vdu-id-ref"], vnfd["vdu"]))
131 if "monitoring-parameter" in vdu:
132 for param in vdu["monitoring-parameter"]:
133 metric_name = param["performance-metric"]
134 log.debug(f"Using an {type(self.backend)} as backend")
135 if type(self.backend) is PrometheusTSBDBackend:
136 openstack_metric_name = self.backend.map_metric(metric_name)
137 else:
138 openstack_metric_name = METRIC_MAPPINGS[metric_name]
139 metric_type = self._get_metric_type(metric_name)
140 try:
141 resource_id = self._get_resource_uuid(
142 nsr_id, vnf_member_index, vdur["name"]
143 )
144 except ValueError:
145 log.warning(
146 "Could not find resource_uuid for vdur %s, vnf_member_index %s, nsr_id %s. "
147 "Was it recently deleted?",
148 vdur["name"],
149 vnf_member_index,
150 nsr_id,
151 )
152 continue
153 try:
154 log.info(
155 "Collecting metric type: %s and metric_name: %s and resource_id %s and ",
156 metric_type,
157 metric_name,
158 resource_id,
159 )
160 value = self.backend.collect_metric(
161 metric_type, openstack_metric_name, resource_id
162 )
163
164 if (
165 value is None
166 and metric_name
167 in METRIC_MAPPINGS_FOR_ROCKY_AND_NEWER_RELEASES
168 and type(self.backend) is not PrometheusTSBDBackend
169 ):
170 # Reattempting metric collection with new metric names.
171 # Some metric names have changed in newer Openstack releases
172 log.info(
173 "Reattempting metric collection for type: %s and name: %s and resource_id %s",
174 metric_type,
175 metric_name,
176 resource_id,
177 )
178 openstack_metric_name = (
179 METRIC_MAPPINGS_FOR_ROCKY_AND_NEWER_RELEASES[
180 metric_name
181 ]
182 )
183 value = self.backend.collect_metric(
184 metric_type, openstack_metric_name, resource_id
185 )
186 if value is not None:
187 log.info("value: %s", value)
188 metric = VnfMetric(
189 nsr_id,
190 vnf_member_index,
191 vdur["name"],
192 metric_name,
193 value,
194 tags,
195 )
196 metrics.append(metric)
197 else:
198 log.info("metric value is empty")
199 except Exception as e:
200 log.exception(
201 "Error collecting metric %s for vdu %s"
202 % (metric_name, vdur["name"])
203 )
204 log.info("Error in metric collection: %s" % e)
205 return metrics
206
207 def _get_backend(self, vim_account: dict, vim_session: object):
208 if vim_account.get("prometheus-config"):
209 try:
210 tsbd = PrometheusTSBDBackend(vim_account)
211 log.debug("Using prometheustsbd backend to collect metric")
212 return tsbd
213 except Exception as e:
214 log.error(f"Can't create prometheus client, {e}")
215 return None
216 try:
217 gnocchi = GnocchiBackend(vim_account, vim_session)
218 gnocchi.client.metric.list(limit=1)
219 log.debug("Using gnocchi backend to collect metric")
220 return gnocchi
221 except (HTTPException, EndpointNotFound):
222 ceilometer = CeilometerBackend(vim_account, vim_session)
223 ceilometer.client.capabilities.get()
224 log.debug("Using ceilometer backend to collect metric")
225 return ceilometer
226
227 def _get_metric_type(self, metric_name: str) -> MetricType:
228 if metric_name not in INTERFACE_METRICS:
229 if metric_name not in INSTANCE_DISK:
230 return MetricType.INSTANCE
231 else:
232 return MetricType.INSTANCEDISK
233 else:
234 return MetricType.INTERFACE_ALL
235
236
237 class OpenstackBackend:
238 def collect_metric(
239 self, metric_type: MetricType, metric_name: str, resource_id: str
240 ):
241 pass
242
243
244 class PrometheusTSBDBackend(OpenstackBackend):
245 def __init__(self, vim_account: dict):
246 self.cred = vim_account["prometheus-config"]["prometheus_cred"]
247 self.map = vim_account["prometheus-config"]["prometheus_map"]
248 self.client = self._build_prometheus_client(vim_account)
249
250 def _build_prometheus_client(self, vim_account: dict) -> prometheus_client:
251 url = vim_account["prometheus-config"]["prometheus_url"]
252 return prometheus_client(url, disable_ssl=True)
253
254 def collect_metric(
255 self, metric_type: MetricType, metric_name: str, resource_id: str
256 ):
257 metric = self.query_metric(metric_name, resource_id)
258 return metric["value"][1] if metric else None
259
260 def map_metric(self, metric_name: str):
261 return self.map[metric_name]
262
263 def query_metric(self, metric_name, resource_id=None):
264 metrics = self.client.get_current_metric_value(metric_name=metric_name)
265 if resource_id:
266 metric = next(
267 filter(lambda x: resource_id in x["metric"]["resource_id"], metrics)
268 )
269 return metric
270 return metrics
271
272
273 class GnocchiBackend(OpenstackBackend):
274 def __init__(self, vim_account: dict, vim_session: object):
275 self.client = self._build_gnocchi_client(vim_account, vim_session)
276 self.neutron = self._build_neutron_client(vim_account, vim_session)
277
278 def _build_gnocchi_client(
279 self, vim_account: dict, vim_session: object
280 ) -> gnocchi_client.Client:
281 return gnocchi_client.Client(session=vim_session)
282
283 def _build_neutron_client(
284 self, vim_account: dict, vim_session: object
285 ) -> neutron_client.Client:
286 return neutron_client.Client(session=vim_session)
287
288 def collect_metric(
289 self, metric_type: MetricType, metric_name: str, resource_id: str
290 ):
291 if metric_type == MetricType.INTERFACE_ALL:
292 return self._collect_interface_all_metric(metric_name, resource_id)
293
294 elif metric_type == MetricType.INSTANCE:
295 return self._collect_instance_metric(metric_name, resource_id)
296
297 elif metric_type == MetricType.INSTANCEDISK:
298 return self._collect_instance_disk_metric(metric_name, resource_id)
299
300 else:
301 raise Exception("Unknown metric type %s" % metric_type.value)
302
303 def _collect_interface_all_metric(self, openstack_metric_name, resource_id):
304 total_measure = None
305 interfaces = self.client.resource.search(
306 resource_type="instance_network_interface",
307 query={"=": {"instance_id": resource_id}},
308 )
309 for interface in interfaces:
310 try:
311 measures = self.client.metric.get_measures(
312 openstack_metric_name, resource_id=interface["id"], limit=1
313 )
314 if measures:
315 if not total_measure:
316 total_measure = 0.0
317 total_measure += measures[-1][2]
318 except (gnocchiclient.exceptions.NotFound, TypeError) as e:
319 # Gnocchi in some Openstack versions raise TypeError instead of NotFound
320 log.debug(
321 "No metric %s found for interface %s: %s",
322 openstack_metric_name,
323 interface["id"],
324 e,
325 )
326 return total_measure
327
328 def _collect_instance_disk_metric(self, openstack_metric_name, resource_id):
329 value = None
330 instances = self.client.resource.search(
331 resource_type="instance_disk",
332 query={"=": {"instance_id": resource_id}},
333 )
334 for instance in instances:
335 try:
336 measures = self.client.metric.get_measures(
337 openstack_metric_name, resource_id=instance["id"], limit=1
338 )
339 if measures:
340 value = measures[-1][2]
341
342 except gnocchiclient.exceptions.NotFound as e:
343 log.debug(
344 "No metric %s found for instance disk %s: %s",
345 openstack_metric_name,
346 instance["id"],
347 e,
348 )
349 return value
350
351 def _collect_instance_metric(self, openstack_metric_name, resource_id):
352 value = None
353 try:
354 aggregation = METRIC_AGGREGATORS.get(openstack_metric_name)
355
356 try:
357 measures = self.client.metric.get_measures(
358 openstack_metric_name,
359 aggregation=aggregation,
360 start=time.time() - 1200,
361 resource_id=resource_id,
362 )
363 if measures:
364 value = measures[-1][2]
365 except (
366 gnocchiclient.exceptions.NotFound,
367 gnocchiclient.exceptions.BadRequest,
368 TypeError,
369 ) as e:
370 # CPU metric in previous Openstack versions do not support rate:mean aggregation method
371 # Gnocchi in some Openstack versions raise TypeError instead of NotFound or BadRequest
372 if openstack_metric_name == "cpu":
373 log.debug(
374 "No metric %s found for instance %s: %s",
375 openstack_metric_name,
376 resource_id,
377 e,
378 )
379 log.info(
380 "Retrying to get metric %s for instance %s without aggregation",
381 openstack_metric_name,
382 resource_id,
383 )
384 measures = self.client.metric.get_measures(
385 openstack_metric_name, resource_id=resource_id, limit=1
386 )
387 else:
388 raise e
389 # measures[-1] is the last measure
390 # measures[-2] is the previous measure
391 # measures[x][2] is the value of the metric
392 if measures and len(measures) >= 2:
393 value = measures[-1][2] - measures[-2][2]
394 if value:
395 # measures[-1][0] is the time of the reporting interval
396 # measures[-1][1] is the duration of the reporting interval
397 if aggregation:
398 # If this is an aggregate, we need to divide the total over the reported time period.
399 # Even if the aggregation method is not supported by Openstack, the code will execute it
400 # because aggregation is specified in METRIC_AGGREGATORS
401 value = value / measures[-1][1]
402 if openstack_metric_name in METRIC_MULTIPLIERS:
403 value = value * METRIC_MULTIPLIERS[openstack_metric_name]
404 except gnocchiclient.exceptions.NotFound as e:
405 log.debug(
406 "No metric %s found for instance %s: %s",
407 openstack_metric_name,
408 resource_id,
409 e,
410 )
411 return value
412
413
414 class CeilometerBackend(OpenstackBackend):
415 def __init__(self, vim_account: dict, vim_session: object):
416 self.client = self._build_ceilometer_client(vim_account, vim_session)
417
418 def _build_ceilometer_client(
419 self, vim_account: dict, vim_session: object
420 ) -> ceilometer_client.Client:
421 return ceilometer_client.Client("2", session=vim_session)
422
423 def collect_metric(
424 self, metric_type: MetricType, metric_name: str, resource_id: str
425 ):
426 if metric_type != MetricType.INSTANCE:
427 raise NotImplementedError(
428 "Ceilometer backend only support instance metrics"
429 )
430 measures = self.client.samples.list(
431 meter_name=metric_name,
432 limit=1,
433 q=[{"field": "resource_id", "op": "eq", "value": resource_id}],
434 )
435 return measures[0].counter_volume if measures else None