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
, NsiLcmOpTopic
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 "nsilcmops": NsiLcmOpTopic
35 # [NEW_TOPIC]: add an entry here
43 self
.logger
= logging
.getLogger("nbi.engine")
46 def start(self
, config
):
48 Connect to database, filesystem storage, and messaging
49 :param config: two level dictionary with configuration. Top level should contain 'database', 'storage',
53 # check right version of common
54 if versiontuple(common_version
) < versiontuple(min_common_version
):
55 raise EngineException("Not compatible osm/common version '{}'. Needed '{}' or higher".format(
56 common_version
, min_common_version
))
60 if config
["database"]["driver"] == "mongo":
61 self
.db
= dbmongo
.DbMongo()
62 self
.db
.db_connect(config
["database"])
63 elif config
["database"]["driver"] == "memory":
64 self
.db
= dbmemory
.DbMemory()
65 self
.db
.db_connect(config
["database"])
67 raise EngineException("Invalid configuration param '{}' at '[database]':'driver'".format(
68 config
["database"]["driver"]))
70 if config
["storage"]["driver"] == "local":
71 self
.fs
= fslocal
.FsLocal()
72 self
.fs
.fs_connect(config
["storage"])
74 raise EngineException("Invalid configuration param '{}' at '[storage]':'driver'".format(
75 config
["storage"]["driver"]))
77 if config
["message"]["driver"] == "local":
78 self
.msg
= msglocal
.MsgLocal()
79 self
.msg
.connect(config
["message"])
80 elif config
["message"]["driver"] == "kafka":
81 self
.msg
= msgkafka
.MsgKafka()
82 self
.msg
.connect(config
["message"])
84 raise EngineException("Invalid configuration param '{}' at '[message]':'driver'".format(
85 config
["storage"]["driver"]))
87 # create one class per topic
88 for topic
, topic_class
in self
.map_from_topic_to_class
.items():
89 self
.map_topic
[topic
] = topic_class(self
.db
, self
.fs
, self
.msg
)
90 except (DbException
, FsException
, MsgException
) as e
:
91 raise EngineException(str(e
), http_code
=e
.http_code
)
96 self
.db
.db_disconnect()
98 self
.fs
.fs_disconnect()
100 self
.fs
.fs_disconnect()
101 except (DbException
, FsException
, MsgException
) as e
:
102 raise EngineException(str(e
), http_code
=e
.http_code
)
104 def new_item(self
, rollback
, session
, topic
, indata
=None, kwargs
=None, headers
=None, force
=False):
106 Creates a new entry into database. For nsds and vnfds it creates an almost empty DISABLED entry,
107 that must be completed with a call to method upload_content
108 :param rollback: list to append created items at database in case a rollback must to be done
109 :param session: contains the used login username and working project
110 :param topic: it can be: users, projects, vim_accounts, sdns, nsrs, nsds, vnfds
111 :param indata: data to be inserted
112 :param kwargs: used to override the indata descriptor
113 :param headers: http request headers
114 :param force: If True avoid some dependence checks
115 :return: _id: identity of the inserted data.
117 if topic
not in self
.map_topic
:
118 raise EngineException("Unknown topic {}!!!".format(topic
), HTTPStatus
.INTERNAL_SERVER_ERROR
)
119 return self
.map_topic
[topic
].new(rollback
, session
, indata
, kwargs
, headers
, force
)
121 def upload_content(self
, session
, topic
, _id
, indata
, kwargs
, headers
, force
=False):
123 Upload content for an already created entry (_id)
124 :param session: contains the used login username and working project
125 :param topic: it can be: users, projects, vnfds, nsds,
126 :param _id: server id of the item
127 :param indata: data to be inserted
128 :param kwargs: used to override the indata descriptor
129 :param headers: http request headers
130 :param force: If True avoid some dependence checks
131 :return: _id: identity of the inserted data.
133 if topic
not in self
.map_topic
:
134 raise EngineException("Unknown topic {}!!!".format(topic
), HTTPStatus
.INTERNAL_SERVER_ERROR
)
135 return self
.map_topic
[topic
].upload_content(session
, _id
, indata
, kwargs
, headers
, force
)
137 def get_item_list(self
, session
, topic
, filter_q
=None):
140 :param session: contains the used login username and working project
141 :param topic: it can be: users, projects, vnfds, nsds, ...
142 :param filter_q: filter of data to be applied
143 :return: The list, it can be empty if no one match the filter_q.
145 if topic
not in self
.map_topic
:
146 raise EngineException("Unknown topic {}!!!".format(topic
), HTTPStatus
.INTERNAL_SERVER_ERROR
)
147 return self
.map_topic
[topic
].list(session
, filter_q
)
149 def get_item(self
, session
, topic
, _id
):
151 Get complete information on an item
152 :param session: contains the used login username and working project
153 :param topic: it can be: users, projects, vnfds, nsds,
154 :param _id: server id of the item
155 :return: dictionary, raise exception if not found.
157 if topic
not in self
.map_topic
:
158 raise EngineException("Unknown topic {}!!!".format(topic
), HTTPStatus
.INTERNAL_SERVER_ERROR
)
159 return self
.map_topic
[topic
].show(session
, _id
)
161 def get_file(self
, session
, topic
, _id
, path
=None, accept_header
=None):
163 Get descriptor package or artifact file content
164 :param session: contains the used login username and working project
165 :param topic: it can be: users, projects, vnfds, nsds,
166 :param _id: server id of the item
167 :param path: artifact path or "$DESCRIPTOR" or None
168 :param accept_header: Content of Accept header. Must contain applition/zip or/and text/plain
169 :return: opened file plus Accept format or raises an exception
171 if topic
not in self
.map_topic
:
172 raise EngineException("Unknown topic {}!!!".format(topic
), HTTPStatus
.INTERNAL_SERVER_ERROR
)
173 return self
.map_topic
[topic
].get_file(session
, _id
, path
, accept_header
)
175 def del_item_list(self
, session
, topic
, _filter
=None):
177 Delete a list of items
178 :param session: contains the used login username and working project
179 :param topic: it can be: users, projects, vnfds, nsds, ...
180 :param _filter: filter of data to be applied
181 :return: The deleted list, it can be empty if no one match the _filter.
183 if topic
not in self
.map_topic
:
184 raise EngineException("Unknown topic {}!!!".format(topic
), HTTPStatus
.INTERNAL_SERVER_ERROR
)
185 return self
.map_topic
[topic
].delete_list(session
, _filter
)
187 def del_item(self
, session
, topic
, _id
, force
=False):
189 Delete item by its internal id
190 :param session: contains the used login username and working project
191 :param topic: it can be: users, projects, vnfds, nsds, ...
192 :param _id: server id of the item
193 :param force: indicates if deletion must be forced in case of conflict
194 :return: dictionary with deleted item _id. It raises exception if not found.
196 if topic
not in self
.map_topic
:
197 raise EngineException("Unknown topic {}!!!".format(topic
), HTTPStatus
.INTERNAL_SERVER_ERROR
)
198 return self
.map_topic
[topic
].delete(session
, _id
, force
)
200 def edit_item(self
, session
, topic
, _id
, indata
=None, kwargs
=None, force
=False):
202 Update an existing entry at database
203 :param session: contains the used login username and working project
204 :param topic: it can be: users, projects, vnfds, nsds, ...
205 :param _id: identifier to be updated
206 :param indata: data to be inserted
207 :param kwargs: used to override the indata descriptor
208 :param force: If True avoid some dependence checks
209 :return: dictionary, raise exception if not found.
211 if topic
not in self
.map_topic
:
212 raise EngineException("Unknown topic {}!!!".format(topic
), HTTPStatus
.INTERNAL_SERVER_ERROR
)
213 return self
.map_topic
[topic
].edit(session
, _id
, indata
, kwargs
, force
)
217 Prune database not needed content
220 return self
.db
.del_list("nsrs", {"_admin.to_delete": True})
222 def create_admin(self
):
224 Creates a new user admin/admin into database if database is empty. Useful for initialization
225 :return: _id identity of the inserted data, or None
227 users
= self
.db
.get_one("users", fail_on_empty
=False, fail_on_more
=False)
230 # raise EngineException("Unauthorized. Database users is not empty", HTTPStatus.UNAUTHORIZED)
231 user_desc
= {"username": "admin", "password": "admin", "projects": ["admin"]}
232 fake_session
= {"project_id": "admin", "username": "admin", "admin": True}
234 _id
= self
.map_topic
["users"].new(roolback_list
, fake_session
, user_desc
, force
=True)
237 def upgrade_db(self
, current_version
, target_version
):
238 if not target_version
or current_version
== target_version
:
240 if target_version
== '1.0':
241 if not current_version
:
242 # create database version
245 "_id": 'version', # Always 'version'
246 "version_int": 1000, # version number
247 "version": '1.0', # version text
248 "date": "2018-10-25", # version date
249 "description": "added serial", # changes in this version
250 'status': 'ENABLED', # ENABLED, DISABLED (migration in process), ERROR,
251 'serial': b64encode(serial
)
253 self
.db
.create("admin", version_data
)
254 self
.db
.set_secret_key(serial
)
255 # TODO add future migrations here
257 raise EngineException("Wrong database version '{}'. Expected '{}'"
258 ". It cannot be up/down-grade".format(current_version
, target_version
),
259 http_code
=HTTPStatus
.INTERNAL_SERVER_ERROR
)
261 def init_db(self
, target_version
='1.0'):
263 Init database if empty. If not empty it checks that database version and migrates if needed
264 If empty, it creates a new user admin/admin at 'users' and a new entry at 'version'
265 :param target_version: check desired database version. Migrate to it if possible or raises exception
266 :return: None if ok, exception if error or if the version is different.
269 version_data
= self
.db
.get_one("admin", {"_id": "version"}, fail_on_empty
=False, fail_on_more
=True)
270 # check database status is ok
271 if version_data
and version_data
.get("status") != 'ENABLED':
272 raise EngineException("Wrong database status '{}'".format(
273 version_data
["status"]), HTTPStatus
.INTERNAL_SERVER_ERROR
)
276 db_version
= None if not version_data
else version_data
.get("version")
277 if db_version
!= target_version
:
278 self
.upgrade_db(db_version
, target_version
)
280 # create user admin if not exist