blob: 4713b89f698c557273756ecd76766fe211ed832a [file] [log] [blame]
tiernoc94c3df2018-02-09 15:38:54 +01001# -*- coding: utf-8 -*-
2
tiernoc94c3df2018-02-09 15:38:54 +01003import logging
tiernob24258a2018-10-04 18:39:49 +02004from osm_common import dbmongo, dbmemory, fslocal, msglocal, msgkafka, version as common_version
5from osm_common.dbbase import DbException
tiernoa8d63632018-05-10 13:12:32 +02006from osm_common.fsbase import FsException
7from osm_common.msgbase import MsgException
tiernoc94c3df2018-02-09 15:38:54 +01008from http import HTTPStatus
tiernob24258a2018-10-04 18:39:49 +02009from base_topic import EngineException, versiontuple
10from admin_topics import UserTopic, ProjectTopic, VimAccountTopic, SdnTopic
Felipe Vicensb57758d2018-10-16 16:00:20 +020011from descriptor_topics import VnfdTopic, NsdTopic, PduTopic, NstTopic
Felipe Vicens07f31722018-10-29 15:16:44 +010012from instance_topics import NsrTopic, VnfrTopic, NsLcmOpTopic, NsiTopic, NsiLcmOpTopic
tiernod985a8d2018-10-19 14:12:28 +020013from base64 import b64encode
14from os import urandom
tiernoc94c3df2018-02-09 15:38:54 +010015
16__author__ = "Alfonso Tierno <alfonso.tiernosepulveda@telefonica.com>"
tiernob24258a2018-10-04 18:39:49 +020017min_common_version = "0.1.8"
tierno441dbbf2018-07-10 12:52:48 +020018
19
tiernoc94c3df2018-02-09 15:38:54 +010020class Engine(object):
tiernob24258a2018-10-04 18:39:49 +020021 map_from_topic_to_class = {
22 "vnfds": VnfdTopic,
23 "nsds": NsdTopic,
Felipe Vicensb57758d2018-10-16 16:00:20 +020024 "nsts": NstTopic,
tiernob24258a2018-10-04 18:39:49 +020025 "pdus": PduTopic,
26 "nsrs": NsrTopic,
27 "vnfrs": VnfrTopic,
28 "nslcmops": NsLcmOpTopic,
29 "vim_accounts": VimAccountTopic,
30 "sdns": SdnTopic,
31 "users": UserTopic,
32 "projects": ProjectTopic,
Felipe Vicensb57758d2018-10-16 16:00:20 +020033 "nsis": NsiTopic,
Felipe Vicens07f31722018-10-29 15:16:44 +010034 "nsilcmops": NsiLcmOpTopic
tiernob24258a2018-10-04 18:39:49 +020035 # [NEW_TOPIC]: add an entry here
36 }
tiernoc94c3df2018-02-09 15:38:54 +010037
38 def __init__(self):
tiernoc94c3df2018-02-09 15:38:54 +010039 self.db = None
40 self.fs = None
41 self.msg = None
42 self.config = None
43 self.logger = logging.getLogger("nbi.engine")
tiernob24258a2018-10-04 18:39:49 +020044 self.map_topic = {}
tiernoc94c3df2018-02-09 15:38:54 +010045
46 def start(self, config):
47 """
48 Connect to database, filesystem storage, and messaging
49 :param config: two level dictionary with configuration. Top level should contain 'database', 'storage',
50 :return: None
51 """
52 self.config = config
tiernob24258a2018-10-04 18:39:49 +020053 # check right version of common
54 if versiontuple(common_version) < versiontuple(min_common_version):
55 raise EngineException("Not compatible osm/common version '{}'. Needed '{}' or higher".format(
56 common_version, min_common_version))
57
tiernoc94c3df2018-02-09 15:38:54 +010058 try:
59 if not self.db:
60 if config["database"]["driver"] == "mongo":
61 self.db = dbmongo.DbMongo()
62 self.db.db_connect(config["database"])
63 elif config["database"]["driver"] == "memory":
64 self.db = dbmemory.DbMemory()
65 self.db.db_connect(config["database"])
66 else:
67 raise EngineException("Invalid configuration param '{}' at '[database]':'driver'".format(
68 config["database"]["driver"]))
69 if not self.fs:
70 if config["storage"]["driver"] == "local":
71 self.fs = fslocal.FsLocal()
72 self.fs.fs_connect(config["storage"])
73 else:
74 raise EngineException("Invalid configuration param '{}' at '[storage]':'driver'".format(
75 config["storage"]["driver"]))
76 if not self.msg:
77 if config["message"]["driver"] == "local":
78 self.msg = msglocal.MsgLocal()
79 self.msg.connect(config["message"])
80 elif config["message"]["driver"] == "kafka":
81 self.msg = msgkafka.MsgKafka()
82 self.msg.connect(config["message"])
83 else:
84 raise EngineException("Invalid configuration param '{}' at '[message]':'driver'".format(
85 config["storage"]["driver"]))
tiernob24258a2018-10-04 18:39:49 +020086
87 # create one class per topic
88 for topic, topic_class in self.map_from_topic_to_class.items():
89 self.map_topic[topic] = topic_class(self.db, self.fs, self.msg)
tiernoc94c3df2018-02-09 15:38:54 +010090 except (DbException, FsException, MsgException) as e:
91 raise EngineException(str(e), http_code=e.http_code)
92
93 def stop(self):
94 try:
95 if self.db:
96 self.db.db_disconnect()
97 if self.fs:
98 self.fs.fs_disconnect()
99 if self.fs:
100 self.fs.fs_disconnect()
101 except (DbException, FsException, MsgException) as e:
102 raise EngineException(str(e), http_code=e.http_code)
103
tiernob24258a2018-10-04 18:39:49 +0200104 def new_item(self, rollback, session, topic, indata=None, kwargs=None, headers=None, force=False):
tiernoc94c3df2018-02-09 15:38:54 +0100105 """
tiernof27c79b2018-03-12 17:08:42 +0100106 Creates a new entry into database. For nsds and vnfds it creates an almost empty DISABLED entry,
107 that must be completed with a call to method upload_content
tiernob24258a2018-10-04 18:39:49 +0200108 :param rollback: list to append created items at database in case a rollback must to be done
tiernoc94c3df2018-02-09 15:38:54 +0100109 :param session: contains the used login username and working project
tiernob24258a2018-10-04 18:39:49 +0200110 :param topic: it can be: users, projects, vim_accounts, sdns, nsrs, nsds, vnfds
tiernoc94c3df2018-02-09 15:38:54 +0100111 :param indata: data to be inserted
112 :param kwargs: used to override the indata descriptor
113 :param headers: http request headers
tiernob92094f2018-05-11 13:44:22 +0200114 :param force: If True avoid some dependence checks
tierno0ffaa992018-05-09 13:21:56 +0200115 :return: _id: identity of the inserted data.
tiernoc94c3df2018-02-09 15:38:54 +0100116 """
tiernob24258a2018-10-04 18:39:49 +0200117 if topic not in self.map_topic:
118 raise EngineException("Unknown topic {}!!!".format(topic), HTTPStatus.INTERNAL_SERVER_ERROR)
119 return self.map_topic[topic].new(rollback, session, indata, kwargs, headers, force)
tiernoc94c3df2018-02-09 15:38:54 +0100120
tiernob24258a2018-10-04 18:39:49 +0200121 def upload_content(self, session, topic, _id, indata, kwargs, headers, force=False):
tierno65acb4d2018-04-06 16:42:40 +0200122 """
tiernob24258a2018-10-04 18:39:49 +0200123 Upload content for an already created entry (_id)
tierno65acb4d2018-04-06 16:42:40 +0200124 :param session: contains the used login username and working project
tiernob24258a2018-10-04 18:39:49 +0200125 :param topic: it can be: users, projects, vnfds, nsds,
126 :param _id: server id of the item
127 :param indata: data to be inserted
tierno65acb4d2018-04-06 16:42:40 +0200128 :param kwargs: used to override the indata descriptor
tiernob24258a2018-10-04 18:39:49 +0200129 :param headers: http request headers
130 :param force: If True avoid some dependence checks
131 :return: _id: identity of the inserted data.
tierno65acb4d2018-04-06 16:42:40 +0200132 """
tiernob24258a2018-10-04 18:39:49 +0200133 if topic not in self.map_topic:
134 raise EngineException("Unknown topic {}!!!".format(topic), HTTPStatus.INTERNAL_SERVER_ERROR)
135 return self.map_topic[topic].upload_content(session, _id, indata, kwargs, headers, force)
tiernoc94c3df2018-02-09 15:38:54 +0100136
tiernob24258a2018-10-04 18:39:49 +0200137 def get_item_list(self, session, topic, filter_q=None):
tiernoc94c3df2018-02-09 15:38:54 +0100138 """
139 Get a list of items
140 :param session: contains the used login username and working project
tiernob24258a2018-10-04 18:39:49 +0200141 :param topic: it can be: users, projects, vnfds, nsds, ...
142 :param filter_q: filter of data to be applied
143 :return: The list, it can be empty if no one match the filter_q.
tiernoc94c3df2018-02-09 15:38:54 +0100144 """
tiernob24258a2018-10-04 18:39:49 +0200145 if topic not in self.map_topic:
146 raise EngineException("Unknown topic {}!!!".format(topic), HTTPStatus.INTERNAL_SERVER_ERROR)
147 return self.map_topic[topic].list(session, filter_q)
tiernof27c79b2018-03-12 17:08:42 +0100148
tiernob24258a2018-10-04 18:39:49 +0200149 def get_item(self, session, topic, _id):
tiernoc94c3df2018-02-09 15:38:54 +0100150 """
tiernob24258a2018-10-04 18:39:49 +0200151 Get complete information on an item
tiernoc94c3df2018-02-09 15:38:54 +0100152 :param session: contains the used login username and working project
tiernob24258a2018-10-04 18:39:49 +0200153 :param topic: it can be: users, projects, vnfds, nsds,
tiernoc94c3df2018-02-09 15:38:54 +0100154 :param _id: server id of the item
155 :return: dictionary, raise exception if not found.
156 """
tiernob24258a2018-10-04 18:39:49 +0200157 if topic not in self.map_topic:
158 raise EngineException("Unknown topic {}!!!".format(topic), HTTPStatus.INTERNAL_SERVER_ERROR)
159 return self.map_topic[topic].show(session, _id)
tiernoc94c3df2018-02-09 15:38:54 +0100160
tierno87006042018-10-24 12:50:20 +0200161 def get_file(self, session, topic, _id, path=None, accept_header=None):
162 """
163 Get descriptor package or artifact file content
164 :param session: contains the used login username and working project
165 :param topic: it can be: users, projects, vnfds, nsds,
166 :param _id: server id of the item
167 :param path: artifact path or "$DESCRIPTOR" or None
168 :param accept_header: Content of Accept header. Must contain applition/zip or/and text/plain
169 :return: opened file plus Accept format or raises an exception
170 """
171 if topic not in self.map_topic:
172 raise EngineException("Unknown topic {}!!!".format(topic), HTTPStatus.INTERNAL_SERVER_ERROR)
173 return self.map_topic[topic].get_file(session, _id, path, accept_header)
174
tiernob24258a2018-10-04 18:39:49 +0200175 def del_item_list(self, session, topic, _filter=None):
tiernoc94c3df2018-02-09 15:38:54 +0100176 """
177 Delete a list of items
178 :param session: contains the used login username and working project
tiernob24258a2018-10-04 18:39:49 +0200179 :param topic: it can be: users, projects, vnfds, nsds, ...
180 :param _filter: filter of data to be applied
181 :return: The deleted list, it can be empty if no one match the _filter.
tiernoc94c3df2018-02-09 15:38:54 +0100182 """
tiernob24258a2018-10-04 18:39:49 +0200183 if topic not in self.map_topic:
184 raise EngineException("Unknown topic {}!!!".format(topic), HTTPStatus.INTERNAL_SERVER_ERROR)
185 return self.map_topic[topic].delete_list(session, _filter)
tiernoc94c3df2018-02-09 15:38:54 +0100186
tiernob24258a2018-10-04 18:39:49 +0200187 def del_item(self, session, topic, _id, force=False):
tiernoc94c3df2018-02-09 15:38:54 +0100188 """
tiernob92094f2018-05-11 13:44:22 +0200189 Delete item by its internal id
tiernoc94c3df2018-02-09 15:38:54 +0100190 :param session: contains the used login username and working project
tiernob24258a2018-10-04 18:39:49 +0200191 :param topic: it can be: users, projects, vnfds, nsds, ...
tiernoc94c3df2018-02-09 15:38:54 +0100192 :param _id: server id of the item
tierno65acb4d2018-04-06 16:42:40 +0200193 :param force: indicates if deletion must be forced in case of conflict
tierno09c073e2018-04-26 13:36:48 +0200194 :return: dictionary with deleted item _id. It raises exception if not found.
tiernoc94c3df2018-02-09 15:38:54 +0100195 """
tiernob24258a2018-10-04 18:39:49 +0200196 if topic not in self.map_topic:
197 raise EngineException("Unknown topic {}!!!".format(topic), HTTPStatus.INTERNAL_SERVER_ERROR)
198 return self.map_topic[topic].delete(session, _id, force)
tiernoc94c3df2018-02-09 15:38:54 +0100199
tiernob24258a2018-10-04 18:39:49 +0200200 def edit_item(self, session, topic, _id, indata=None, kwargs=None, force=False):
201 """
202 Update an existing entry at database
203 :param session: contains the used login username and working project
204 :param topic: it can be: users, projects, vnfds, nsds, ...
205 :param _id: identifier to be updated
206 :param indata: data to be inserted
207 :param kwargs: used to override the indata descriptor
208 :param force: If True avoid some dependence checks
209 :return: dictionary, raise exception if not found.
210 """
211 if topic not in self.map_topic:
212 raise EngineException("Unknown topic {}!!!".format(topic), HTTPStatus.INTERNAL_SERVER_ERROR)
213 return self.map_topic[topic].edit(session, _id, indata, kwargs, force)
tiernoc94c3df2018-02-09 15:38:54 +0100214
215 def prune(self):
216 """
217 Prune database not needed content
218 :return: None
219 """
220 return self.db.del_list("nsrs", {"_admin.to_delete": True})
221
222 def create_admin(self):
223 """
tierno4a946e42018-04-12 17:48:49 +0200224 Creates a new user admin/admin into database if database is empty. Useful for initialization
225 :return: _id identity of the inserted data, or None
tiernoc94c3df2018-02-09 15:38:54 +0100226 """
227 users = self.db.get_one("users", fail_on_empty=False, fail_on_more=False)
228 if users:
tierno4a946e42018-04-12 17:48:49 +0200229 return None
230 # raise EngineException("Unauthorized. Database users is not empty", HTTPStatus.UNAUTHORIZED)
tiernob24258a2018-10-04 18:39:49 +0200231 user_desc = {"username": "admin", "password": "admin", "projects": ["admin"]}
232 fake_session = {"project_id": "admin", "username": "admin", "admin": True}
233 roolback_list = []
234 _id = self.map_topic["users"].new(roolback_list, fake_session, user_desc, force=True)
tiernoc94c3df2018-02-09 15:38:54 +0100235 return _id
236
tiernod985a8d2018-10-19 14:12:28 +0200237 def upgrade_db(self, current_version, target_version):
238 if not target_version or current_version == target_version:
239 return
240 if target_version == '1.0':
241 if not current_version:
242 # create database version
243 serial = urandom(32)
244 version_data = {
245 "_id": 'version', # Always 'version'
246 "version_int": 1000, # version number
247 "version": '1.0', # version text
248 "date": "2018-10-25", # version date
249 "description": "added serial", # changes in this version
250 'status': 'ENABLED', # ENABLED, DISABLED (migration in process), ERROR,
251 'serial': b64encode(serial)
252 }
253 self.db.create("admin", version_data)
254 self.db.set_secret_key(serial)
255 # TODO add future migrations here
256
257 raise EngineException("Wrong database version '{}'. Expected '{}'"
258 ". It cannot be up/down-grade".format(current_version, target_version),
259 http_code=HTTPStatus.INTERNAL_SERVER_ERROR)
260
tierno4a946e42018-04-12 17:48:49 +0200261 def init_db(self, target_version='1.0'):
262 """
tiernod985a8d2018-10-19 14:12:28 +0200263 Init database if empty. If not empty it checks that database version and migrates if needed
tierno4a946e42018-04-12 17:48:49 +0200264 If empty, it creates a new user admin/admin at 'users' and a new entry at 'version'
tiernod985a8d2018-10-19 14:12:28 +0200265 :param target_version: check desired database version. Migrate to it if possible or raises exception
tierno4a946e42018-04-12 17:48:49 +0200266 :return: None if ok, exception if error or if the version is different.
267 """
tiernod985a8d2018-10-19 14:12:28 +0200268
269 version_data = self.db.get_one("admin", {"_id": "version"}, fail_on_empty=False, fail_on_more=True)
270 # check database status is ok
271 if version_data and version_data.get("status") != 'ENABLED':
tierno4a946e42018-04-12 17:48:49 +0200272 raise EngineException("Wrong database status '{}'".format(
tiernod985a8d2018-10-19 14:12:28 +0200273 version_data["status"]), HTTPStatus.INTERNAL_SERVER_ERROR)
274
275 # check version
276 db_version = None if not version_data else version_data.get("version")
277 if db_version != target_version:
278 self.upgrade_db(db_version, target_version)
279
280 # create user admin if not exist
281 self.create_admin()
tierno4a946e42018-04-12 17:48:49 +0200282 return