blob: a0a80a754c374c59ccfc20ccb8fc1f894885fbed [file] [log] [blame]
lavado456d0f32019-11-15 17:04:02 -05001# -*- coding: utf-8 -*-
2
bravof2fe71f22021-01-27 21:22:19 -03003# Copyright 2021 Whitestack, LLC
lavado456d0f32019-11-15 17:04:02 -05004# *************************************************************
5
6# This file is part of OSM Monitoring module
7# All Rights Reserved to Whitestack, LLC
8
9# Licensed under the Apache License, Version 2.0 (the "License"); you may
10# not use this file except in compliance with the License. You may obtain
11# a copy of the License at
12
13# http://www.apache.org/licenses/LICENSE-2.0
14
15# Unless required by applicable law or agreed to in writing, software
16# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
17# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
18# License for the specific language governing permissions and limitations
19# under the License.
20# For those usages not covered by the Apache License, Version 2.0 please
bravof960d0462020-12-17 17:27:29 -030021# contact: glavado@whitestack.com or fbravo@whitestack.com
lavado456d0f32019-11-15 17:04:02 -050022##
23import logging
24
25from osm_mon.core.common_db import CommonDbClient
26from osm_mon.core.config import Config
bravof2fe71f22021-01-27 21:22:19 -030027from osm_mon.core.keystone import KeystoneConnection
bravof396648b2020-03-31 18:42:45 -030028from osm_mon.dashboarder.backends.grafana import GrafanaBackend
Gianpietro Lavado1d71df52019-12-02 17:41:20 +000029from osm_mon import __path__ as mon_path
bravof5ac54152021-03-08 16:50:37 -030030from osm_mon.core.utils import find_in_list, create_filter_from_nsr
Atul Agarwal5d7b0d12021-10-19 17:20:52 +000031import re
lavado456d0f32019-11-15 17:04:02 -050032
33log = logging.getLogger(__name__)
34
35
36class DashboarderService:
37 def __init__(self, config: Config):
38 self.conf = config
39 self.common_db = CommonDbClient(self.conf)
bravof396648b2020-03-31 18:42:45 -030040 self.grafana = GrafanaBackend(self.conf)
lavado456d0f32019-11-15 17:04:02 -050041
garciadeblas8e4179f2021-05-14 16:47:03 +020042 if bool(self.conf.get("keystone", "enabled")):
bravof2fe71f22021-01-27 21:22:19 -030043 self.keystone = KeystoneConnection(self.conf)
44 else:
45 self.keystone = None
46
lavado456d0f32019-11-15 17:04:02 -050047 def create_dashboards(self):
48 # TODO lavado: migrate these methods to mongo change streams
49 # Lists all dashboards and OSM resources for later comparisons
Atul Agarwal5d7b0d12021-10-19 17:20:52 +000050 datasource_name_substr = self.conf.get("prometheus-operator", "ds_name_substr")
51 prom_operator_port = self.conf.get("prometheus-operator", "port")
bravof396648b2020-03-31 18:42:45 -030052 dashboard_uids = self.grafana.get_all_dashboard_uids()
Atul Agarwal5d7b0d12021-10-19 17:20:52 +000053 datasource_names = self.grafana.get_all_datasource_names(datasource_name_substr)
lavado456d0f32019-11-15 17:04:02 -050054 osm_resource_uids = []
Atul Agarwal5d7b0d12021-10-19 17:20:52 +000055 osm_datasource_names = []
bravof2fe71f22021-01-27 21:22:19 -030056 projects = []
57
58 # Check if keystone is the auth/projects backend and get projects from there
59 if self.keystone:
60 try:
61 projects.extend(
garciadeblas8e4179f2021-05-14 16:47:03 +020062 map(
63 lambda project: {"_id": project.id, "name": project.name},
64 self.keystone.getProjects(),
65 )
bravof2fe71f22021-01-27 21:22:19 -030066 )
67 except Exception:
garciadeblas8e4179f2021-05-14 16:47:03 +020068 log.error("Cannot retrieve projects from keystone")
Atul Agarwal7af74e42021-03-16 11:02:14 +000069 else:
70 projects.extend(self.common_db.get_projects())
lavado456d0f32019-11-15 17:04:02 -050071
72 # Reads existing project list and creates a dashboard for each
lavado456d0f32019-11-15 17:04:02 -050073 for project in projects:
garciadeblas8e4179f2021-05-14 16:47:03 +020074 project_id = project["_id"]
lavado456d0f32019-11-15 17:04:02 -050075 # Collect Project IDs for periodical dashboard clean-up
76 osm_resource_uids.append(project_id)
garciadeblas8e4179f2021-05-14 16:47:03 +020077 dashboard_path = "{}/dashboarder/templates/project_scoped.json".format(
78 mon_path[0]
79 )
Atul Agarwal5d7b0d12021-10-19 17:20:52 +000080 cnf_dashboard_path = "{}/dashboarder/templates/cnf_scoped.json".format(
81 mon_path[0]
82 )
lavado456d0f32019-11-15 17:04:02 -050083 if project_id not in dashboard_uids:
garciadeblas8e4179f2021-05-14 16:47:03 +020084 project_name = project["name"]
palsus0ab64072021-02-09 18:23:03 +000085 if project_name != "admin":
86 # Create project folder in Grafana only if user is not admin.
87 # Admin user's dashboard will be created in default folder
88 self.grafana.create_grafana_folders(project_name)
garciadeblas8e4179f2021-05-14 16:47:03 +020089 self.grafana.create_dashboard(project_id, project_name, dashboard_path)
90 log.debug("Created dashboard for Project: %s", project_id)
lavado456d0f32019-11-15 17:04:02 -050091 else:
garciadeblas8e4179f2021-05-14 16:47:03 +020092 log.debug("Dashboard already exists")
lavado456d0f32019-11-15 17:04:02 -050093
Atul Agarwal5d7b0d12021-10-19 17:20:52 +000094 # Read existing k8s cluster list and creates a dashboard for each
95 k8sclusters = self.common_db.get_k8sclusters()
96 for k8scluster in k8sclusters:
97 k8scluster_id = k8scluster["_id"]
98 k8scluster_name = k8scluster["name"]
99 osm_resource_uids.append(k8scluster_id)
100 osm_datasource_names.append("{}-{}".format(datasource_name_substr, k8scluster_name))
101 if k8scluster_id not in dashboard_uids:
102 projects_read = k8scluster["_admin"]["projects_read"]
103 if len(projects_read) and projects_read[0] == project_id:
104 # Collect K8S Cluster IDs for periodical dashboard clean-up
105 k8scluster_address = k8scluster["credentials"]["clusters"][0]["cluster"]["server"]
106 # Extract K8S Cluster ip from url
107 k8scluster_ip = re.findall(r'://([\w\-\.]+)', k8scluster_address)[0]
108
109 # prometheus-operator url
110 datasource_url = "http://{}:{}".format(k8scluster_ip, prom_operator_port)
111
112 # Create datsource for prometheus-operator in grafana
113 datasource_type = "prometheus"
114 datasource_name = "{}-{}".format(datasource_name_substr, k8scluster_name)
115 if datasource_name not in datasource_names:
116 self.grafana.create_datasource(datasource_name, datasource_type, datasource_url)
117 log.debug("Created datasource for k8scluster: %s", k8scluster_id)
118
119 if project["name"] != "admin":
120 self.grafana.create_dashboard(
121 k8scluster_id, k8scluster_name, cnf_dashboard_path, project_name=project["name"],
122 datasource_name=datasource_name)
123 else:
124 self.grafana.create_dashboard(
125 k8scluster_id, k8scluster_name, cnf_dashboard_path, datasource_name=datasource_name)
126 log.debug("Created dashboard for k8scluster: %s", k8scluster_id)
127 else:
128 log.debug("Dashboard already exist for k8scluster: %s", k8scluster_id)
129
lavado456d0f32019-11-15 17:04:02 -0500130 # Reads existing NS list and creates a dashboard for each
131 # TODO lavado: only create for ACTIVE NSRs
132 nsrs = self.common_db.get_nsrs()
133 for nsr in nsrs:
garciadeblas8e4179f2021-05-14 16:47:03 +0200134 nsr_id = nsr["_id"]
135 dashboard_path = "{}/dashboarder/templates/ns_scoped.json".format(
136 mon_path[0]
137 )
lavado456d0f32019-11-15 17:04:02 -0500138 # Collect NS IDs for periodical dashboard clean-up
139 osm_resource_uids.append(nsr_id)
140 # Check if the NSR's VNFDs contain metrics
bravof12fda452020-12-17 10:21:22 -0300141 # Only one DF at the moment, support for this feature is comming in the future
garciadeblas8e4179f2021-05-14 16:47:03 +0200142 vnfds_profiles = nsr["nsd"]["df"][0]["vnf-profile"]
bravof12fda452020-12-17 10:21:22 -0300143 for vnf_profile in vnfds_profiles:
lavado456d0f32019-11-15 17:04:02 -0500144 try:
garciadeblas8e4179f2021-05-14 16:47:03 +0200145 vnfd = self.common_db.get_vnfd_by_id(
146 vnf_profile["vnfd-id"], create_filter_from_nsr(nsr)
147 )
lavado456d0f32019-11-15 17:04:02 -0500148 # If there are metrics, create dashboard (if exists)
garciadeblas8e4179f2021-05-14 16:47:03 +0200149 vdu_found = find_in_list(
150 vnfd["vdu"], lambda a_vdu: "monitoring-parameter" in a_vdu
151 )
bravof960d0462020-12-17 17:27:29 -0300152 if vdu_found:
lavado456d0f32019-11-15 17:04:02 -0500153 if nsr_id not in dashboard_uids:
garciadeblas8e4179f2021-05-14 16:47:03 +0200154 nsr_name = nsr["name"]
agarwalat85a91852020-10-08 12:24:47 +0000155 project_id = nsr["_admin"]["projects_read"][0]
palsus0ab64072021-02-09 18:23:03 +0000156 try:
157 # Get project details from commondb
158 project_details = self.common_db.get_project(project_id)
159 project_name = project_details["name"]
160 except Exception as e:
161 # Project not found in commondb
162 if self.keystone:
163 # Serach project in keystone
164 for project in projects:
garciadeblas8e4179f2021-05-14 16:47:03 +0200165 if project_id == project["_id"]:
palsus0ab64072021-02-09 18:23:03 +0000166 project_name = project["name"]
167 else:
garciadeblas8e4179f2021-05-14 16:47:03 +0200168 log.info("Project %s not found", project_id)
169 log.debug("Exception %s" % e)
170 self.grafana.create_dashboard(
Atul Agarwal5d7b0d12021-10-19 17:20:52 +0000171 nsr_id, nsr_name, dashboard_path, project_name=project_name
garciadeblas8e4179f2021-05-14 16:47:03 +0200172 )
173 log.debug("Created dashboard for NS: %s", nsr_id)
lavado456d0f32019-11-15 17:04:02 -0500174 else:
garciadeblas8e4179f2021-05-14 16:47:03 +0200175 log.debug("Dashboard already exists")
lavado456d0f32019-11-15 17:04:02 -0500176 break
177 else:
garciadeblas8e4179f2021-05-14 16:47:03 +0200178 log.debug("NS does not has metrics")
lavado456d0f32019-11-15 17:04:02 -0500179 except Exception:
180 log.exception("VNFD is not valid or has been renamed")
181 continue
182
183 # Delete obsolete dashboards
184 for dashboard_uid in dashboard_uids:
185 if dashboard_uid not in osm_resource_uids:
bravof396648b2020-03-31 18:42:45 -0300186 self.grafana.delete_dashboard(dashboard_uid)
garciadeblas8e4179f2021-05-14 16:47:03 +0200187 log.debug("Deleted obsolete dashboard: %s", dashboard_uid)
lavado456d0f32019-11-15 17:04:02 -0500188 else:
garciadeblas8e4179f2021-05-14 16:47:03 +0200189 log.debug("All dashboards in use")
agarwalat85a91852020-10-08 12:24:47 +0000190
Atul Agarwal5d7b0d12021-10-19 17:20:52 +0000191 # Delete obsolute datasources
192 for datasource_name in datasource_names:
193 if datasource_name not in osm_datasource_names:
194 self.grafana.delete_datasource(datasource_name)
195 log.debug("Deleted obsolete datasource: %s", datasource_name)
196 else:
197 log.debug("All dashboards in use")
198
agarwalat85a91852020-10-08 12:24:47 +0000199 def create_grafana_user(self, user):
200 self.grafana.create_grafana_users(user)
201
Atul Agarwal46dc3bd2021-08-27 12:33:57 +0000202 def delete_non_existing_users(self):
203 if self.keystone:
204 # Get users from keystone
205 users = self.keystone.getUsers()
206 usernames = []
207 for user in users:
208 usernames.append(user.name)
209 grafana_users = self.grafana.get_grafana_users()
210 users_to_be_deleted = list(set(grafana_users) - set(usernames))
211 for grafana_user in users_to_be_deleted:
212 self.grafana.delete_grafana_users(grafana_user)
213
garciadeblas8e4179f2021-05-14 16:47:03 +0200214 def create_grafana_team_member(
215 self, project_data, userid=None, project_list=None, user=None
216 ):
Atul Agarwal806fe452021-03-15 09:16:09 +0000217 if user:
218 user_name = user
219 else:
220 try:
221 # Get user details from commondb
222 user = self.common_db.get_user_by_id(userid)
223 user_name = user["username"]
224 except Exception as e:
225 # User not found in commondb
226 if self.keystone:
227 # Search user in keystone
228 user = self.keystone.getUserById(userid)
229 user_name = user.name
230 else:
garciadeblas8e4179f2021-05-14 16:47:03 +0200231 log.info("User %s not found", userid)
232 log.debug("Exception %s" % e)
Atul Agarwal806fe452021-03-15 09:16:09 +0000233 if project_list:
234 # user-project mapping is done by osm cli
235 for proj in project_data:
236 project = self.common_db.get_project(proj["project"])
garciadeblas8e4179f2021-05-14 16:47:03 +0200237 proj_name = project["name"]
Atul Agarwal806fe452021-03-15 09:16:09 +0000238 role_obj = self.common_db.get_role_by_id(proj["role"])
239 is_admin = role_obj["permissions"].get("admin")
garciadeblas8e4179f2021-05-14 16:47:03 +0200240 self.grafana.create_grafana_teams_members(
241 proj_name, user_name, is_admin, project_list
242 )
Atul Agarwal806fe452021-03-15 09:16:09 +0000243 else:
244 # user-project mapping is done by osm ui
245 proj_list = []
palsus0ab64072021-02-09 18:23:03 +0000246 if self.keystone:
Atul Agarwal806fe452021-03-15 09:16:09 +0000247 users_proj_list = self.keystone.getProjectsById(userid)
248 for project in users_proj_list:
249 proj_list.append(project.name)
palsus0ab64072021-02-09 18:23:03 +0000250 else:
Atul Agarwal806fe452021-03-15 09:16:09 +0000251 users_proj_list = user.get("project_role_mappings")
252 for project in users_proj_list:
253 proj_data = self.common_db.get_project(project["project"])
garciadeblas8e4179f2021-05-14 16:47:03 +0200254 proj_list.append(proj_data["name"])
Atul Agarwal806fe452021-03-15 09:16:09 +0000255 for proj in project_data:
256 if self.keystone:
257 # Backend authentication type is keystone
258 try:
259 # Getting project and role objects from keystone using ids
260 role_obj = self.keystone.getRoleById(proj["role"])
garciadeblas8e4179f2021-05-14 16:47:03 +0200261 proj_data = self.keystone.getProjectsByProjectId(
262 proj["project"]
263 )
264 log.info(
265 "role object {} {}".format(
266 role_obj.permissions, proj_data.name
267 )
268 )
269 is_admin = role_obj.permissions["admin"]
Atul Agarwal806fe452021-03-15 09:16:09 +0000270 except Exception:
271 # Getting project and role objects from keystone using names
272 role_obj = self.keystone.getRoleByName(proj["role"])[0]
garciadeblas8e4179f2021-05-14 16:47:03 +0200273 proj_data = self.keystone.getProjectsByProjectName(
274 proj["project"]
275 )[0]
276 is_admin = role_obj.to_dict().get("permissions").get("admin")
277 log.info(
278 "role object {} {}".format(
279 role_obj.to_dict(), proj_data.name
280 )
281 )
Atul Agarwal806fe452021-03-15 09:16:09 +0000282 proj_name = proj_data.name
283 else:
284 # Backend authentication type is internal
285 try:
286 # Getting project and role object from commondb using names
287 role_obj = self.common_db.get_role_by_name(proj["role"])
288 proj_name = proj["project"]
289 except Exception:
290 # Getting project and role object from commondb using ids
291 role_obj = self.common_db.get_role_by_id(proj["role"])
292 proj_data = self.common_db.get_project(proj["project"])
garciadeblas8e4179f2021-05-14 16:47:03 +0200293 proj_name = proj_data["name"]
Atul Agarwal806fe452021-03-15 09:16:09 +0000294 is_admin = role_obj["permissions"].get("admin")
garciadeblas8e4179f2021-05-14 16:47:03 +0200295 self.grafana.create_grafana_teams_members(
296 proj_name, user_name, is_admin, proj_list
297 )
agarwalat85a91852020-10-08 12:24:47 +0000298
299 def create_grafana_team(self, team_name):
300 self.grafana.create_grafana_teams(team_name)
301
302 def delete_grafana_user(self, user_name):
303 self.grafana.delete_grafana_users(user_name)
304
305 def delete_grafana_team(self, project_name):
306 self.grafana.delete_grafana_team(project_name)
307
308 def update_grafana_team(self, project_new_name, project_old_name):
309 self.grafana.update_grafana_teams(project_new_name, project_old_name)
Atul Agarwal806fe452021-03-15 09:16:09 +0000310
311 def remove_grafana_team_members(self, user_id, proj_data):
312 try:
313 # Get user details from commondb
314 user = self.common_db.get_user_by_id(user_id)
315 user_name = user["username"]
316 except Exception as e:
317 # User not found in commondb
318 if self.keystone:
319 # Find user in keystone
320 user = self.keystone.getUserById(user_id)
321 user_name = user.name
322 else:
garciadeblas8e4179f2021-05-14 16:47:03 +0200323 log.info("User %s not found", user_id)
324 log.debug("Exception %s" % e)
Atul Agarwal806fe452021-03-15 09:16:09 +0000325 self.grafana.remove_grafana_team_member(user_name, proj_data)