1 # -*- coding: utf-8 -*-
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
13 from base64
import b64encode
14 from os
import urandom
16 __author__
= "Alfonso Tierno <alfonso.tiernosepulveda@telefonica.com>"
17 min_common_version
= "0.1.8"
21 map_from_topic_to_class
= {
28 "nslcmops": NsLcmOpTopic
,
29 "vim_accounts": VimAccountTopic
,
32 "projects": ProjectTopic
,
34 # [NEW_TOPIC]: add an entry here
42 self
.logger
= logging
.getLogger("nbi.engine")
45 def start(self
, config
):
47 Connect to database, filesystem storage, and messaging
48 :param config: two level dictionary with configuration. Top level should contain 'database', 'storage',
52 # check right version of common
53 if versiontuple(common_version
) < versiontuple(min_common_version
):
54 raise EngineException("Not compatible osm/common version '{}'. Needed '{}' or higher".format(
55 common_version
, min_common_version
))
59 if config
["database"]["driver"] == "mongo":
60 self
.db
= dbmongo
.DbMongo()
61 self
.db
.db_connect(config
["database"])
62 elif config
["database"]["driver"] == "memory":
63 self
.db
= dbmemory
.DbMemory()
64 self
.db
.db_connect(config
["database"])
66 raise EngineException("Invalid configuration param '{}' at '[database]':'driver'".format(
67 config
["database"]["driver"]))
69 if config
["storage"]["driver"] == "local":
70 self
.fs
= fslocal
.FsLocal()
71 self
.fs
.fs_connect(config
["storage"])
73 raise EngineException("Invalid configuration param '{}' at '[storage]':'driver'".format(
74 config
["storage"]["driver"]))
76 if config
["message"]["driver"] == "local":
77 self
.msg
= msglocal
.MsgLocal()
78 self
.msg
.connect(config
["message"])
79 elif config
["message"]["driver"] == "kafka":
80 self
.msg
= msgkafka
.MsgKafka()
81 self
.msg
.connect(config
["message"])
83 raise EngineException("Invalid configuration param '{}' at '[message]':'driver'".format(
84 config
["storage"]["driver"]))
86 # create one class per topic
87 for topic
, topic_class
in self
.map_from_topic_to_class
.items():
88 self
.map_topic
[topic
] = topic_class(self
.db
, self
.fs
, self
.msg
)
89 except (DbException
, FsException
, MsgException
) as e
:
90 raise EngineException(str(e
), http_code
=e
.http_code
)
95 self
.db
.db_disconnect()
97 self
.fs
.fs_disconnect()
99 self
.fs
.fs_disconnect()
100 except (DbException
, FsException
, MsgException
) as e
:
101 raise EngineException(str(e
), http_code
=e
.http_code
)
103 def new_item(self
, rollback
, session
, topic
, indata
=None, kwargs
=None, headers
=None, force
=False):
105 Creates a new entry into database. For nsds and vnfds it creates an almost empty DISABLED entry,
106 that must be completed with a call to method upload_content
107 :param rollback: list to append created items at database in case a rollback must to be done
108 :param session: contains the used login username and working project
109 :param topic: it can be: users, projects, vim_accounts, sdns, nsrs, nsds, vnfds
110 :param indata: data to be inserted
111 :param kwargs: used to override the indata descriptor
112 :param headers: http request headers
113 :param force: If True avoid some dependence checks
114 :return: _id: identity of the inserted data.
116 if topic
not in self
.map_topic
:
117 raise EngineException("Unknown topic {}!!!".format(topic
), HTTPStatus
.INTERNAL_SERVER_ERROR
)
118 return self
.map_topic
[topic
].new(rollback
, session
, indata
, kwargs
, headers
, force
)
120 def upload_content(self
, session
, topic
, _id
, indata
, kwargs
, headers
, force
=False):
122 Upload content for an already created entry (_id)
123 :param session: contains the used login username and working project
124 :param topic: it can be: users, projects, vnfds, nsds,
125 :param _id: server id of the item
126 :param indata: data to be inserted
127 :param kwargs: used to override the indata descriptor
128 :param headers: http request headers
129 :param force: If True avoid some dependence checks
130 :return: _id: identity of the inserted data.
132 if topic
not in self
.map_topic
:
133 raise EngineException("Unknown topic {}!!!".format(topic
), HTTPStatus
.INTERNAL_SERVER_ERROR
)
134 return self
.map_topic
[topic
].upload_content(session
, _id
, indata
, kwargs
, headers
, force
)
136 def get_item_list(self
, session
, topic
, filter_q
=None):
139 :param session: contains the used login username and working project
140 :param topic: it can be: users, projects, vnfds, nsds, ...
141 :param filter_q: filter of data to be applied
142 :return: The list, it can be empty if no one match the filter_q.
144 if topic
not in self
.map_topic
:
145 raise EngineException("Unknown topic {}!!!".format(topic
), HTTPStatus
.INTERNAL_SERVER_ERROR
)
146 return self
.map_topic
[topic
].list(session
, filter_q
)
148 def get_item(self
, session
, topic
, _id
):
150 Get complete information on an item
151 :param session: contains the used login username and working project
152 :param topic: it can be: users, projects, vnfds, nsds,
153 :param _id: server id of the item
154 :return: dictionary, raise exception if not found.
156 if topic
not in self
.map_topic
:
157 raise EngineException("Unknown topic {}!!!".format(topic
), HTTPStatus
.INTERNAL_SERVER_ERROR
)
158 return self
.map_topic
[topic
].show(session
, _id
)
160 def get_file(self
, session
, topic
, _id
, path
=None, accept_header
=None):
162 Get descriptor package or artifact file content
163 :param session: contains the used login username and working project
164 :param topic: it can be: users, projects, vnfds, nsds,
165 :param _id: server id of the item
166 :param path: artifact path or "$DESCRIPTOR" or None
167 :param accept_header: Content of Accept header. Must contain applition/zip or/and text/plain
168 :return: opened file plus Accept format or raises an exception
170 if topic
not in self
.map_topic
:
171 raise EngineException("Unknown topic {}!!!".format(topic
), HTTPStatus
.INTERNAL_SERVER_ERROR
)
172 return self
.map_topic
[topic
].get_file(session
, _id
, path
, accept_header
)
174 def del_item_list(self
, session
, topic
, _filter
=None):
176 Delete a list of items
177 :param session: contains the used login username and working project
178 :param topic: it can be: users, projects, vnfds, nsds, ...
179 :param _filter: filter of data to be applied
180 :return: The deleted list, it can be empty if no one match the _filter.
182 if topic
not in self
.map_topic
:
183 raise EngineException("Unknown topic {}!!!".format(topic
), HTTPStatus
.INTERNAL_SERVER_ERROR
)
184 return self
.map_topic
[topic
].delete_list(session
, _filter
)
186 def del_item(self
, session
, topic
, _id
, force
=False):
188 Delete item by its internal id
189 :param session: contains the used login username and working project
190 :param topic: it can be: users, projects, vnfds, nsds, ...
191 :param _id: server id of the item
192 :param force: indicates if deletion must be forced in case of conflict
193 :return: dictionary with deleted item _id. It raises exception if not found.
195 if topic
not in self
.map_topic
:
196 raise EngineException("Unknown topic {}!!!".format(topic
), HTTPStatus
.INTERNAL_SERVER_ERROR
)
197 return self
.map_topic
[topic
].delete(session
, _id
, force
)
199 def edit_item(self
, session
, topic
, _id
, indata
=None, kwargs
=None, force
=False):
201 Update an existing entry at database
202 :param session: contains the used login username and working project
203 :param topic: it can be: users, projects, vnfds, nsds, ...
204 :param _id: identifier to be updated
205 :param indata: data to be inserted
206 :param kwargs: used to override the indata descriptor
207 :param force: If True avoid some dependence checks
208 :return: dictionary, raise exception if not found.
210 if topic
not in self
.map_topic
:
211 raise EngineException("Unknown topic {}!!!".format(topic
), HTTPStatus
.INTERNAL_SERVER_ERROR
)
212 return self
.map_topic
[topic
].edit(session
, _id
, indata
, kwargs
, force
)
216 Prune database not needed content
219 return self
.db
.del_list("nsrs", {"_admin.to_delete": True})
221 def create_admin(self
):
223 Creates a new user admin/admin into database if database is empty. Useful for initialization
224 :return: _id identity of the inserted data, or None
226 users
= self
.db
.get_one("users", fail_on_empty
=False, fail_on_more
=False)
229 # raise EngineException("Unauthorized. Database users is not empty", HTTPStatus.UNAUTHORIZED)
230 user_desc
= {"username": "admin", "password": "admin", "projects": ["admin"]}
231 fake_session
= {"project_id": "admin", "username": "admin", "admin": True}
233 _id
= self
.map_topic
["users"].new(roolback_list
, fake_session
, user_desc
, force
=True)
236 def upgrade_db(self
, current_version
, target_version
):
237 if not target_version
or current_version
== target_version
:
239 if target_version
== '1.0':
240 if not current_version
:
241 # create database version
244 "_id": 'version', # Always 'version'
245 "version_int": 1000, # version number
246 "version": '1.0', # version text
247 "date": "2018-10-25", # version date
248 "description": "added serial", # changes in this version
249 'status': 'ENABLED', # ENABLED, DISABLED (migration in process), ERROR,
250 'serial': b64encode(serial
)
252 self
.db
.create("admin", version_data
)
253 self
.db
.set_secret_key(serial
)
254 # TODO add future migrations here
256 raise EngineException("Wrong database version '{}'. Expected '{}'"
257 ". It cannot be up/down-grade".format(current_version
, target_version
),
258 http_code
=HTTPStatus
.INTERNAL_SERVER_ERROR
)
260 def init_db(self
, target_version
='1.0'):
262 Init database if empty. If not empty it checks that database version and migrates if needed
263 If empty, it creates a new user admin/admin at 'users' and a new entry at 'version'
264 :param target_version: check desired database version. Migrate to it if possible or raises exception
265 :return: None if ok, exception if error or if the version is different.
268 version_data
= self
.db
.get_one("admin", {"_id": "version"}, fail_on_empty
=False, fail_on_more
=True)
269 # check database status is ok
270 if version_data
and version_data
.get("status") != 'ENABLED':
271 raise EngineException("Wrong database status '{}'".format(
272 version_data
["status"]), HTTPStatus
.INTERNAL_SERVER_ERROR
)
275 db_version
= None if not version_data
else version_data
.get("version")
276 if db_version
!= target_version
:
277 self
.upgrade_db(db_version
, target_version
)
279 # create user admin if not exist