Adding slice templates to NBI
[osm/NBI.git] / osm_nbi / engine.py
1 # -*- coding: utf-8 -*-
2
3 import logging
4 from osm_common import dbmongo, dbmemory, fslocal, msglocal, msgkafka, version as common_version
5 from osm_common.dbbase import DbException
6 from osm_common.fsbase import FsException
7 from osm_common.msgbase import MsgException
8 from http import HTTPStatus
9 from base_topic import EngineException, versiontuple
10 from admin_topics import UserTopic, ProjectTopic, VimAccountTopic, SdnTopic
11 from descriptor_topics import VnfdTopic, NsdTopic, PduTopic, NstTopic
12 from instance_topics import NsrTopic, VnfrTopic, NsLcmOpTopic, NsiTopic
13 from base64 import b64encode
14 from os import urandom
15
16 __author__ = "Alfonso Tierno <alfonso.tiernosepulveda@telefonica.com>"
17 min_common_version = "0.1.8"
18
19
20 class Engine(object):
21 map_from_topic_to_class = {
22 "vnfds": VnfdTopic,
23 "nsds": NsdTopic,
24 "nsts": NstTopic,
25 "pdus": PduTopic,
26 "nsrs": NsrTopic,
27 "vnfrs": VnfrTopic,
28 "nslcmops": NsLcmOpTopic,
29 "vim_accounts": VimAccountTopic,
30 "sdns": SdnTopic,
31 "users": UserTopic,
32 "projects": ProjectTopic,
33 "nsis": NsiTopic,
34 # [NEW_TOPIC]: add an entry here
35 }
36
37 def __init__(self):
38 self.db = None
39 self.fs = None
40 self.msg = None
41 self.config = None
42 self.logger = logging.getLogger("nbi.engine")
43 self.map_topic = {}
44
45 def start(self, config):
46 """
47 Connect to database, filesystem storage, and messaging
48 :param config: two level dictionary with configuration. Top level should contain 'database', 'storage',
49 :return: None
50 """
51 self.config = config
52 # check right version of common
53 if versiontuple(common_version) < versiontuple(min_common_version):
54 raise EngineException("Not compatible osm/common version '{}'. Needed '{}' or higher".format(
55 common_version, min_common_version))
56
57 try:
58 if not self.db:
59 if config["database"]["driver"] == "mongo":
60 self.db = dbmongo.DbMongo()
61 self.db.db_connect(config["database"])
62 elif config["database"]["driver"] == "memory":
63 self.db = dbmemory.DbMemory()
64 self.db.db_connect(config["database"])
65 else:
66 raise EngineException("Invalid configuration param '{}' at '[database]':'driver'".format(
67 config["database"]["driver"]))
68 if not self.fs:
69 if config["storage"]["driver"] == "local":
70 self.fs = fslocal.FsLocal()
71 self.fs.fs_connect(config["storage"])
72 else:
73 raise EngineException("Invalid configuration param '{}' at '[storage]':'driver'".format(
74 config["storage"]["driver"]))
75 if not self.msg:
76 if config["message"]["driver"] == "local":
77 self.msg = msglocal.MsgLocal()
78 self.msg.connect(config["message"])
79 elif config["message"]["driver"] == "kafka":
80 self.msg = msgkafka.MsgKafka()
81 self.msg.connect(config["message"])
82 else:
83 raise EngineException("Invalid configuration param '{}' at '[message]':'driver'".format(
84 config["storage"]["driver"]))
85
86 # create one class per topic
87 for topic, topic_class in self.map_from_topic_to_class.items():
88 self.map_topic[topic] = topic_class(self.db, self.fs, self.msg)
89 except (DbException, FsException, MsgException) as e:
90 raise EngineException(str(e), http_code=e.http_code)
91
92 def stop(self):
93 try:
94 if self.db:
95 self.db.db_disconnect()
96 if self.fs:
97 self.fs.fs_disconnect()
98 if self.fs:
99 self.fs.fs_disconnect()
100 except (DbException, FsException, MsgException) as e:
101 raise EngineException(str(e), http_code=e.http_code)
102
103 def new_item(self, rollback, session, topic, indata=None, kwargs=None, headers=None, force=False):
104 """
105 Creates a new entry into database. For nsds and vnfds it creates an almost empty DISABLED entry,
106 that must be completed with a call to method upload_content
107 :param rollback: list to append created items at database in case a rollback must to be done
108 :param session: contains the used login username and working project
109 :param topic: it can be: users, projects, vim_accounts, sdns, nsrs, nsds, vnfds
110 :param indata: data to be inserted
111 :param kwargs: used to override the indata descriptor
112 :param headers: http request headers
113 :param force: If True avoid some dependence checks
114 :return: _id: identity of the inserted data.
115 """
116 if topic not in self.map_topic:
117 raise EngineException("Unknown topic {}!!!".format(topic), HTTPStatus.INTERNAL_SERVER_ERROR)
118 return self.map_topic[topic].new(rollback, session, indata, kwargs, headers, force)
119
120 def upload_content(self, session, topic, _id, indata, kwargs, headers, force=False):
121 """
122 Upload content for an already created entry (_id)
123 :param session: contains the used login username and working project
124 :param topic: it can be: users, projects, vnfds, nsds,
125 :param _id: server id of the item
126 :param indata: data to be inserted
127 :param kwargs: used to override the indata descriptor
128 :param headers: http request headers
129 :param force: If True avoid some dependence checks
130 :return: _id: identity of the inserted data.
131 """
132 if topic not in self.map_topic:
133 raise EngineException("Unknown topic {}!!!".format(topic), HTTPStatus.INTERNAL_SERVER_ERROR)
134 return self.map_topic[topic].upload_content(session, _id, indata, kwargs, headers, force)
135
136 def get_item_list(self, session, topic, filter_q=None):
137 """
138 Get a list of items
139 :param session: contains the used login username and working project
140 :param topic: it can be: users, projects, vnfds, nsds, ...
141 :param filter_q: filter of data to be applied
142 :return: The list, it can be empty if no one match the filter_q.
143 """
144 if topic not in self.map_topic:
145 raise EngineException("Unknown topic {}!!!".format(topic), HTTPStatus.INTERNAL_SERVER_ERROR)
146 return self.map_topic[topic].list(session, filter_q)
147
148 def get_item(self, session, topic, _id):
149 """
150 Get complete information on an item
151 :param session: contains the used login username and working project
152 :param topic: it can be: users, projects, vnfds, nsds,
153 :param _id: server id of the item
154 :return: dictionary, raise exception if not found.
155 """
156 if topic not in self.map_topic:
157 raise EngineException("Unknown topic {}!!!".format(topic), HTTPStatus.INTERNAL_SERVER_ERROR)
158 return self.map_topic[topic].show(session, _id)
159
160 def get_file(self, session, topic, _id, path=None, accept_header=None):
161 """
162 Get descriptor package or artifact file content
163 :param session: contains the used login username and working project
164 :param topic: it can be: users, projects, vnfds, nsds,
165 :param _id: server id of the item
166 :param path: artifact path or "$DESCRIPTOR" or None
167 :param accept_header: Content of Accept header. Must contain applition/zip or/and text/plain
168 :return: opened file plus Accept format or raises an exception
169 """
170 if topic not in self.map_topic:
171 raise EngineException("Unknown topic {}!!!".format(topic), HTTPStatus.INTERNAL_SERVER_ERROR)
172 return self.map_topic[topic].get_file(session, _id, path, accept_header)
173
174 def del_item_list(self, session, topic, _filter=None):
175 """
176 Delete a list of items
177 :param session: contains the used login username and working project
178 :param topic: it can be: users, projects, vnfds, nsds, ...
179 :param _filter: filter of data to be applied
180 :return: The deleted list, it can be empty if no one match the _filter.
181 """
182 if topic not in self.map_topic:
183 raise EngineException("Unknown topic {}!!!".format(topic), HTTPStatus.INTERNAL_SERVER_ERROR)
184 return self.map_topic[topic].delete_list(session, _filter)
185
186 def del_item(self, session, topic, _id, force=False):
187 """
188 Delete item by its internal id
189 :param session: contains the used login username and working project
190 :param topic: it can be: users, projects, vnfds, nsds, ...
191 :param _id: server id of the item
192 :param force: indicates if deletion must be forced in case of conflict
193 :return: dictionary with deleted item _id. It raises exception if not found.
194 """
195 if topic not in self.map_topic:
196 raise EngineException("Unknown topic {}!!!".format(topic), HTTPStatus.INTERNAL_SERVER_ERROR)
197 return self.map_topic[topic].delete(session, _id, force)
198
199 def edit_item(self, session, topic, _id, indata=None, kwargs=None, force=False):
200 """
201 Update an existing entry at database
202 :param session: contains the used login username and working project
203 :param topic: it can be: users, projects, vnfds, nsds, ...
204 :param _id: identifier to be updated
205 :param indata: data to be inserted
206 :param kwargs: used to override the indata descriptor
207 :param force: If True avoid some dependence checks
208 :return: dictionary, raise exception if not found.
209 """
210 if topic not in self.map_topic:
211 raise EngineException("Unknown topic {}!!!".format(topic), HTTPStatus.INTERNAL_SERVER_ERROR)
212 return self.map_topic[topic].edit(session, _id, indata, kwargs, force)
213
214 def prune(self):
215 """
216 Prune database not needed content
217 :return: None
218 """
219 return self.db.del_list("nsrs", {"_admin.to_delete": True})
220
221 def create_admin(self):
222 """
223 Creates a new user admin/admin into database if database is empty. Useful for initialization
224 :return: _id identity of the inserted data, or None
225 """
226 users = self.db.get_one("users", fail_on_empty=False, fail_on_more=False)
227 if users:
228 return None
229 # raise EngineException("Unauthorized. Database users is not empty", HTTPStatus.UNAUTHORIZED)
230 user_desc = {"username": "admin", "password": "admin", "projects": ["admin"]}
231 fake_session = {"project_id": "admin", "username": "admin", "admin": True}
232 roolback_list = []
233 _id = self.map_topic["users"].new(roolback_list, fake_session, user_desc, force=True)
234 return _id
235
236 def upgrade_db(self, current_version, target_version):
237 if not target_version or current_version == target_version:
238 return
239 if target_version == '1.0':
240 if not current_version:
241 # create database version
242 serial = urandom(32)
243 version_data = {
244 "_id": 'version', # Always 'version'
245 "version_int": 1000, # version number
246 "version": '1.0', # version text
247 "date": "2018-10-25", # version date
248 "description": "added serial", # changes in this version
249 'status': 'ENABLED', # ENABLED, DISABLED (migration in process), ERROR,
250 'serial': b64encode(serial)
251 }
252 self.db.create("admin", version_data)
253 self.db.set_secret_key(serial)
254 # TODO add future migrations here
255
256 raise EngineException("Wrong database version '{}'. Expected '{}'"
257 ". It cannot be up/down-grade".format(current_version, target_version),
258 http_code=HTTPStatus.INTERNAL_SERVER_ERROR)
259
260 def init_db(self, target_version='1.0'):
261 """
262 Init database if empty. If not empty it checks that database version and migrates if needed
263 If empty, it creates a new user admin/admin at 'users' and a new entry at 'version'
264 :param target_version: check desired database version. Migrate to it if possible or raises exception
265 :return: None if ok, exception if error or if the version is different.
266 """
267
268 version_data = self.db.get_one("admin", {"_id": "version"}, fail_on_empty=False, fail_on_more=True)
269 # check database status is ok
270 if version_data and version_data.get("status") != 'ENABLED':
271 raise EngineException("Wrong database status '{}'".format(
272 version_data["status"]), HTTPStatus.INTERNAL_SERVER_ERROR)
273
274 # check version
275 db_version = None if not version_data else version_data.get("version")
276 if db_version != target_version:
277 self.upgrade_db(db_version, target_version)
278
279 # create user admin if not exist
280 self.create_admin()
281 return