blob: 38cc08e0b327600f062a06e7f180a4de404a2d57 [file] [log] [blame]
tiernoc94c3df2018-02-09 15:38:54 +01001# -*- coding: utf-8 -*-
2
tiernod125caf2018-11-22 16:05:54 +00003# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7# http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
12# implied.
13# See the License for the specific language governing permissions and
14# limitations under the License.
15
tiernoc94c3df2018-02-09 15:38:54 +010016import logging
tiernob24258a2018-10-04 18:39:49 +020017from osm_common import dbmongo, dbmemory, fslocal, msglocal, msgkafka, version as common_version
18from osm_common.dbbase import DbException
tiernoa8d63632018-05-10 13:12:32 +020019from osm_common.fsbase import FsException
20from osm_common.msgbase import MsgException
tiernoc94c3df2018-02-09 15:38:54 +010021from http import HTTPStatus
tiernob24258a2018-10-04 18:39:49 +020022from base_topic import EngineException, versiontuple
tierno55ba2e62018-12-11 17:22:22 +000023from admin_topics import UserTopic, ProjectTopic, VimAccountTopic, WimAccountTopic, SdnTopic
Felipe Vicensb57758d2018-10-16 16:00:20 +020024from descriptor_topics import VnfdTopic, NsdTopic, PduTopic, NstTopic
Felipe Vicens07f31722018-10-29 15:16:44 +010025from instance_topics import NsrTopic, VnfrTopic, NsLcmOpTopic, NsiTopic, NsiLcmOpTopic
tiernod985a8d2018-10-19 14:12:28 +020026from base64 import b64encode
27from os import urandom
tiernoc94c3df2018-02-09 15:38:54 +010028
29__author__ = "Alfonso Tierno <alfonso.tiernosepulveda@telefonica.com>"
tiernob24258a2018-10-04 18:39:49 +020030min_common_version = "0.1.8"
tierno441dbbf2018-07-10 12:52:48 +020031
32
tiernoc94c3df2018-02-09 15:38:54 +010033class Engine(object):
tiernob24258a2018-10-04 18:39:49 +020034 map_from_topic_to_class = {
35 "vnfds": VnfdTopic,
36 "nsds": NsdTopic,
Felipe Vicensb57758d2018-10-16 16:00:20 +020037 "nsts": NstTopic,
tiernob24258a2018-10-04 18:39:49 +020038 "pdus": PduTopic,
39 "nsrs": NsrTopic,
40 "vnfrs": VnfrTopic,
41 "nslcmops": NsLcmOpTopic,
42 "vim_accounts": VimAccountTopic,
tierno55ba2e62018-12-11 17:22:22 +000043 "wim_accounts": WimAccountTopic,
tiernob24258a2018-10-04 18:39:49 +020044 "sdns": SdnTopic,
45 "users": UserTopic,
46 "projects": ProjectTopic,
Felipe Vicensb57758d2018-10-16 16:00:20 +020047 "nsis": NsiTopic,
Felipe Vicens07f31722018-10-29 15:16:44 +010048 "nsilcmops": NsiLcmOpTopic
tiernob24258a2018-10-04 18:39:49 +020049 # [NEW_TOPIC]: add an entry here
50 }
tiernoc94c3df2018-02-09 15:38:54 +010051
52 def __init__(self):
tiernoc94c3df2018-02-09 15:38:54 +010053 self.db = None
54 self.fs = None
55 self.msg = None
56 self.config = None
57 self.logger = logging.getLogger("nbi.engine")
tiernob24258a2018-10-04 18:39:49 +020058 self.map_topic = {}
tiernoc94c3df2018-02-09 15:38:54 +010059
60 def start(self, config):
61 """
62 Connect to database, filesystem storage, and messaging
63 :param config: two level dictionary with configuration. Top level should contain 'database', 'storage',
64 :return: None
65 """
66 self.config = config
tiernob24258a2018-10-04 18:39:49 +020067 # check right version of common
68 if versiontuple(common_version) < versiontuple(min_common_version):
69 raise EngineException("Not compatible osm/common version '{}'. Needed '{}' or higher".format(
70 common_version, min_common_version))
71
tiernoc94c3df2018-02-09 15:38:54 +010072 try:
73 if not self.db:
74 if config["database"]["driver"] == "mongo":
75 self.db = dbmongo.DbMongo()
76 self.db.db_connect(config["database"])
77 elif config["database"]["driver"] == "memory":
78 self.db = dbmemory.DbMemory()
79 self.db.db_connect(config["database"])
80 else:
81 raise EngineException("Invalid configuration param '{}' at '[database]':'driver'".format(
82 config["database"]["driver"]))
83 if not self.fs:
84 if config["storage"]["driver"] == "local":
85 self.fs = fslocal.FsLocal()
86 self.fs.fs_connect(config["storage"])
87 else:
88 raise EngineException("Invalid configuration param '{}' at '[storage]':'driver'".format(
89 config["storage"]["driver"]))
90 if not self.msg:
91 if config["message"]["driver"] == "local":
92 self.msg = msglocal.MsgLocal()
93 self.msg.connect(config["message"])
94 elif config["message"]["driver"] == "kafka":
95 self.msg = msgkafka.MsgKafka()
96 self.msg.connect(config["message"])
97 else:
98 raise EngineException("Invalid configuration param '{}' at '[message]':'driver'".format(
99 config["storage"]["driver"]))
tiernob24258a2018-10-04 18:39:49 +0200100
101 # create one class per topic
102 for topic, topic_class in self.map_from_topic_to_class.items():
103 self.map_topic[topic] = topic_class(self.db, self.fs, self.msg)
tiernoc94c3df2018-02-09 15:38:54 +0100104 except (DbException, FsException, MsgException) as e:
105 raise EngineException(str(e), http_code=e.http_code)
106
107 def stop(self):
108 try:
109 if self.db:
110 self.db.db_disconnect()
111 if self.fs:
112 self.fs.fs_disconnect()
113 if self.fs:
114 self.fs.fs_disconnect()
115 except (DbException, FsException, MsgException) as e:
116 raise EngineException(str(e), http_code=e.http_code)
117
tiernob24258a2018-10-04 18:39:49 +0200118 def new_item(self, rollback, session, topic, indata=None, kwargs=None, headers=None, force=False):
tiernoc94c3df2018-02-09 15:38:54 +0100119 """
tiernof27c79b2018-03-12 17:08:42 +0100120 Creates a new entry into database. For nsds and vnfds it creates an almost empty DISABLED entry,
121 that must be completed with a call to method upload_content
tiernob24258a2018-10-04 18:39:49 +0200122 :param rollback: list to append created items at database in case a rollback must to be done
tiernoc94c3df2018-02-09 15:38:54 +0100123 :param session: contains the used login username and working project
tiernob24258a2018-10-04 18:39:49 +0200124 :param topic: it can be: users, projects, vim_accounts, sdns, nsrs, nsds, vnfds
tiernoc94c3df2018-02-09 15:38:54 +0100125 :param indata: data to be inserted
126 :param kwargs: used to override the indata descriptor
127 :param headers: http request headers
tiernob92094f2018-05-11 13:44:22 +0200128 :param force: If True avoid some dependence checks
tierno0ffaa992018-05-09 13:21:56 +0200129 :return: _id: identity of the inserted data.
tiernoc94c3df2018-02-09 15:38:54 +0100130 """
tiernob24258a2018-10-04 18:39:49 +0200131 if topic not in self.map_topic:
132 raise EngineException("Unknown topic {}!!!".format(topic), HTTPStatus.INTERNAL_SERVER_ERROR)
133 return self.map_topic[topic].new(rollback, session, indata, kwargs, headers, force)
tiernoc94c3df2018-02-09 15:38:54 +0100134
tiernob24258a2018-10-04 18:39:49 +0200135 def upload_content(self, session, topic, _id, indata, kwargs, headers, force=False):
tierno65acb4d2018-04-06 16:42:40 +0200136 """
tiernob24258a2018-10-04 18:39:49 +0200137 Upload content for an already created entry (_id)
tierno65acb4d2018-04-06 16:42:40 +0200138 :param session: contains the used login username and working project
tiernob24258a2018-10-04 18:39:49 +0200139 :param topic: it can be: users, projects, vnfds, nsds,
140 :param _id: server id of the item
141 :param indata: data to be inserted
tierno65acb4d2018-04-06 16:42:40 +0200142 :param kwargs: used to override the indata descriptor
tiernob24258a2018-10-04 18:39:49 +0200143 :param headers: http request headers
144 :param force: If True avoid some dependence checks
145 :return: _id: identity of the inserted data.
tierno65acb4d2018-04-06 16:42:40 +0200146 """
tiernob24258a2018-10-04 18:39:49 +0200147 if topic not in self.map_topic:
148 raise EngineException("Unknown topic {}!!!".format(topic), HTTPStatus.INTERNAL_SERVER_ERROR)
149 return self.map_topic[topic].upload_content(session, _id, indata, kwargs, headers, force)
tiernoc94c3df2018-02-09 15:38:54 +0100150
tiernob24258a2018-10-04 18:39:49 +0200151 def get_item_list(self, session, topic, filter_q=None):
tiernoc94c3df2018-02-09 15:38:54 +0100152 """
153 Get a list of items
154 :param session: contains the used login username and working project
tiernob24258a2018-10-04 18:39:49 +0200155 :param topic: it can be: users, projects, vnfds, nsds, ...
156 :param filter_q: filter of data to be applied
157 :return: The list, it can be empty if no one match the filter_q.
tiernoc94c3df2018-02-09 15:38:54 +0100158 """
tiernob24258a2018-10-04 18:39:49 +0200159 if topic not in self.map_topic:
160 raise EngineException("Unknown topic {}!!!".format(topic), HTTPStatus.INTERNAL_SERVER_ERROR)
161 return self.map_topic[topic].list(session, filter_q)
tiernof27c79b2018-03-12 17:08:42 +0100162
tiernob24258a2018-10-04 18:39:49 +0200163 def get_item(self, session, topic, _id):
tiernoc94c3df2018-02-09 15:38:54 +0100164 """
tiernob24258a2018-10-04 18:39:49 +0200165 Get complete information on an item
tiernoc94c3df2018-02-09 15:38:54 +0100166 :param session: contains the used login username and working project
tiernob24258a2018-10-04 18:39:49 +0200167 :param topic: it can be: users, projects, vnfds, nsds,
tiernoc94c3df2018-02-09 15:38:54 +0100168 :param _id: server id of the item
169 :return: dictionary, raise exception if not found.
170 """
tiernob24258a2018-10-04 18:39:49 +0200171 if topic not in self.map_topic:
172 raise EngineException("Unknown topic {}!!!".format(topic), HTTPStatus.INTERNAL_SERVER_ERROR)
173 return self.map_topic[topic].show(session, _id)
tiernoc94c3df2018-02-09 15:38:54 +0100174
tierno87006042018-10-24 12:50:20 +0200175 def get_file(self, session, topic, _id, path=None, accept_header=None):
176 """
177 Get descriptor package or artifact file content
178 :param session: contains the used login username and working project
179 :param topic: it can be: users, projects, vnfds, nsds,
180 :param _id: server id of the item
181 :param path: artifact path or "$DESCRIPTOR" or None
182 :param accept_header: Content of Accept header. Must contain applition/zip or/and text/plain
183 :return: opened file plus Accept format or raises an exception
184 """
185 if topic not in self.map_topic:
186 raise EngineException("Unknown topic {}!!!".format(topic), HTTPStatus.INTERNAL_SERVER_ERROR)
187 return self.map_topic[topic].get_file(session, _id, path, accept_header)
188
tiernob24258a2018-10-04 18:39:49 +0200189 def del_item_list(self, session, topic, _filter=None):
tiernoc94c3df2018-02-09 15:38:54 +0100190 """
191 Delete a list of items
192 :param session: contains the used login username and working project
tiernob24258a2018-10-04 18:39:49 +0200193 :param topic: it can be: users, projects, vnfds, nsds, ...
194 :param _filter: filter of data to be applied
195 :return: The deleted list, it can be empty if no one match the _filter.
tiernoc94c3df2018-02-09 15:38:54 +0100196 """
tiernob24258a2018-10-04 18:39:49 +0200197 if topic not in self.map_topic:
198 raise EngineException("Unknown topic {}!!!".format(topic), HTTPStatus.INTERNAL_SERVER_ERROR)
199 return self.map_topic[topic].delete_list(session, _filter)
tiernoc94c3df2018-02-09 15:38:54 +0100200
tiernob24258a2018-10-04 18:39:49 +0200201 def del_item(self, session, topic, _id, force=False):
tiernoc94c3df2018-02-09 15:38:54 +0100202 """
tiernob92094f2018-05-11 13:44:22 +0200203 Delete item by its internal id
tiernoc94c3df2018-02-09 15:38:54 +0100204 :param session: contains the used login username and working project
tiernob24258a2018-10-04 18:39:49 +0200205 :param topic: it can be: users, projects, vnfds, nsds, ...
tiernoc94c3df2018-02-09 15:38:54 +0100206 :param _id: server id of the item
tierno65acb4d2018-04-06 16:42:40 +0200207 :param force: indicates if deletion must be forced in case of conflict
tierno09c073e2018-04-26 13:36:48 +0200208 :return: dictionary with deleted item _id. It raises exception if not found.
tiernoc94c3df2018-02-09 15:38:54 +0100209 """
tiernob24258a2018-10-04 18:39:49 +0200210 if topic not in self.map_topic:
211 raise EngineException("Unknown topic {}!!!".format(topic), HTTPStatus.INTERNAL_SERVER_ERROR)
212 return self.map_topic[topic].delete(session, _id, force)
tiernoc94c3df2018-02-09 15:38:54 +0100213
tiernob24258a2018-10-04 18:39:49 +0200214 def edit_item(self, session, topic, _id, indata=None, kwargs=None, force=False):
215 """
216 Update an existing entry at database
217 :param session: contains the used login username and working project
218 :param topic: it can be: users, projects, vnfds, nsds, ...
219 :param _id: identifier to be updated
220 :param indata: data to be inserted
221 :param kwargs: used to override the indata descriptor
222 :param force: If True avoid some dependence checks
223 :return: dictionary, raise exception if not found.
224 """
225 if topic not in self.map_topic:
226 raise EngineException("Unknown topic {}!!!".format(topic), HTTPStatus.INTERNAL_SERVER_ERROR)
227 return self.map_topic[topic].edit(session, _id, indata, kwargs, force)
tiernoc94c3df2018-02-09 15:38:54 +0100228
tiernoc94c3df2018-02-09 15:38:54 +0100229 def create_admin(self):
230 """
tierno4a946e42018-04-12 17:48:49 +0200231 Creates a new user admin/admin into database if database is empty. Useful for initialization
232 :return: _id identity of the inserted data, or None
tiernoc94c3df2018-02-09 15:38:54 +0100233 """
234 users = self.db.get_one("users", fail_on_empty=False, fail_on_more=False)
235 if users:
tierno4a946e42018-04-12 17:48:49 +0200236 return None
237 # raise EngineException("Unauthorized. Database users is not empty", HTTPStatus.UNAUTHORIZED)
tiernob24258a2018-10-04 18:39:49 +0200238 user_desc = {"username": "admin", "password": "admin", "projects": ["admin"]}
239 fake_session = {"project_id": "admin", "username": "admin", "admin": True}
240 roolback_list = []
241 _id = self.map_topic["users"].new(roolback_list, fake_session, user_desc, force=True)
tiernoc94c3df2018-02-09 15:38:54 +0100242 return _id
243
tiernod985a8d2018-10-19 14:12:28 +0200244 def upgrade_db(self, current_version, target_version):
245 if not target_version or current_version == target_version:
246 return
247 if target_version == '1.0':
248 if not current_version:
249 # create database version
250 serial = urandom(32)
251 version_data = {
252 "_id": 'version', # Always 'version'
253 "version_int": 1000, # version number
254 "version": '1.0', # version text
255 "date": "2018-10-25", # version date
256 "description": "added serial", # changes in this version
257 'status': 'ENABLED', # ENABLED, DISABLED (migration in process), ERROR,
258 'serial': b64encode(serial)
259 }
260 self.db.create("admin", version_data)
261 self.db.set_secret_key(serial)
262 # TODO add future migrations here
263
264 raise EngineException("Wrong database version '{}'. Expected '{}'"
265 ". It cannot be up/down-grade".format(current_version, target_version),
266 http_code=HTTPStatus.INTERNAL_SERVER_ERROR)
267
tierno4a946e42018-04-12 17:48:49 +0200268 def init_db(self, target_version='1.0'):
269 """
tiernod985a8d2018-10-19 14:12:28 +0200270 Init database if empty. If not empty it checks that database version and migrates if needed
tierno4a946e42018-04-12 17:48:49 +0200271 If empty, it creates a new user admin/admin at 'users' and a new entry at 'version'
tiernod985a8d2018-10-19 14:12:28 +0200272 :param target_version: check desired database version. Migrate to it if possible or raises exception
tierno4a946e42018-04-12 17:48:49 +0200273 :return: None if ok, exception if error or if the version is different.
274 """
tiernod985a8d2018-10-19 14:12:28 +0200275
276 version_data = self.db.get_one("admin", {"_id": "version"}, fail_on_empty=False, fail_on_more=True)
277 # check database status is ok
278 if version_data and version_data.get("status") != 'ENABLED':
tierno4a946e42018-04-12 17:48:49 +0200279 raise EngineException("Wrong database status '{}'".format(
tiernod985a8d2018-10-19 14:12:28 +0200280 version_data["status"]), HTTPStatus.INTERNAL_SERVER_ERROR)
281
282 # check version
283 db_version = None if not version_data else version_data.get("version")
284 if db_version != target_version:
285 self.upgrade_db(db_version, target_version)
286
287 # create user admin if not exist
288 self.create_admin()
tierno4a946e42018-04-12 17:48:49 +0200289 return