bug565 fixing getting file content from descriptors
[osm/NBI.git] / osm_nbi / engine.py
1 # -*- coding: utf-8 -*-
2
3 import logging
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
14 __author__ = "Alfonso Tierno <alfonso.tiernosepulveda@telefonica.com>"
15 min_common_version = "0.1.8"
16
17
18 class Engine(object):
19 map_from_topic_to_class = {
20 "vnfds": VnfdTopic,
21 "nsds": NsdTopic,
22 "pdus": PduTopic,
23 "nsrs": NsrTopic,
24 "vnfrs": VnfrTopic,
25 "nslcmops": NsLcmOpTopic,
26 "vim_accounts": VimAccountTopic,
27 "sdns": SdnTopic,
28 "users": UserTopic,
29 "projects": ProjectTopic,
30 # [NEW_TOPIC]: add an entry here
31 }
32
33 def __init__(self):
34 self.db = None
35 self.fs = None
36 self.msg = None
37 self.config = None
38 self.logger = logging.getLogger("nbi.engine")
39 self.map_topic = {}
40
41 def start(self, config):
42 """
43 Connect to database, filesystem storage, and messaging
44 :param config: two level dictionary with configuration. Top level should contain 'database', 'storage',
45 :return: None
46 """
47 self.config = config
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))
52
53 try:
54 if not self.db:
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"])
61 else:
62 raise EngineException("Invalid configuration param '{}' at '[database]':'driver'".format(
63 config["database"]["driver"]))
64 if not self.fs:
65 if config["storage"]["driver"] == "local":
66 self.fs = fslocal.FsLocal()
67 self.fs.fs_connect(config["storage"])
68 else:
69 raise EngineException("Invalid configuration param '{}' at '[storage]':'driver'".format(
70 config["storage"]["driver"]))
71 if not self.msg:
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"])
78 else:
79 raise EngineException("Invalid configuration param '{}' at '[message]':'driver'".format(
80 config["storage"]["driver"]))
81
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)
87
88 def stop(self):
89 try:
90 if self.db:
91 self.db.db_disconnect()
92 if self.fs:
93 self.fs.fs_disconnect()
94 if self.fs:
95 self.fs.fs_disconnect()
96 except (DbException, FsException, MsgException) as e:
97 raise EngineException(str(e), http_code=e.http_code)
98
99 def new_item(self, rollback, session, topic, indata=None, kwargs=None, headers=None, force=False):
100 """
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.
111 """
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)
115
116 def upload_content(self, session, topic, _id, indata, kwargs, headers, force=False):
117 """
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.
127 """
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)
131
132 def get_item_list(self, session, topic, filter_q=None):
133 """
134 Get a list of items
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.
139 """
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)
143
144 def get_item(self, session, topic, _id):
145 """
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.
151 """
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)
155
156 def get_file(self, session, topic, _id, path=None, accept_header=None):
157 """
158 Get descriptor package or artifact file content
159 :param session: contains the used login username and working project
160 :param topic: it can be: users, projects, vnfds, nsds,
161 :param _id: server id of the item
162 :param path: artifact path or "$DESCRIPTOR" or None
163 :param accept_header: Content of Accept header. Must contain applition/zip or/and text/plain
164 :return: opened file plus Accept format or raises an exception
165 """
166 if topic not in self.map_topic:
167 raise EngineException("Unknown topic {}!!!".format(topic), HTTPStatus.INTERNAL_SERVER_ERROR)
168 return self.map_topic[topic].get_file(session, _id, path, accept_header)
169
170 def del_item_list(self, session, topic, _filter=None):
171 """
172 Delete a list of items
173 :param session: contains the used login username and working project
174 :param topic: it can be: users, projects, vnfds, nsds, ...
175 :param _filter: filter of data to be applied
176 :return: The deleted list, it can be empty if no one match the _filter.
177 """
178 if topic not in self.map_topic:
179 raise EngineException("Unknown topic {}!!!".format(topic), HTTPStatus.INTERNAL_SERVER_ERROR)
180 return self.map_topic[topic].delete_list(session, _filter)
181
182 def del_item(self, session, topic, _id, force=False):
183 """
184 Delete item by its internal id
185 :param session: contains the used login username and working project
186 :param topic: it can be: users, projects, vnfds, nsds, ...
187 :param _id: server id of the item
188 :param force: indicates if deletion must be forced in case of conflict
189 :return: dictionary with deleted item _id. It raises exception if not found.
190 """
191 if topic not in self.map_topic:
192 raise EngineException("Unknown topic {}!!!".format(topic), HTTPStatus.INTERNAL_SERVER_ERROR)
193 return self.map_topic[topic].delete(session, _id, force)
194
195 def edit_item(self, session, topic, _id, indata=None, kwargs=None, force=False):
196 """
197 Update an existing entry at database
198 :param session: contains the used login username and working project
199 :param topic: it can be: users, projects, vnfds, nsds, ...
200 :param _id: identifier to be updated
201 :param indata: data to be inserted
202 :param kwargs: used to override the indata descriptor
203 :param force: If True avoid some dependence checks
204 :return: dictionary, raise exception if not found.
205 """
206 if topic not in self.map_topic:
207 raise EngineException("Unknown topic {}!!!".format(topic), HTTPStatus.INTERNAL_SERVER_ERROR)
208 return self.map_topic[topic].edit(session, _id, indata, kwargs, force)
209
210 def prune(self):
211 """
212 Prune database not needed content
213 :return: None
214 """
215 return self.db.del_list("nsrs", {"_admin.to_delete": True})
216
217 def create_admin(self):
218 """
219 Creates a new user admin/admin into database if database is empty. Useful for initialization
220 :return: _id identity of the inserted data, or None
221 """
222 users = self.db.get_one("users", fail_on_empty=False, fail_on_more=False)
223 if users:
224 return None
225 # raise EngineException("Unauthorized. Database users is not empty", HTTPStatus.UNAUTHORIZED)
226 user_desc = {"username": "admin", "password": "admin", "projects": ["admin"]}
227 fake_session = {"project_id": "admin", "username": "admin", "admin": True}
228 roolback_list = []
229 _id = self.map_topic["users"].new(roolback_list, fake_session, user_desc, force=True)
230 return _id
231
232 def init_db(self, target_version='1.0'):
233 """
234 Init database if empty. If not empty it checks that database version is ok.
235 If empty, it creates a new user admin/admin at 'users' and a new entry at 'version'
236 :return: None if ok, exception if error or if the version is different.
237 """
238 version = self.db.get_one("version", fail_on_empty=False, fail_on_more=False)
239 if not version:
240 # create user admin
241 self.create_admin()
242 # create database version
243 version_data = {
244 "_id": '1.0', # version text
245 "version": 1000, # version number
246 "date": "2018-04-12", # version date
247 "description": "initial design", # changes in this version
248 'status': 'ENABLED' # ENABLED, DISABLED (migration in process), ERROR,
249 }
250 self.db.create("version", version_data)
251 elif version["_id"] != target_version:
252 # TODO implement migration process
253 raise EngineException("Wrong database version '{}'. Expected '{}'".format(
254 version["_id"], target_version), HTTPStatus.INTERNAL_SERVER_ERROR)
255 elif version["status"] != 'ENABLED':
256 raise EngineException("Wrong database status '{}'".format(
257 version["status"]), HTTPStatus.INTERNAL_SERVER_ERROR)
258 return