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