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
14 __author__
= "Alfonso Tierno <alfonso.tiernosepulveda@telefonica.com>"
15 min_common_version
= "0.1.8"
19 map_from_topic_to_class
= {
25 "nslcmops": NsLcmOpTopic
,
26 "vim_accounts": VimAccountTopic
,
29 "projects": ProjectTopic
,
30 # [NEW_TOPIC]: add an entry here
38 self
.logger
= logging
.getLogger("nbi.engine")
41 def start(self
, config
):
43 Connect to database, filesystem storage, and messaging
44 :param config: two level dictionary with configuration. Top level should contain 'database', 'storage',
48 # 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
))
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"])
62 raise EngineException("Invalid configuration param '{}' at '[database]':'driver'".format(
63 config
["database"]["driver"]))
65 if config
["storage"]["driver"] == "local":
66 self
.fs
= fslocal
.FsLocal()
67 self
.fs
.fs_connect(config
["storage"])
69 raise EngineException("Invalid configuration param '{}' at '[storage]':'driver'".format(
70 config
["storage"]["driver"]))
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"])
79 raise EngineException("Invalid configuration param '{}' at '[message]':'driver'".format(
80 config
["storage"]["driver"]))
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
)
85 except (DbException
, FsException
, MsgException
) as e
:
86 raise EngineException(str(e
), http_code
=e
.http_code
)
91 self
.db
.db_disconnect()
93 self
.fs
.fs_disconnect()
95 self
.fs
.fs_disconnect()
96 except (DbException
, FsException
, MsgException
) as e
:
97 raise EngineException(str(e
), http_code
=e
.http_code
)
99 def new_item(self
, rollback
, session
, topic
, indata
=None, kwargs
=None, headers
=None, force
=False):
101 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
103 :param rollback: list to append created items at database in case a rollback must to be done
104 :param session: contains the used login username and working project
105 :param topic: it can be: users, projects, vim_accounts, sdns, nsrs, nsds, vnfds
106 :param indata: data to be inserted
107 :param kwargs: used to override the indata descriptor
108 :param headers: http request headers
109 :param force: If True avoid some dependence checks
110 :return: _id: identity of the inserted data.
112 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
)
116 def upload_content(self
, session
, topic
, _id
, indata
, kwargs
, headers
, force
=False):
118 Upload content for an already created entry (_id)
119 :param session: contains the used login username and working project
120 :param topic: it can be: users, projects, vnfds, nsds,
121 :param _id: server id of the item
122 :param indata: data to be inserted
123 :param kwargs: used to override the indata descriptor
124 :param headers: http request headers
125 :param force: If True avoid some dependence checks
126 :return: _id: identity of the inserted data.
128 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
)
132 def get_item_list(self
, session
, topic
, filter_q
=None):
135 :param session: contains the used login username and working project
136 :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.
140 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
)
144 def get_item(self
, session
, topic
, _id
):
146 Get complete information on an item
147 :param session: contains the used login username and working project
148 :param topic: it can be: users, projects, vnfds, nsds,
149 :param _id: server id of the item
150 :return: dictionary, raise exception if not found.
152 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
)
156 def del_item_list(self
, session
, topic
, _filter
=None):
158 Delete a list of items
159 :param session: contains the used login username and working project
160 :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.
164 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
)
168 def del_item(self
, session
, topic
, _id
, force
=False):
170 Delete item by its internal id
171 :param session: contains the used login username and working project
172 :param topic: it can be: users, projects, vnfds, nsds, ...
173 :param _id: server id of the item
174 :param force: indicates if deletion must be forced in case of conflict
175 :return: dictionary with deleted item _id. It raises exception if not found.
177 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
)
181 def edit_item(self
, session
, topic
, _id
, indata
=None, kwargs
=None, force
=False):
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.
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
)
198 Prune database not needed content
201 return self
.db
.del_list("nsrs", {"_admin.to_delete": True})
203 def create_admin(self
):
205 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
208 users
= self
.db
.get_one("users", fail_on_empty
=False, fail_on_more
=False)
211 # raise EngineException("Unauthorized. Database users is not empty", HTTPStatus.UNAUTHORIZED)
212 user_desc
= {"username": "admin", "password": "admin", "projects": ["admin"]}
213 fake_session
= {"project_id": "admin", "username": "admin", "admin": True}
215 _id
= self
.map_topic
["users"].new(roolback_list
, fake_session
, user_desc
, force
=True)
218 def init_db(self
, target_version
='1.0'):
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.
224 version
= self
.db
.get_one("version", fail_on_empty
=False, fail_on_more
=False)
228 # create database version
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,
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
)