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