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