Fix bug 1884 MON openstack token optimization
[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
35 from osm_mon.collector.metric import Metric
36 from osm_mon.collector.utils.openstack import OpenstackUtils
37 from osm_mon.collector.vnf_collectors.base_vim import BaseVimCollector
38 from osm_mon.collector.vnf_metric import VnfMetric
39 from osm_mon.core.common_db import CommonDbClient
40 from osm_mon.core.config import Config
41
42
43 log = logging.getLogger(__name__)
44
45 METRIC_MAPPINGS = {
46 "average_memory_utilization": "memory.usage",
47 "disk_read_ops": "disk.read.requests.rate",
48 "disk_write_ops": "disk.write.requests.rate",
49 "disk_read_bytes": "disk.read.bytes.rate",
50 "disk_write_bytes": "disk.write.bytes.rate",
51 "packets_in_dropped": "network.outgoing.packets.drop",
52 "packets_out_dropped": "network.incoming.packets.drop",
53 "packets_received": "network.incoming.packets.rate",
54 "packets_sent": "network.outgoing.packets.rate",
55 "cpu_utilization": "cpu",
56 }
57
58 # Metrics which have new names in Rocky and higher releases
59 METRIC_MAPPINGS_FOR_ROCKY_AND_NEWER_RELEASES = {
60 "disk_read_ops": "disk.device.read.requests",
61 "disk_write_ops": "disk.device.write.requests",
62 "disk_read_bytes": "disk.device.read.bytes",
63 "disk_write_bytes": "disk.device.write.bytes",
64 "packets_received": "network.incoming.packets",
65 "packets_sent": "network.outgoing.packets"
66 }
67
68 METRIC_MULTIPLIERS = {"cpu": 0.0000001}
69
70 METRIC_AGGREGATORS = {"cpu": "rate:mean"}
71
72 INTERFACE_METRICS = [
73 "packets_in_dropped",
74 "packets_out_dropped",
75 "packets_received",
76 "packets_sent",
77 ]
78
79
80 class MetricType(Enum):
81 INSTANCE = "instance"
82 INTERFACE_ALL = "interface_all"
83 INTERFACE_ONE = "interface_one"
84
85
86 class OpenstackCollector(BaseVimCollector):
87 def __init__(self, config: Config, vim_account_id: str, vim_session: object):
88 super().__init__(config, vim_account_id)
89 self.common_db = CommonDbClient(config)
90 vim_account = self.common_db.get_vim_account(vim_account_id)
91 self.backend = self._get_backend(vim_account, vim_session)
92
93 def _build_keystone_client(self, vim_account: dict) -> keystone_client.Client:
94 sess = OpenstackUtils.get_session(vim_account)
95 return keystone_client.Client(session=sess)
96
97 def _get_resource_uuid(
98 self, nsr_id: str, vnf_member_index: str, vdur_name: str
99 ) -> str:
100 vdur = self.common_db.get_vdur(nsr_id, vnf_member_index, vdur_name)
101 return vdur["vim-id"]
102
103 def collect(self, vnfr: dict) -> List[Metric]:
104 nsr_id = vnfr["nsr-id-ref"]
105 vnf_member_index = vnfr["member-vnf-index-ref"]
106 vnfd = self.common_db.get_vnfd(vnfr["vnfd-id"])
107 # Populate extra tags for metrics
108 tags = {}
109 tags["ns_name"] = self.common_db.get_nsr(nsr_id)["name"]
110 if vnfr["_admin"]["projects_read"]:
111 tags["project_id"] = vnfr["_admin"]["projects_read"][0]
112 else:
113 tags["project_id"] = ""
114
115 metrics = []
116
117 for vdur in vnfr["vdur"]:
118 # This avoids errors when vdur records have not been completely filled
119 if "name" not in vdur:
120 continue
121 vdu = next(filter(lambda vdu: vdu["id"] == vdur["vdu-id-ref"], vnfd["vdu"]))
122 if "monitoring-parameter" in vdu:
123 for param in vdu["monitoring-parameter"]:
124 metric_name = param["performance-metric"]
125 openstack_metric_name = METRIC_MAPPINGS[metric_name]
126 metric_type = self._get_metric_type(metric_name)
127 try:
128 resource_id = self._get_resource_uuid(
129 nsr_id, vnf_member_index, vdur["name"]
130 )
131 except ValueError:
132 log.warning(
133 "Could not find resource_uuid for vdur %s, vnf_member_index %s, nsr_id %s. "
134 "Was it recently deleted?",
135 vdur["name"],
136 vnf_member_index,
137 nsr_id,
138 )
139 continue
140 try:
141 log.info(
142 "Collecting metric type: %s and metric_name: %s and resource_id %s and ",
143 metric_type,
144 metric_name,
145 resource_id,
146 )
147 value = self.backend.collect_metric(
148 metric_type, openstack_metric_name, resource_id
149 )
150
151 if value is None and metric_name in METRIC_MAPPINGS_FOR_ROCKY_AND_NEWER_RELEASES:
152 # Reattempting metric collection with new metric names.
153 # Some metric names have changed in newer Openstack releases
154 log.info(
155 "Reattempting metric collection for type: %s and name: %s and resource_id %s",
156 metric_type,
157 metric_name,
158 resource_id
159 )
160 openstack_metric_name = METRIC_MAPPINGS_FOR_ROCKY_AND_NEWER_RELEASES[metric_name]
161 value = self.backend.collect_metric(
162 metric_type, openstack_metric_name, resource_id
163 )
164 if value is not None:
165 log.info("value: %s", value)
166 metric = VnfMetric(
167 nsr_id,
168 vnf_member_index,
169 vdur["name"],
170 metric_name,
171 value,
172 tags,
173 )
174 metrics.append(metric)
175 else:
176 log.info("metric value is empty")
177 except Exception as e:
178 log.exception(
179 "Error collecting metric %s for vdu %s"
180 % (metric_name, vdur["name"])
181 )
182 log.info("Error in metric collection: %s" % e)
183 return metrics
184
185 def _get_backend(self, vim_account: dict, vim_session: object):
186 try:
187 gnocchi = GnocchiBackend(vim_account, vim_session)
188 gnocchi.client.metric.list(limit=1)
189 log.info("Using gnocchi backend to collect metric")
190 return gnocchi
191 except (HTTPException, EndpointNotFound):
192 ceilometer = CeilometerBackend(vim_account, vim_session)
193 ceilometer.client.capabilities.get()
194 log.info("Using ceilometer backend to collect metric")
195 return ceilometer
196
197 def _get_metric_type(self, metric_name: str) -> MetricType:
198 if metric_name not in INTERFACE_METRICS:
199 return MetricType.INSTANCE
200 else:
201 return MetricType.INTERFACE_ALL
202
203
204 class OpenstackBackend:
205 def collect_metric(
206 self, metric_type: MetricType, metric_name: str, resource_id: str
207 ):
208 pass
209
210
211 class GnocchiBackend(OpenstackBackend):
212 def __init__(self, vim_account: dict, vim_session: object):
213 self.client = self._build_gnocchi_client(vim_account, vim_session)
214 self.neutron = self._build_neutron_client(vim_account, vim_session)
215
216 def _build_gnocchi_client(self, vim_account: dict, vim_session: object) -> gnocchi_client.Client:
217 return gnocchi_client.Client(session=vim_session)
218
219 def _build_neutron_client(self, vim_account: dict, vim_session: object) -> neutron_client.Client:
220 return neutron_client.Client(session=vim_session)
221
222 def collect_metric(
223 self, metric_type: MetricType, metric_name: str, resource_id: str
224 ):
225 if metric_type == MetricType.INTERFACE_ALL:
226 return self._collect_interface_all_metric(metric_name, resource_id)
227
228 elif metric_type == MetricType.INSTANCE:
229 return self._collect_instance_metric(metric_name, resource_id)
230
231 else:
232 raise Exception("Unknown metric type %s" % metric_type.value)
233
234 def _collect_interface_all_metric(self, openstack_metric_name, resource_id):
235 total_measure = None
236 interfaces = self.client.resource.search(
237 resource_type="instance_network_interface",
238 query={"=": {"instance_id": resource_id}},
239 )
240 for interface in interfaces:
241 try:
242 measures = self.client.metric.get_measures(
243 openstack_metric_name, resource_id=interface["id"], limit=1
244 )
245 if measures:
246 if not total_measure:
247 total_measure = 0.0
248 total_measure += measures[-1][2]
249 except (gnocchiclient.exceptions.NotFound, TypeError) as e:
250 # Gnocchi in some Openstack versions raise TypeError instead of NotFound
251 log.debug(
252 "No metric %s found for interface %s: %s",
253 openstack_metric_name,
254 interface["id"],
255 e,
256 )
257 return total_measure
258
259 def _collect_instance_metric(self, openstack_metric_name, resource_id):
260 value = None
261 try:
262 aggregation = METRIC_AGGREGATORS.get(openstack_metric_name)
263
264 try:
265 measures = self.client.metric.get_measures(
266 openstack_metric_name,
267 aggregation=aggregation,
268 start=time.time() - 1200,
269 resource_id=resource_id,
270 )
271 if measures:
272 value = measures[-1][2]
273 except (
274 gnocchiclient.exceptions.NotFound,
275 gnocchiclient.exceptions.BadRequest,
276 TypeError,
277 ) as e:
278 # CPU metric in previous Openstack versions do not support rate:mean aggregation method
279 # Gnocchi in some Openstack versions raise TypeError instead of NotFound or BadRequest
280 if openstack_metric_name == "cpu":
281 log.debug(
282 "No metric %s found for instance %s: %s",
283 openstack_metric_name,
284 resource_id,
285 e,
286 )
287 log.info(
288 "Retrying to get metric %s for instance %s without aggregation",
289 openstack_metric_name,
290 resource_id,
291 )
292 measures = self.client.metric.get_measures(
293 openstack_metric_name, resource_id=resource_id, limit=1
294 )
295 else:
296 raise e
297 # measures[-1] is the last measure
298 # measures[-2] is the previous measure
299 # measures[x][2] is the value of the metric
300 if measures and len(measures) >= 2:
301 value = measures[-1][2] - measures[-2][2]
302 if value:
303 # measures[-1][0] is the time of the reporting interval
304 # measures[-1][1] is the duration of the reporting interval
305 if aggregation:
306 # If this is an aggregate, we need to divide the total over the reported time period.
307 # Even if the aggregation method is not supported by Openstack, the code will execute it
308 # because aggregation is specified in METRIC_AGGREGATORS
309 value = value / measures[-1][1]
310 if openstack_metric_name in METRIC_MULTIPLIERS:
311 value = value * METRIC_MULTIPLIERS[openstack_metric_name]
312 except gnocchiclient.exceptions.NotFound as e:
313 log.debug(
314 "No metric %s found for instance %s: %s",
315 openstack_metric_name,
316 resource_id,
317 e,
318 )
319 return value
320
321
322 class CeilometerBackend(OpenstackBackend):
323 def __init__(self, vim_account: dict, vim_session: object):
324 self.client = self._build_ceilometer_client(vim_account, vim_session)
325
326 def _build_ceilometer_client(self, vim_account: dict, vim_session: object) -> ceilometer_client.Client:
327 return ceilometer_client.Client("2", session=vim_session)
328
329 def collect_metric(
330 self, metric_type: MetricType, metric_name: str, resource_id: str
331 ):
332 if metric_type != MetricType.INSTANCE:
333 raise NotImplementedError(
334 "Ceilometer backend only support instance metrics"
335 )
336 measures = self.client.samples.list(
337 meter_name=metric_name,
338 limit=1,
339 q=[{"field": "resource_id", "op": "eq", "value": resource_id}],
340 )
341 return measures[0].counter_volume if measures else None