Fix bug 771 Do not revoke token when try to do a non allowed operation
[osm/NBI.git] / osm_nbi / engine.py
1 # -*- coding: utf-8 -*-
2
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 # http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
12 # implied.
13 # See the License for the specific language governing permissions and
14 # limitations under the License.
15
16 import logging
17 import yaml
18 from osm_common import dbmongo, dbmemory, fslocal, msglocal, msgkafka, version as common_version
19 from osm_common.dbbase import DbException
20 from osm_common.fsbase import FsException
21 from osm_common.msgbase import MsgException
22 from http import HTTPStatus
23
24 from authconn_keystone import AuthconnKeystone
25 from base_topic import EngineException, versiontuple
26 from admin_topics import UserTopic, ProjectTopic, VimAccountTopic, WimAccountTopic, SdnTopic
27 from admin_topics import UserTopicAuth, ProjectTopicAuth, RoleTopicAuth
28 from descriptor_topics import VnfdTopic, NsdTopic, PduTopic, NstTopic
29 from instance_topics import NsrTopic, VnfrTopic, NsLcmOpTopic, NsiTopic, NsiLcmOpTopic
30 from pmjobs_topics import PmJobsTopic
31 from base64 import b64encode
32 from os import urandom, path
33 from threading import Lock
34
35 __author__ = "Alfonso Tierno <alfonso.tiernosepulveda@telefonica.com>"
36 min_common_version = "0.1.16"
37
38
39 class Engine(object):
40 map_from_topic_to_class = {
41 "vnfds": VnfdTopic,
42 "nsds": NsdTopic,
43 "nsts": NstTopic,
44 "pdus": PduTopic,
45 "nsrs": NsrTopic,
46 "vnfrs": VnfrTopic,
47 "nslcmops": NsLcmOpTopic,
48 "vim_accounts": VimAccountTopic,
49 "wim_accounts": WimAccountTopic,
50 "sdns": SdnTopic,
51 "users": UserTopic,
52 "projects": ProjectTopic,
53 "nsis": NsiTopic,
54 "nsilcmops": NsiLcmOpTopic
55 # [NEW_TOPIC]: add an entry here
56 # "pm_jobs": PmJobsTopic will be added manually because it needs other parameters
57 }
58
59 map_target_version_to_int = {
60 "1.0": 1000,
61 "1.1": 1001,
62 "1.2": 1002,
63 # Add new versions here
64 }
65
66 def __init__(self):
67 self.db = None
68 self.fs = None
69 self.msg = None
70 self.auth = None
71 self.config = None
72 self.operations = None
73 self.logger = logging.getLogger("nbi.engine")
74 self.map_topic = {}
75 self.write_lock = None
76
77 def start(self, config):
78 """
79 Connect to database, filesystem storage, and messaging
80 :param config: two level dictionary with configuration. Top level should contain 'database', 'storage',
81 :return: None
82 """
83 self.config = config
84 # check right version of common
85 if versiontuple(common_version) < versiontuple(min_common_version):
86 raise EngineException("Not compatible osm/common version '{}'. Needed '{}' or higher".format(
87 common_version, min_common_version))
88
89 try:
90 if not self.db:
91 if config["database"]["driver"] == "mongo":
92 self.db = dbmongo.DbMongo()
93 self.db.db_connect(config["database"])
94 elif config["database"]["driver"] == "memory":
95 self.db = dbmemory.DbMemory()
96 self.db.db_connect(config["database"])
97 else:
98 raise EngineException("Invalid configuration param '{}' at '[database]':'driver'".format(
99 config["database"]["driver"]))
100 if not self.fs:
101 if config["storage"]["driver"] == "local":
102 self.fs = fslocal.FsLocal()
103 self.fs.fs_connect(config["storage"])
104 else:
105 raise EngineException("Invalid configuration param '{}' at '[storage]':'driver'".format(
106 config["storage"]["driver"]))
107 if not self.msg:
108 if config["message"]["driver"] == "local":
109 self.msg = msglocal.MsgLocal()
110 self.msg.connect(config["message"])
111 elif config["message"]["driver"] == "kafka":
112 self.msg = msgkafka.MsgKafka()
113 self.msg.connect(config["message"])
114 else:
115 raise EngineException("Invalid configuration param '{}' at '[message]':'driver'".format(
116 config["message"]["driver"]))
117 if not self.auth:
118 if config["authentication"]["backend"] == "keystone":
119 self.auth = AuthconnKeystone(config["authentication"])
120 if not self.operations:
121 if "resources_to_operations" in config["rbac"]:
122 resources_to_operations_file = config["rbac"]["resources_to_operations"]
123 else:
124 possible_paths = (
125 __file__[:__file__.rfind("engine.py")] + "resources_to_operations.yml",
126 "./resources_to_operations.yml"
127 )
128 for config_file in possible_paths:
129 if path.isfile(config_file):
130 resources_to_operations_file = config_file
131 break
132 if not resources_to_operations_file:
133 raise EngineException("Invalid permission configuration: resources_to_operations file missing")
134
135 with open(resources_to_operations_file, 'r') as f:
136 resources_to_operations = yaml.load(f)
137
138 self.operations = []
139
140 for _, value in resources_to_operations["resources_to_operations"].items():
141 if value not in self.operations:
142 self.operations += [value]
143
144 if config["authentication"]["backend"] == "keystone":
145 self.map_from_topic_to_class["users"] = UserTopicAuth
146 self.map_from_topic_to_class["projects"] = ProjectTopicAuth
147 self.map_from_topic_to_class["roles"] = RoleTopicAuth
148
149 self.write_lock = Lock()
150 # create one class per topic
151 for topic, topic_class in self.map_from_topic_to_class.items():
152 if self.auth and topic_class in (UserTopicAuth, ProjectTopicAuth):
153 self.map_topic[topic] = topic_class(self.db, self.fs, self.msg, self.auth)
154 elif self.auth and topic_class == RoleTopicAuth:
155 self.map_topic[topic] = topic_class(self.db, self.fs, self.msg, self.auth,
156 self.operations)
157 else:
158 self.map_topic[topic] = topic_class(self.db, self.fs, self.msg)
159
160 self.map_topic["pm_jobs"] = PmJobsTopic(config["prometheus"].get("host"), config["prometheus"].get("port"))
161 except (DbException, FsException, MsgException) as e:
162 raise EngineException(str(e), http_code=e.http_code)
163
164 def stop(self):
165 try:
166 if self.db:
167 self.db.db_disconnect()
168 if self.fs:
169 self.fs.fs_disconnect()
170 if self.msg:
171 self.msg.disconnect()
172 self.write_lock = None
173 except (DbException, FsException, MsgException) as e:
174 raise EngineException(str(e), http_code=e.http_code)
175
176 def new_item(self, rollback, session, topic, indata=None, kwargs=None, headers=None):
177 """
178 Creates a new entry into database. For nsds and vnfds it creates an almost empty DISABLED entry,
179 that must be completed with a call to method upload_content
180 :param rollback: list to append created items at database in case a rollback must to be done
181 :param session: contains the used login username and working project, force to avoid checkins, public
182 :param topic: it can be: users, projects, vim_accounts, sdns, nsrs, nsds, vnfds
183 :param indata: data to be inserted
184 :param kwargs: used to override the indata descriptor
185 :param headers: http request headers
186 :return: _id: identity of the inserted data.
187 """
188 if topic not in self.map_topic:
189 raise EngineException("Unknown topic {}!!!".format(topic), HTTPStatus.INTERNAL_SERVER_ERROR)
190 with self.write_lock:
191 return self.map_topic[topic].new(rollback, session, indata, kwargs, headers)
192
193 def upload_content(self, session, topic, _id, indata, kwargs, headers):
194 """
195 Upload content for an already created entry (_id)
196 :param session: contains the used login username and working project
197 :param topic: it can be: users, projects, vnfds, nsds,
198 :param _id: server id of the item
199 :param indata: data to be inserted
200 :param kwargs: used to override the indata descriptor
201 :param headers: http request headers
202 :return: _id: identity of the inserted data.
203 """
204 if topic not in self.map_topic:
205 raise EngineException("Unknown topic {}!!!".format(topic), HTTPStatus.INTERNAL_SERVER_ERROR)
206 with self.write_lock:
207 return self.map_topic[topic].upload_content(session, _id, indata, kwargs, headers)
208
209 def get_item_list(self, session, topic, filter_q=None):
210 """
211 Get a list of items
212 :param session: contains the used login username and working project
213 :param topic: it can be: users, projects, vnfds, nsds, ...
214 :param filter_q: filter of data to be applied
215 :return: The list, it can be empty if no one match the filter_q.
216 """
217 if topic not in self.map_topic:
218 raise EngineException("Unknown topic {}!!!".format(topic), HTTPStatus.INTERNAL_SERVER_ERROR)
219 return self.map_topic[topic].list(session, filter_q)
220
221 def get_item(self, session, topic, _id):
222 """
223 Get complete information on an item
224 :param session: contains the used login username and working project
225 :param topic: it can be: users, projects, vnfds, nsds,
226 :param _id: server id of the item
227 :return: dictionary, raise exception if not found.
228 """
229 if topic not in self.map_topic:
230 raise EngineException("Unknown topic {}!!!".format(topic), HTTPStatus.INTERNAL_SERVER_ERROR)
231 return self.map_topic[topic].show(session, _id)
232
233 def get_file(self, session, topic, _id, path=None, accept_header=None):
234 """
235 Get descriptor package or artifact file content
236 :param session: contains the used login username and working project
237 :param topic: it can be: users, projects, vnfds, nsds,
238 :param _id: server id of the item
239 :param path: artifact path or "$DESCRIPTOR" or None
240 :param accept_header: Content of Accept header. Must contain applition/zip or/and text/plain
241 :return: opened file plus Accept format or raises an exception
242 """
243 if topic not in self.map_topic:
244 raise EngineException("Unknown topic {}!!!".format(topic), HTTPStatus.INTERNAL_SERVER_ERROR)
245 return self.map_topic[topic].get_file(session, _id, path, accept_header)
246
247 def del_item_list(self, session, topic, _filter=None):
248 """
249 Delete a list of items
250 :param session: contains the used login username and working project
251 :param topic: it can be: users, projects, vnfds, nsds, ...
252 :param _filter: filter of data to be applied
253 :return: The deleted list, it can be empty if no one match the _filter.
254 """
255 if topic not in self.map_topic:
256 raise EngineException("Unknown topic {}!!!".format(topic), HTTPStatus.INTERNAL_SERVER_ERROR)
257 with self.write_lock:
258 return self.map_topic[topic].delete_list(session, _filter)
259
260 def del_item(self, session, topic, _id):
261 """
262 Delete item by its internal id
263 :param session: contains the used login username and working project
264 :param topic: it can be: users, projects, vnfds, nsds, ...
265 :param _id: server id of the item
266 :return: dictionary with deleted item _id. It raises exception if not found.
267 """
268 if topic not in self.map_topic:
269 raise EngineException("Unknown topic {}!!!".format(topic), HTTPStatus.INTERNAL_SERVER_ERROR)
270 with self.write_lock:
271 return self.map_topic[topic].delete(session, _id)
272
273 def edit_item(self, session, topic, _id, indata=None, kwargs=None):
274 """
275 Update an existing entry at database
276 :param session: contains the used login username and working project
277 :param topic: it can be: users, projects, vnfds, nsds, ...
278 :param _id: identifier to be updated
279 :param indata: data to be inserted
280 :param kwargs: used to override the indata descriptor
281 :return: dictionary, raise exception if not found.
282 """
283 if topic not in self.map_topic:
284 raise EngineException("Unknown topic {}!!!".format(topic), HTTPStatus.INTERNAL_SERVER_ERROR)
285 with self.write_lock:
286 return self.map_topic[topic].edit(session, _id, indata, kwargs)
287
288 def create_admin_project(self):
289 """
290 Creates a new project 'admin' into database if database is empty. Useful for initialization.
291 :return: _id identity of the inserted data, or None
292 """
293
294 projects = self.db.get_one("projects", fail_on_empty=False, fail_on_more=False)
295 if projects:
296 return None
297 project_desc = {"name": "admin"}
298 fake_session = {"project_id": "admin", "username": "admin", "admin": True, "force": True, "public": None}
299 rollback_list = []
300 _id = self.map_topic["projects"].new(rollback_list, fake_session, project_desc)
301 return _id
302
303 def create_admin_user(self):
304 """
305 Creates a new user admin/admin into database if database is empty. Useful for initialization
306 :return: _id identity of the inserted data, or None
307 """
308 users = self.db.get_one("users", fail_on_empty=False, fail_on_more=False)
309 if users:
310 return None
311 # raise EngineException("Unauthorized. Database users is not empty", HTTPStatus.UNAUTHORIZED)
312 user_desc = {"username": "admin", "password": "admin", "projects": ["admin"]}
313 fake_session = {"project_id": "admin", "username": "admin", "admin": True, "force": True, "public": None}
314 roolback_list = []
315 _id = self.map_topic["users"].new(roolback_list, fake_session, user_desc)
316 return _id
317
318 def create_admin(self):
319 """
320 Creates new 'admin' user and project into database if database is empty. Useful for initialization.
321 :return: _id identity of the inserted data, or None
322 """
323 project_id = self.create_admin_project()
324 user_id = self.create_admin_user()
325 if not project_id and not user_id:
326 return None
327 else:
328 return {'project_id': project_id, 'user_id': user_id}
329
330 def upgrade_db(self, current_version, target_version):
331 if target_version not in self.map_target_version_to_int.keys():
332 raise EngineException("Cannot upgrade to version '{}' with this version of code".format(target_version),
333 http_code=HTTPStatus.INTERNAL_SERVER_ERROR)
334
335 if current_version == target_version:
336 return
337
338 target_version_int = self.map_target_version_to_int[target_version]
339
340 if not current_version:
341 # create database version
342 serial = urandom(32)
343 version_data = {
344 "_id": "version", # Always "version"
345 "version_int": 1000, # version number
346 "version": "1.0", # version text
347 "date": "2018-10-25", # version date
348 "description": "added serial", # changes in this version
349 'status': "ENABLED", # ENABLED, DISABLED (migration in process), ERROR,
350 'serial': b64encode(serial)
351 }
352 self.db.create("admin", version_data)
353 self.db.set_secret_key(serial)
354 current_version = "1.0"
355
356 if current_version in ("1.0", "1.1") and target_version_int >= self.map_target_version_to_int["1.2"]:
357 self.db.del_list("roles_operations")
358
359 version_data = {
360 "_id": "version",
361 "version_int": 1002,
362 "version": "1.2",
363 "date": "2019-06-11",
364 "description": "set new format for roles_operations"
365 }
366
367 self.db.set_one("admin", {"_id": "version"}, version_data)
368 current_version = "1.2"
369 # TODO add future migrations here
370
371 def init_db(self, target_version='1.0'):
372 """
373 Init database if empty. If not empty it checks that database version and migrates if needed
374 If empty, it creates a new user admin/admin at 'users' and a new entry at 'version'
375 :param target_version: check desired database version. Migrate to it if possible or raises exception
376 :return: None if ok, exception if error or if the version is different.
377 """
378
379 version_data = self.db.get_one("admin", {"_id": "version"}, fail_on_empty=False, fail_on_more=True)
380 # check database status is ok
381 if version_data and version_data.get("status") != 'ENABLED':
382 raise EngineException("Wrong database status '{}'".format(
383 version_data["status"]), HTTPStatus.INTERNAL_SERVER_ERROR)
384
385 # check version
386 db_version = None if not version_data else version_data.get("version")
387 if db_version != target_version:
388 self.upgrade_db(db_version, target_version)
389
390 # create user admin if not exist
391 if not self.auth:
392 self.create_admin()
393
394 return