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
12 from instance_topics
import NsrTopic
, VnfrTopic
, NsLcmOpTopic
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
= {
27 "nslcmops": NsLcmOpTopic
,
28 "vim_accounts": VimAccountTopic
,
31 "projects": ProjectTopic
,
32 # [NEW_TOPIC]: add an entry here
40 self
.logger
= logging
.getLogger("nbi.engine")
43 def start(self
, config
):
45 Connect to database, filesystem storage, and messaging
46 :param config: two level dictionary with configuration. Top level should contain 'database', 'storage',
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
))
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"])
64 raise EngineException("Invalid configuration param '{}' at '[database]':'driver'".format(
65 config
["database"]["driver"]))
67 if config
["storage"]["driver"] == "local":
68 self
.fs
= fslocal
.FsLocal()
69 self
.fs
.fs_connect(config
["storage"])
71 raise EngineException("Invalid configuration param '{}' at '[storage]':'driver'".format(
72 config
["storage"]["driver"]))
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"])
81 raise EngineException("Invalid configuration param '{}' at '[message]':'driver'".format(
82 config
["storage"]["driver"]))
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
)
93 self
.db
.db_disconnect()
95 self
.fs
.fs_disconnect()
97 self
.fs
.fs_disconnect()
98 except (DbException
, FsException
, MsgException
) as e
:
99 raise EngineException(str(e
), http_code
=e
.http_code
)
101 def new_item(self
, rollback
, session
, topic
, indata
=None, kwargs
=None, headers
=None, force
=False):
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.
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
)
118 def upload_content(self
, session
, topic
, _id
, indata
, kwargs
, headers
, force
=False):
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.
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
)
134 def get_item_list(self
, session
, topic
, filter_q
=None):
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.
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
)
146 def get_item(self
, session
, topic
, _id
):
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.
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
)
158 def get_file(self
, session
, topic
, _id
, path
=None, accept_header
=None):
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
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
)
172 def del_item_list(self
, session
, topic
, _filter
=None):
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.
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
)
184 def del_item(self
, session
, topic
, _id
, force
=False):
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.
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
)
197 def edit_item(self
, session
, topic
, _id
, indata
=None, kwargs
=None, force
=False):
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.
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
)
214 Prune database not needed content
217 return self
.db
.del_list("nsrs", {"_admin.to_delete": True})
219 def create_admin(self
):
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
224 users
= self
.db
.get_one("users", fail_on_empty
=False, fail_on_more
=False)
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}
231 _id
= self
.map_topic
["users"].new(roolback_list
, fake_session
, user_desc
, force
=True)
234 def upgrade_db(self
, current_version
, target_version
):
235 if not target_version
or current_version
== target_version
:
237 if target_version
== '1.0':
238 if not current_version
:
239 # create database version
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
)
250 self
.db
.create("admin", version_data
)
251 self
.db
.set_secret_key(serial
)
252 # TODO add future migrations here
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
)
258 def init_db(self
, target_version
='1.0'):
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.
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
)
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
)
277 # create user admin if not exist