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