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