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