Adding NSI operations (Create, Read, Delete)
[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, NsiLcmOpTopic
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 "nsilcmops": NsiLcmOpTopic
35 # [NEW_TOPIC]: add an entry here
36 }
37
38 def __init__(self):
39 self.db = None
40 self.fs = None
41 self.msg = None
42 self.config = None
43 self.logger = logging.getLogger("nbi.engine")
44 self.map_topic = {}
45
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
53 # 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
58 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"]))
86
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)
90 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
104 def new_item(self, rollback, session, topic, indata=None, kwargs=None, headers=None, force=False):
105 """
106 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
108 :param rollback: list to append created items at database in case a rollback must to be done
109 :param session: contains the used login username and working project
110 :param topic: it can be: users, projects, vim_accounts, sdns, nsrs, nsds, vnfds
111 :param indata: data to be inserted
112 :param kwargs: used to override the indata descriptor
113 :param headers: http request headers
114 :param force: If True avoid some dependence checks
115 :return: _id: identity of the inserted data.
116 """
117 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)
120
121 def upload_content(self, session, topic, _id, indata, kwargs, headers, force=False):
122 """
123 Upload content for an already created entry (_id)
124 :param session: contains the used login username and working project
125 :param topic: it can be: users, projects, vnfds, nsds,
126 :param _id: server id of the item
127 :param indata: data to be inserted
128 :param kwargs: used to override the indata descriptor
129 :param headers: http request headers
130 :param force: If True avoid some dependence checks
131 :return: _id: identity of the inserted data.
132 """
133 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)
136
137 def get_item_list(self, session, topic, filter_q=None):
138 """
139 Get a list of items
140 :param session: contains the used login username and working project
141 :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.
144 """
145 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)
148
149 def get_item(self, session, topic, _id):
150 """
151 Get complete information on an item
152 :param session: contains the used login username and working project
153 :param topic: it can be: users, projects, vnfds, nsds,
154 :param _id: server id of the item
155 :return: dictionary, raise exception if not found.
156 """
157 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)
160
161 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
175 def del_item_list(self, session, topic, _filter=None):
176 """
177 Delete a list of items
178 :param session: contains the used login username and working project
179 :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.
182 """
183 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)
186
187 def del_item(self, session, topic, _id, force=False):
188 """
189 Delete item by its internal id
190 :param session: contains the used login username and working project
191 :param topic: it can be: users, projects, vnfds, nsds, ...
192 :param _id: server id of the item
193 :param force: indicates if deletion must be forced in case of conflict
194 :return: dictionary with deleted item _id. It raises exception if not found.
195 """
196 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)
199
200 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)
214
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 """
224 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
226 """
227 users = self.db.get_one("users", fail_on_empty=False, fail_on_more=False)
228 if users:
229 return None
230 # raise EngineException("Unauthorized. Database users is not empty", HTTPStatus.UNAUTHORIZED)
231 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)
235 return _id
236
237 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
261 def init_db(self, target_version='1.0'):
262 """
263 Init database if empty. If not empty it checks that database version and migrates if needed
264 If empty, it creates a new user admin/admin at 'users' and a new entry at 'version'
265 :param target_version: check desired database version. Migrate to it if possible or raises exception
266 :return: None if ok, exception if error or if the version is different.
267 """
268
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':
272 raise EngineException("Wrong database status '{}'".format(
273 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()
282 return