0eaa1b982f0ddf0b5d726b50e9aa1c29e851db48
[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 import datetime
23 import json
24 import logging
25 from enum import Enum
26 from typing import List
27
28 import gnocchiclient.exceptions
29 from ceilometerclient.v2 import client as ceilometer_client
30 from gnocchiclient.v1 import client as gnocchi_client
31 from keystoneauth1 import session
32 from keystoneauth1.identity import v3
33 from keystoneclient.v3 import client as keystone_client
34 from neutronclient.v2_0 import client as neutron_client
35
36 from osm_mon.collector.metric import Metric
37 from osm_mon.collector.utils import CollectorUtils
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 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_util",
56 }
57
58 INTERFACE_METRICS = ['packets_in_dropped', 'packets_out_dropped', 'packets_received', 'packets_sent']
59
60
61 class MetricType(Enum):
62 INSTANCE = 'instance'
63 INTERFACE_ALL = 'interface_all'
64 INTERFACE_ONE = 'interface_one'
65
66
67 class OpenstackCollector(BaseVimCollector):
68 def __init__(self, config: Config, vim_account_id: str):
69 super().__init__(config, vim_account_id)
70 self.conf = config
71 self.common_db = CommonDbClient(config)
72 self.backend = self._get_backend(vim_account_id)
73
74 def _build_keystone_client(self, vim_account_id: str) -> keystone_client.Client:
75 sess = OpenstackBackend.get_session(vim_account_id)
76 return keystone_client.Client(session=sess)
77
78 def _get_resource_uuid(self, nsr_id: str, vnf_member_index: str, vdur_name: str) -> str:
79 vdur = self.common_db.get_vdur(nsr_id, vnf_member_index, vdur_name)
80 return vdur['vim-id']
81
82 def _get_granularity(self, vim_account_id: str):
83 creds = CollectorUtils.get_credentials(vim_account_id)
84 vim_config = json.loads(creds.config)
85 if 'granularity' in vim_config:
86 return int(vim_config['granularity'])
87 else:
88 return int(self.conf.get('openstack', 'default_granularity'))
89
90 def collect(self, vnfr: dict) -> List[Metric]:
91 nsr_id = vnfr['nsr-id-ref']
92 vnf_member_index = vnfr['member-vnf-index-ref']
93 vnfd = self.common_db.get_vnfd(vnfr['vnfd-id'])
94 metrics = []
95 for vdur in vnfr['vdur']:
96 # This avoids errors when vdur records have not been completely filled
97 if 'name' not in vdur:
98 continue
99 vdu = next(
100 filter(lambda vdu: vdu['id'] == vdur['vdu-id-ref'], vnfd['vdu'])
101 )
102 if 'monitoring-param' in vdu:
103 for param in vdu['monitoring-param']:
104 metric_name = param['nfvi-metric']
105 interface_name = param['interface-name-ref'] if 'interface-name-ref' in param else None
106 openstack_metric_name = METRIC_MAPPINGS[metric_name]
107 metric_type = self._get_metric_type(metric_name, interface_name)
108 try:
109 resource_id = self._get_resource_uuid(nsr_id, vnf_member_index, vdur['name'])
110 except ValueError:
111 log.warning(
112 "Could not find resource_uuid for vdur %s, vnf_member_index %s, nsr_id %s. "
113 "Was it recently deleted?",
114 vdur['name'], vnf_member_index, nsr_id)
115 continue
116 try:
117 value = self.backend.collect_metric(metric_type, openstack_metric_name, resource_id,
118 interface_name)
119 if value is not None:
120 tags = {}
121 if interface_name:
122 tags['interface'] = interface_name
123 metric = VnfMetric(nsr_id, vnf_member_index, vdur['name'], metric_name, value, tags)
124 metrics.append(metric)
125 except Exception:
126 log.exception("Error collecting metric %s for vdu %s" % (metric_name, vdur['name']))
127 return metrics
128
129 def _get_backend(self, vim_account_id: str):
130 keystone = self._build_keystone_client(vim_account_id)
131 if keystone.services.list('gnocchi'):
132 granularity = self._get_granularity(vim_account_id)
133 return GnocchiBackend(vim_account_id, granularity)
134 elif keystone.services.list('ceilometer'):
135 return CeilometerBackend(vim_account_id)
136
137 def _get_metric_type(self, metric_name: str, interface_name: str) -> MetricType:
138 if metric_name not in INTERFACE_METRICS:
139 return MetricType.INSTANCE
140 else:
141 if interface_name:
142 return MetricType.INTERFACE_ONE
143 return MetricType.INTERFACE_ALL
144
145
146 class OpenstackBackend:
147 def collect_metric(self, metric_type: MetricType, metric_name: str, resource_id: str, interface_name: str):
148 pass
149
150 @staticmethod
151 def get_session(vim_account_id: str):
152 creds = CollectorUtils.get_credentials(vim_account_id)
153 verify_ssl = CollectorUtils.is_verify_ssl(creds)
154 auth = v3.Password(auth_url=creds.url,
155 username=creds.user,
156 password=creds.password,
157 project_name=creds.tenant_name,
158 project_domain_id='default',
159 user_domain_id='default')
160 return session.Session(auth=auth, verify=verify_ssl)
161
162
163 class GnocchiBackend(OpenstackBackend):
164
165 def __init__(self, vim_account_id: str, granularity: int):
166 self.client = self._build_gnocchi_client(vim_account_id)
167 self.neutron = self._build_neutron_client(vim_account_id)
168 self.granularity = granularity
169
170 def _build_gnocchi_client(self, vim_account_id: str) -> gnocchi_client.Client:
171 sess = OpenstackBackend.get_session(vim_account_id)
172 return gnocchi_client.Client(session=sess)
173
174 def _build_neutron_client(self, vim_account_id: str) -> neutron_client.Client:
175 sess = OpenstackBackend.get_session(vim_account_id)
176 return neutron_client.Client(session=sess)
177
178 def collect_metric(self, metric_type: MetricType, metric_name: str, resource_id: str, interface_name: str):
179 if metric_type == MetricType.INTERFACE_ONE:
180 return self._collect_interface_one_metric(metric_name, resource_id, interface_name)
181
182 if metric_type == MetricType.INTERFACE_ALL:
183 return self._collect_interface_all_metric(metric_name, resource_id)
184
185 elif metric_type == MetricType.INSTANCE:
186 return self._collect_instance_metric(metric_name, resource_id)
187
188 else:
189 raise Exception('Unknown metric type %s' % metric_type.value)
190
191 def _collect_interface_one_metric(self, metric_name, resource_id, interface_name):
192 delta = 10 * self.granularity
193 start_date = datetime.datetime.now() - datetime.timedelta(seconds=delta)
194 ports = self.neutron.list_ports(name=interface_name, device_id=resource_id)
195 if not ports or not ports['ports']:
196 raise Exception(
197 'Port not found for interface %s on instance %s' % (interface_name, resource_id))
198 port = ports['ports'][0]
199 port_uuid = port['id'][:11]
200 tap_name = 'tap' + port_uuid
201 interfaces = self.client.resource.search(resource_type='instance_network_interface',
202 query={'=': {'name': tap_name}})
203 measures = self.client.metric.get_measures(metric_name,
204 start=start_date,
205 resource_id=interfaces[0]['id'],
206 granularity=self.granularity)
207 return measures[-1][2] if measures else None
208
209 def _collect_interface_all_metric(self, openstack_metric_name, resource_id):
210 delta = 10 * self.granularity
211 start_date = datetime.datetime.now() - datetime.timedelta(seconds=delta)
212 total_measure = None
213 interfaces = self.client.resource.search(resource_type='instance_network_interface',
214 query={'=': {'instance_id': resource_id}})
215 for interface in interfaces:
216 try:
217 measures = self.client.metric.get_measures(openstack_metric_name,
218 start=start_date,
219 resource_id=interface['id'],
220 granularity=self.granularity)
221 if measures:
222 if not total_measure:
223 total_measure = 0.0
224 total_measure += measures[-1][2]
225
226 except gnocchiclient.exceptions.NotFound as e:
227 log.debug("No metric %s found for interface %s: %s", openstack_metric_name,
228 interface['id'], e)
229 return total_measure
230
231 def _collect_instance_metric(self, openstack_metric_name, resource_id):
232 delta = 10 * self.granularity
233 start_date = datetime.datetime.now() - datetime.timedelta(seconds=delta)
234 value = None
235 try:
236 measures = self.client.metric.get_measures(openstack_metric_name,
237 start=start_date,
238 resource_id=resource_id,
239 granularity=self.granularity)
240 if measures:
241 value = measures[-1][2]
242 except gnocchiclient.exceptions.NotFound as e:
243 log.debug("No metric %s found for instance %s: %s", openstack_metric_name, resource_id,
244 e)
245 return value
246
247
248 class CeilometerBackend(OpenstackBackend):
249 def __init__(self, vim_account_id: str):
250 self.client = self._build_ceilometer_client(vim_account_id)
251
252 def _build_ceilometer_client(self, vim_account_id: str) -> ceilometer_client.Client:
253 sess = OpenstackBackend.get_session(vim_account_id)
254 return ceilometer_client.Client(session=sess)
255
256 def collect_metric(self, metric_type: MetricType, metric_name: str, resource_id: str, interface_name: str):
257 if metric_type != MetricType.INSTANCE:
258 raise NotImplementedError('Ceilometer backend only support instance metrics')
259 measures = self.client.samples.list(meter_name=metric_name, limit=1, q=[
260 {'field': 'resource_id', 'op': 'eq', 'value': resource_id}])
261 return measures[0].counter_volume if measures else None