blob: ab7eec007a138d942237d8ddf5b08371cf6e1992 [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
11from descriptor_topics import VnfdTopic, NsdTopic, PduTopic
12from instance_topics import NsrTopic, VnfrTopic, NsLcmOpTopic
tiernoc94c3df2018-02-09 15:38:54 +010013
14__author__ = "Alfonso Tierno <alfonso.tiernosepulveda@telefonica.com>"
tiernob24258a2018-10-04 18:39:49 +020015min_common_version = "0.1.8"
tierno441dbbf2018-07-10 12:52:48 +020016
17
tiernoc94c3df2018-02-09 15:38:54 +010018class Engine(object):
tiernob24258a2018-10-04 18:39:49 +020019 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 }
tiernoc94c3df2018-02-09 15:38:54 +010032
33 def __init__(self):
tiernoc94c3df2018-02-09 15:38:54 +010034 self.db = None
35 self.fs = None
36 self.msg = None
37 self.config = None
38 self.logger = logging.getLogger("nbi.engine")
tiernob24258a2018-10-04 18:39:49 +020039 self.map_topic = {}
tiernoc94c3df2018-02-09 15:38:54 +010040
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
tiernob24258a2018-10-04 18:39:49 +020048 # 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
tiernoc94c3df2018-02-09 15:38:54 +010053 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"]))
tiernob24258a2018-10-04 18:39:49 +020081
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)
tiernoc94c3df2018-02-09 15:38:54 +010085 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
tiernob24258a2018-10-04 18:39:49 +020099 def new_item(self, rollback, session, topic, indata=None, kwargs=None, headers=None, force=False):
tiernoc94c3df2018-02-09 15:38:54 +0100100 """
tiernof27c79b2018-03-12 17:08:42 +0100101 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
tiernob24258a2018-10-04 18:39:49 +0200103 :param rollback: list to append created items at database in case a rollback must to be done
tiernoc94c3df2018-02-09 15:38:54 +0100104 :param session: contains the used login username and working project
tiernob24258a2018-10-04 18:39:49 +0200105 :param topic: it can be: users, projects, vim_accounts, sdns, nsrs, nsds, vnfds
tiernoc94c3df2018-02-09 15:38:54 +0100106 :param indata: data to be inserted
107 :param kwargs: used to override the indata descriptor
108 :param headers: http request headers
tiernob92094f2018-05-11 13:44:22 +0200109 :param force: If True avoid some dependence checks
tierno0ffaa992018-05-09 13:21:56 +0200110 :return: _id: identity of the inserted data.
tiernoc94c3df2018-02-09 15:38:54 +0100111 """
tiernob24258a2018-10-04 18:39:49 +0200112 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)
tiernoc94c3df2018-02-09 15:38:54 +0100115
tiernob24258a2018-10-04 18:39:49 +0200116 def upload_content(self, session, topic, _id, indata, kwargs, headers, force=False):
tierno65acb4d2018-04-06 16:42:40 +0200117 """
tiernob24258a2018-10-04 18:39:49 +0200118 Upload content for an already created entry (_id)
tierno65acb4d2018-04-06 16:42:40 +0200119 :param session: contains the used login username and working project
tiernob24258a2018-10-04 18:39:49 +0200120 :param topic: it can be: users, projects, vnfds, nsds,
121 :param _id: server id of the item
122 :param indata: data to be inserted
tierno65acb4d2018-04-06 16:42:40 +0200123 :param kwargs: used to override the indata descriptor
tiernob24258a2018-10-04 18:39:49 +0200124 :param headers: http request headers
125 :param force: If True avoid some dependence checks
126 :return: _id: identity of the inserted data.
tierno65acb4d2018-04-06 16:42:40 +0200127 """
tiernob24258a2018-10-04 18:39:49 +0200128 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)
tiernoc94c3df2018-02-09 15:38:54 +0100131
tiernob24258a2018-10-04 18:39:49 +0200132 def get_item_list(self, session, topic, filter_q=None):
tiernoc94c3df2018-02-09 15:38:54 +0100133 """
134 Get a list of items
135 :param session: contains the used login username and working project
tiernob24258a2018-10-04 18:39:49 +0200136 :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.
tiernoc94c3df2018-02-09 15:38:54 +0100139 """
tiernob24258a2018-10-04 18:39:49 +0200140 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)
tiernof27c79b2018-03-12 17:08:42 +0100143
tiernob24258a2018-10-04 18:39:49 +0200144 def get_item(self, session, topic, _id):
tiernoc94c3df2018-02-09 15:38:54 +0100145 """
tiernob24258a2018-10-04 18:39:49 +0200146 Get complete information on an item
tiernoc94c3df2018-02-09 15:38:54 +0100147 :param session: contains the used login username and working project
tiernob24258a2018-10-04 18:39:49 +0200148 :param topic: it can be: users, projects, vnfds, nsds,
tiernoc94c3df2018-02-09 15:38:54 +0100149 :param _id: server id of the item
150 :return: dictionary, raise exception if not found.
151 """
tiernob24258a2018-10-04 18:39:49 +0200152 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)
tiernoc94c3df2018-02-09 15:38:54 +0100155
tiernob24258a2018-10-04 18:39:49 +0200156 def del_item_list(self, session, topic, _filter=None):
tiernoc94c3df2018-02-09 15:38:54 +0100157 """
158 Delete a list of items
159 :param session: contains the used login username and working project
tiernob24258a2018-10-04 18:39:49 +0200160 :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.
tiernoc94c3df2018-02-09 15:38:54 +0100163 """
tiernob24258a2018-10-04 18:39:49 +0200164 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)
tiernoc94c3df2018-02-09 15:38:54 +0100167
tiernob24258a2018-10-04 18:39:49 +0200168 def del_item(self, session, topic, _id, force=False):
tiernoc94c3df2018-02-09 15:38:54 +0100169 """
tiernob92094f2018-05-11 13:44:22 +0200170 Delete item by its internal id
tiernoc94c3df2018-02-09 15:38:54 +0100171 :param session: contains the used login username and working project
tiernob24258a2018-10-04 18:39:49 +0200172 :param topic: it can be: users, projects, vnfds, nsds, ...
tiernoc94c3df2018-02-09 15:38:54 +0100173 :param _id: server id of the item
tierno65acb4d2018-04-06 16:42:40 +0200174 :param force: indicates if deletion must be forced in case of conflict
tierno09c073e2018-04-26 13:36:48 +0200175 :return: dictionary with deleted item _id. It raises exception if not found.
tiernoc94c3df2018-02-09 15:38:54 +0100176 """
tiernob24258a2018-10-04 18:39:49 +0200177 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)
tiernoc94c3df2018-02-09 15:38:54 +0100180
tiernob24258a2018-10-04 18:39:49 +0200181 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)
tiernoc94c3df2018-02-09 15:38:54 +0100195
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 """
tierno4a946e42018-04-12 17:48:49 +0200205 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
tiernoc94c3df2018-02-09 15:38:54 +0100207 """
208 users = self.db.get_one("users", fail_on_empty=False, fail_on_more=False)
209 if users:
tierno4a946e42018-04-12 17:48:49 +0200210 return None
211 # raise EngineException("Unauthorized. Database users is not empty", HTTPStatus.UNAUTHORIZED)
tiernob24258a2018-10-04 18:39:49 +0200212 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)
tiernoc94c3df2018-02-09 15:38:54 +0100216 return _id
217
tierno4a946e42018-04-12 17:48:49 +0200218 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 """
tierno56ac2452018-04-17 16:06:26 +0200224 version = self.db.get_one("version", fail_on_empty=False, fail_on_more=False)
tierno4a946e42018-04-12 17:48:49 +0200225 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