1 # Copyright 2018 Whitestack, LLC
2 # *************************************************************
4 # This file is part of OSM Monitoring module
5 # All Rights Reserved to Whitestack, LLC
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: bdiaz@whitestack.com or glavado@whitestack.com
25 from typing
import List
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
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
44 log
= logging
.getLogger(__name__
)
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",
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"
69 METRIC_MULTIPLIERS
= {"cpu": 0.0000001}
71 METRIC_AGGREGATORS
= {"cpu": "rate:mean"}
75 "packets_out_dropped",
88 class MetricType(Enum
):
90 INTERFACE_ALL
= "interface_all"
91 INTERFACE_ONE
= "interface_one"
92 INSTANCEDISK
= 'instancedisk'
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
)
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
)
106 def _get_resource_uuid(
107 self
, nsr_id
: str, vnf_member_index
: str, vdur_name
: str
109 vdur
= self
.common_db
.get_vdur(nsr_id
, vnf_member_index
, vdur_name
)
110 return vdur
["vim-id"]
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
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]
122 tags
["project_id"] = ""
126 for vdur
in vnfr
["vdur"]:
127 # This avoids errors when vdur records have not been completely filled
128 if "name" not in vdur
:
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
)
138 openstack_metric_name
= METRIC_MAPPINGS
[metric_name
]
139 metric_type
= self
._get
_metric
_type
(metric_name
)
141 resource_id
= self
._get
_resource
_uuid
(
142 nsr_id
, vnf_member_index
, vdur
["name"]
146 "Could not find resource_uuid for vdur %s, vnf_member_index %s, nsr_id %s. "
147 "Was it recently deleted?",
155 "Collecting metric type: %s and metric_name: %s and resource_id %s and ",
160 value
= self
.backend
.collect_metric(
161 metric_type
, openstack_metric_name
, resource_id
164 if value
is None and metric_name
in METRIC_MAPPINGS_FOR_ROCKY_AND_NEWER_RELEASES
and type(self
.backend
) is not PrometheusTSBDBackend
:
165 # Reattempting metric collection with new metric names.
166 # Some metric names have changed in newer Openstack releases
168 "Reattempting metric collection for type: %s and name: %s and resource_id %s",
173 openstack_metric_name
= METRIC_MAPPINGS_FOR_ROCKY_AND_NEWER_RELEASES
[metric_name
]
174 value
= self
.backend
.collect_metric(
175 metric_type
, openstack_metric_name
, resource_id
177 if value
is not None:
178 log
.info("value: %s", value
)
187 metrics
.append(metric
)
189 log
.info("metric value is empty")
190 except Exception as e
:
192 "Error collecting metric %s for vdu %s"
193 % (metric_name
, vdur
["name"])
195 log
.info("Error in metric collection: %s" % e
)
198 def _get_backend(self
, vim_account
: dict, vim_session
: object):
199 if vim_account
.get("prometheus-config"):
201 tsbd
= PrometheusTSBDBackend(vim_account
)
202 log
.debug("Using prometheustsbd backend to collect metric")
204 except Exception as e
:
205 log
.error(f
"Can't create prometheus client, {e}")
208 gnocchi
= GnocchiBackend(vim_account
, vim_session
)
209 gnocchi
.client
.metric
.list(limit
=1)
210 log
.debug("Using gnocchi backend to collect metric")
212 except (HTTPException
, EndpointNotFound
):
213 ceilometer
= CeilometerBackend(vim_account
, vim_session
)
214 ceilometer
.client
.capabilities
.get()
215 log
.debug("Using ceilometer backend to collect metric")
218 def _get_metric_type(self
, metric_name
: str) -> MetricType
:
219 if metric_name
not in INTERFACE_METRICS
:
220 if metric_name
not in INSTANCE_DISK
:
221 return MetricType
.INSTANCE
223 return MetricType
.INSTANCEDISK
225 return MetricType
.INTERFACE_ALL
228 class OpenstackBackend
:
230 self
, metric_type
: MetricType
, metric_name
: str, resource_id
: str
235 class PrometheusTSBDBackend(OpenstackBackend
):
236 def __init__(self
, vim_account
: dict):
237 self
.cred
= vim_account
["prometheus-config"]["prometheus_cred"]
238 self
.map = vim_account
["prometheus-config"]["prometheus_map"]
239 self
.client
= self
._build
_prometheus
_client
(vim_account
)
241 def _build_prometheus_client(self
, vim_account
: dict) -> prometheus_client
:
242 url
= vim_account
["prometheus-config"]["prometheus_url"]
243 return prometheus_client(url
, disable_ssl
= True)
246 self
, metric_type
: MetricType
, metric_name
: str, resource_id
: str
248 metric
= self
.query_metric(metric_name
, resource_id
)
249 return metric
["value"][1] if metric
else None
251 def map_metric(self
, metric_name
: str):
252 return self
.map[metric_name
]
254 def query_metric(self
, metric_name
, resource_id
= None):
255 metrics
= self
.client
.get_current_metric_value(metric_name
= metric_name
)
257 metric
= next(filter(lambda x
: resource_id
in x
["metric"]["resource_id"], metrics
))
262 class GnocchiBackend(OpenstackBackend
):
263 def __init__(self
, vim_account
: dict, vim_session
: object):
264 self
.client
= self
._build
_gnocchi
_client
(vim_account
, vim_session
)
265 self
.neutron
= self
._build
_neutron
_client
(vim_account
, vim_session
)
267 def _build_gnocchi_client(self
, vim_account
: dict, vim_session
: object) -> gnocchi_client
.Client
:
268 return gnocchi_client
.Client(session
=vim_session
)
270 def _build_neutron_client(self
, vim_account
: dict, vim_session
: object) -> neutron_client
.Client
:
271 return neutron_client
.Client(session
=vim_session
)
274 self
, metric_type
: MetricType
, metric_name
: str, resource_id
: str
276 if metric_type
== MetricType
.INTERFACE_ALL
:
277 return self
._collect
_interface
_all
_metric
(metric_name
, resource_id
)
279 elif metric_type
== MetricType
.INSTANCE
:
280 return self
._collect
_instance
_metric
(metric_name
, resource_id
)
282 elif metric_type
== MetricType
.INSTANCEDISK
:
283 return self
._collect
_instance
_disk
_metric
(metric_name
, resource_id
)
286 raise Exception("Unknown metric type %s" % metric_type
.value
)
288 def _collect_interface_all_metric(self
, openstack_metric_name
, resource_id
):
290 interfaces
= self
.client
.resource
.search(
291 resource_type
="instance_network_interface",
292 query
={"=": {"instance_id": resource_id
}},
294 for interface
in interfaces
:
296 measures
= self
.client
.metric
.get_measures(
297 openstack_metric_name
, resource_id
=interface
["id"], limit
=1
300 if not total_measure
:
302 total_measure
+= measures
[-1][2]
303 except (gnocchiclient
.exceptions
.NotFound
, TypeError) as e
:
304 # Gnocchi in some Openstack versions raise TypeError instead of NotFound
306 "No metric %s found for interface %s: %s",
307 openstack_metric_name
,
313 def _collect_instance_disk_metric(self
, openstack_metric_name
, resource_id
):
315 instances
= self
.client
.resource
.search(
316 resource_type
='instance_disk',
317 query
={'=': {'instance_id': resource_id
}},
319 for instance
in instances
:
321 measures
= self
.client
.metric
.get_measures(
322 openstack_metric_name
, resource_id
=instance
['id'], limit
=1
325 value
= measures
[-1][2]
327 except gnocchiclient
.exceptions
.NotFound
as e
:
328 log
.debug("No metric %s found for instance disk %s: %s", openstack_metric_name
,
332 def _collect_instance_metric(self
, openstack_metric_name
, resource_id
):
335 aggregation
= METRIC_AGGREGATORS
.get(openstack_metric_name
)
338 measures
= self
.client
.metric
.get_measures(
339 openstack_metric_name
,
340 aggregation
=aggregation
,
341 start
=time
.time() - 1200,
342 resource_id
=resource_id
,
345 value
= measures
[-1][2]
347 gnocchiclient
.exceptions
.NotFound
,
348 gnocchiclient
.exceptions
.BadRequest
,
351 # CPU metric in previous Openstack versions do not support rate:mean aggregation method
352 # Gnocchi in some Openstack versions raise TypeError instead of NotFound or BadRequest
353 if openstack_metric_name
== "cpu":
355 "No metric %s found for instance %s: %s",
356 openstack_metric_name
,
361 "Retrying to get metric %s for instance %s without aggregation",
362 openstack_metric_name
,
365 measures
= self
.client
.metric
.get_measures(
366 openstack_metric_name
, resource_id
=resource_id
, limit
=1
370 # measures[-1] is the last measure
371 # measures[-2] is the previous measure
372 # measures[x][2] is the value of the metric
373 if measures
and len(measures
) >= 2:
374 value
= measures
[-1][2] - measures
[-2][2]
376 # measures[-1][0] is the time of the reporting interval
377 # measures[-1][1] is the duration of the reporting interval
379 # If this is an aggregate, we need to divide the total over the reported time period.
380 # Even if the aggregation method is not supported by Openstack, the code will execute it
381 # because aggregation is specified in METRIC_AGGREGATORS
382 value
= value
/ measures
[-1][1]
383 if openstack_metric_name
in METRIC_MULTIPLIERS
:
384 value
= value
* METRIC_MULTIPLIERS
[openstack_metric_name
]
385 except gnocchiclient
.exceptions
.NotFound
as e
:
387 "No metric %s found for instance %s: %s",
388 openstack_metric_name
,
395 class CeilometerBackend(OpenstackBackend
):
396 def __init__(self
, vim_account
: dict, vim_session
: object):
397 self
.client
= self
._build
_ceilometer
_client
(vim_account
, vim_session
)
399 def _build_ceilometer_client(self
, vim_account
: dict, vim_session
: object) -> ceilometer_client
.Client
:
400 return ceilometer_client
.Client("2", session
=vim_session
)
403 self
, metric_type
: MetricType
, metric_name
: str, resource_id
: str
405 if metric_type
!= MetricType
.INSTANCE
:
406 raise NotImplementedError(
407 "Ceilometer backend only support instance metrics"
409 measures
= self
.client
.samples
.list(
410 meter_name
=metric_name
,
412 q
=[{"field": "resource_id", "op": "eq", "value": resource_id
}],
414 return measures
[0].counter_volume
if measures
else None