Bug 868 - Fixed
[osm/NBI.git] / osm_nbi / engine.py
1 # -*- coding: utf-8 -*-
2
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 # http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
12 # implied.
13 # See the License for the specific language governing permissions and
14 # limitations under the License.
15
16 import logging
17 import yaml
18 from osm_common import dbmongo, dbmemory, fslocal, fsmongo, msglocal, msgkafka, version as common_version
19 from osm_common.dbbase import DbException
20 from osm_common.fsbase import FsException
21 from osm_common.msgbase import MsgException
22 from http import HTTPStatus
23
24 from osm_nbi.authconn_keystone import AuthconnKeystone
25 from osm_nbi.authconn_internal import AuthconnInternal
26 from osm_nbi.base_topic import EngineException, versiontuple
27 from osm_nbi.admin_topics import VimAccountTopic, WimAccountTopic, SdnTopic
28 from osm_nbi.admin_topics import K8sClusterTopic, K8sRepoTopic
29 from osm_nbi.admin_topics import UserTopicAuth, ProjectTopicAuth, RoleTopicAuth
30 from osm_nbi.descriptor_topics import VnfdTopic, NsdTopic, PduTopic, NstTopic
31 from osm_nbi.instance_topics import NsrTopic, VnfrTopic, NsLcmOpTopic, NsiTopic, NsiLcmOpTopic
32 from osm_nbi.pmjobs_topics import PmJobsTopic
33 from base64 import b64encode
34 from os import urandom, path
35 from threading import Lock
36
37 __author__ = "Alfonso Tierno <alfonso.tiernosepulveda@telefonica.com>"
38 min_common_version = "0.1.16"
39
40
41 class Engine(object):
42 map_from_topic_to_class = {
43 "vnfds": VnfdTopic,
44 "nsds": NsdTopic,
45 "nsts": NstTopic,
46 "pdus": PduTopic,
47 "nsrs": NsrTopic,
48 "vnfrs": VnfrTopic,
49 "nslcmops": NsLcmOpTopic,
50 "vim_accounts": VimAccountTopic,
51 "wim_accounts": WimAccountTopic,
52 "sdns": SdnTopic,
53 "k8sclusters": K8sClusterTopic,
54 "k8srepos": K8sRepoTopic,
55 "users": UserTopicAuth, # Valid for both internal and keystone authentication backends
56 "projects": ProjectTopicAuth, # Valid for both internal and keystone authentication backends
57 "roles": RoleTopicAuth, # Valid for both internal and keystone authentication backends
58 "nsis": NsiTopic,
59 "nsilcmops": NsiLcmOpTopic
60 # [NEW_TOPIC]: add an entry here
61 # "pm_jobs": PmJobsTopic will be added manually because it needs other parameters
62 }
63
64 map_target_version_to_int = {
65 "1.0": 1000,
66 "1.1": 1001,
67 "1.2": 1002,
68 # Add new versions here
69 }
70
71 def __init__(self):
72 self.db = None
73 self.fs = None
74 self.msg = None
75 self.auth = None
76 self.config = None
77 self.operations = None
78 self.logger = logging.getLogger("nbi.engine")
79 self.map_topic = {}
80 self.write_lock = None
81
82 def start(self, config):
83 """
84 Connect to database, filesystem storage, and messaging
85 :param config: two level dictionary with configuration. Top level should contain 'database', 'storage',
86 :return: None
87 """
88 self.config = config
89 # check right version of common
90 if versiontuple(common_version) < versiontuple(min_common_version):
91 raise EngineException("Not compatible osm/common version '{}'. Needed '{}' or higher".format(
92 common_version, min_common_version))
93
94 try:
95 if not self.db:
96 if config["database"]["driver"] == "mongo":
97 self.db = dbmongo.DbMongo()
98 self.db.db_connect(config["database"])
99 elif config["database"]["driver"] == "memory":
100 self.db = dbmemory.DbMemory()
101 self.db.db_connect(config["database"])
102 else:
103 raise EngineException("Invalid configuration param '{}' at '[database]':'driver'".format(
104 config["database"]["driver"]))
105 if not self.fs:
106 if config["storage"]["driver"] == "local":
107 self.fs = fslocal.FsLocal()
108 self.fs.fs_connect(config["storage"])
109 elif config["storage"]["driver"] == "mongo":
110 self.fs = fsmongo.FsMongo()
111 self.fs.fs_connect(config["storage"])
112 else:
113 raise EngineException("Invalid configuration param '{}' at '[storage]':'driver'".format(
114 config["storage"]["driver"]))
115 if not self.msg:
116 if config["message"]["driver"] == "local":
117 self.msg = msglocal.MsgLocal()
118 self.msg.connect(config["message"])
119 elif config["message"]["driver"] == "kafka":
120 self.msg = msgkafka.MsgKafka()
121 self.msg.connect(config["message"])
122 else:
123 raise EngineException("Invalid configuration param '{}' at '[message]':'driver'".format(
124 config["message"]["driver"]))
125 if not self.auth:
126 if config["authentication"]["backend"] == "keystone":
127 self.auth = AuthconnKeystone(config["authentication"], self.db, None)
128 else:
129 self.auth = AuthconnInternal(config["authentication"], self.db, dict())
130 if not self.operations:
131 if "resources_to_operations" in config["rbac"]:
132 resources_to_operations_file = config["rbac"]["resources_to_operations"]
133 else:
134 possible_paths = (
135 __file__[:__file__.rfind("engine.py")] + "resources_to_operations.yml",
136 "./resources_to_operations.yml"
137 )
138 for config_file in possible_paths:
139 if path.isfile(config_file):
140 resources_to_operations_file = config_file
141 break
142 if not resources_to_operations_file:
143 raise EngineException("Invalid permission configuration: resources_to_operations file missing")
144
145 with open(resources_to_operations_file, 'r') as f:
146 resources_to_operations = yaml.load(f, Loader=yaml.Loader)
147
148 self.operations = []
149
150 for _, value in resources_to_operations["resources_to_operations"].items():
151 if value not in self.operations:
152 self.operations += [value]
153
154 self.write_lock = Lock()
155 # create one class per topic
156 for topic, topic_class in self.map_from_topic_to_class.items():
157 # if self.auth and topic_class in (UserTopicAuth, ProjectTopicAuth):
158 # self.map_topic[topic] = topic_class(self.db, self.fs, self.msg, self.auth)
159 if self.auth and topic_class == RoleTopicAuth:
160 self.map_topic[topic] = topic_class(self.db, self.fs, self.msg, self.auth,
161 self.operations)
162 else:
163 self.map_topic[topic] = topic_class(self.db, self.fs, self.msg, self.auth)
164
165 self.map_topic["pm_jobs"] = PmJobsTopic(self.db, config["prometheus"].get("host"),
166 config["prometheus"].get("port"))
167 except (DbException, FsException, MsgException) as e:
168 raise EngineException(str(e), http_code=e.http_code)
169
170 def stop(self):
171 try:
172 if self.db:
173 self.db.db_disconnect()
174 if self.fs:
175 self.fs.fs_disconnect()
176 if self.msg:
177 self.msg.disconnect()
178 self.write_lock = None
179 except (DbException, FsException, MsgException) as e:
180 raise EngineException(str(e), http_code=e.http_code)
181
182 def new_item(self, rollback, session, topic, indata=None, kwargs=None, headers=None):
183 """
184 Creates a new entry into database. For nsds and vnfds it creates an almost empty DISABLED entry,
185 that must be completed with a call to method upload_content
186 :param rollback: list to append created items at database in case a rollback must to be done
187 :param session: contains the used login username and working project, force to avoid checkins, public
188 :param topic: it can be: users, projects, vim_accounts, sdns, nsrs, nsds, vnfds
189 :param indata: data to be inserted
190 :param kwargs: used to override the indata descriptor
191 :param headers: http request headers
192 :return: _id: identity of the inserted data.
193 """
194 if topic not in self.map_topic:
195 raise EngineException("Unknown topic {}!!!".format(topic), HTTPStatus.INTERNAL_SERVER_ERROR)
196 with self.write_lock:
197 return self.map_topic[topic].new(rollback, session, indata, kwargs, headers)
198
199 def upload_content(self, session, topic, _id, indata, kwargs, headers):
200 """
201 Upload content for an already created entry (_id)
202 :param session: contains the used login username and working project
203 :param topic: it can be: users, projects, vnfds, nsds,
204 :param _id: server id of the item
205 :param indata: data to be inserted
206 :param kwargs: used to override the indata descriptor
207 :param headers: http request headers
208 :return: _id: identity of the inserted data.
209 """
210 if topic not in self.map_topic:
211 raise EngineException("Unknown topic {}!!!".format(topic), HTTPStatus.INTERNAL_SERVER_ERROR)
212 with self.write_lock:
213 return self.map_topic[topic].upload_content(session, _id, indata, kwargs, headers)
214
215 def get_item_list(self, session, topic, filter_q=None):
216 """
217 Get a list of items
218 :param session: contains the used login username and working project
219 :param topic: it can be: users, projects, vnfds, nsds, ...
220 :param filter_q: filter of data to be applied
221 :return: The list, it can be empty if no one match the filter_q.
222 """
223 if topic not in self.map_topic:
224 raise EngineException("Unknown topic {}!!!".format(topic), HTTPStatus.INTERNAL_SERVER_ERROR)
225 return self.map_topic[topic].list(session, filter_q)
226
227 def get_item(self, session, topic, _id):
228 """
229 Get complete information on an item
230 :param session: contains the used login username and working project
231 :param topic: it can be: users, projects, vnfds, nsds,
232 :param _id: server id of the item
233 :return: dictionary, raise exception if not found.
234 """
235 if topic not in self.map_topic:
236 raise EngineException("Unknown topic {}!!!".format(topic), HTTPStatus.INTERNAL_SERVER_ERROR)
237 return self.map_topic[topic].show(session, _id)
238
239 def get_file(self, session, topic, _id, path=None, accept_header=None):
240 """
241 Get descriptor package or artifact file content
242 :param session: contains the used login username and working project
243 :param topic: it can be: users, projects, vnfds, nsds,
244 :param _id: server id of the item
245 :param path: artifact path or "$DESCRIPTOR" or None
246 :param accept_header: Content of Accept header. Must contain applition/zip or/and text/plain
247 :return: opened file plus Accept format or raises an exception
248 """
249 if topic not in self.map_topic:
250 raise EngineException("Unknown topic {}!!!".format(topic), HTTPStatus.INTERNAL_SERVER_ERROR)
251 return self.map_topic[topic].get_file(session, _id, path, accept_header)
252
253 def del_item_list(self, session, topic, _filter=None):
254 """
255 Delete a list of items
256 :param session: contains the used login username and working project
257 :param topic: it can be: users, projects, vnfds, nsds, ...
258 :param _filter: filter of data to be applied
259 :return: The deleted list, it can be empty if no one match the _filter.
260 """
261 if topic not in self.map_topic:
262 raise EngineException("Unknown topic {}!!!".format(topic), HTTPStatus.INTERNAL_SERVER_ERROR)
263 with self.write_lock:
264 return self.map_topic[topic].delete_list(session, _filter)
265
266 def del_item(self, session, topic, _id):
267 """
268 Delete item by its internal id
269 :param session: contains the used login username and working project
270 :param topic: it can be: users, projects, vnfds, nsds, ...
271 :param _id: server id of the item
272 :return: dictionary with deleted item _id. It raises exception if not found.
273 """
274 if topic not in self.map_topic:
275 raise EngineException("Unknown topic {}!!!".format(topic), HTTPStatus.INTERNAL_SERVER_ERROR)
276 with self.write_lock:
277 return self.map_topic[topic].delete(session, _id)
278
279 def edit_item(self, session, topic, _id, indata=None, kwargs=None):
280 """
281 Update an existing entry at database
282 :param session: contains the used login username and working project
283 :param topic: it can be: users, projects, vnfds, nsds, ...
284 :param _id: identifier to be updated
285 :param indata: data to be inserted
286 :param kwargs: used to override the indata descriptor
287 :return: dictionary with edited item _id, raise exception if not found.
288 """
289 if topic not in self.map_topic:
290 raise EngineException("Unknown topic {}!!!".format(topic), HTTPStatus.INTERNAL_SERVER_ERROR)
291 with self.write_lock:
292 return self.map_topic[topic].edit(session, _id, indata, kwargs)
293
294 def upgrade_db(self, current_version, target_version):
295 if target_version not in self.map_target_version_to_int.keys():
296 raise EngineException("Cannot upgrade to version '{}' with this version of code".format(target_version),
297 http_code=HTTPStatus.INTERNAL_SERVER_ERROR)
298
299 if current_version == target_version:
300 return
301
302 target_version_int = self.map_target_version_to_int[target_version]
303
304 if not current_version:
305 # create database version
306 serial = urandom(32)
307 version_data = {
308 "_id": "version", # Always "version"
309 "version_int": 1000, # version number
310 "version": "1.0", # version text
311 "date": "2018-10-25", # version date
312 "description": "added serial", # changes in this version
313 'status': "ENABLED", # ENABLED, DISABLED (migration in process), ERROR,
314 'serial': b64encode(serial)
315 }
316 self.db.create("admin", version_data)
317 self.db.set_secret_key(serial)
318 current_version = "1.0"
319
320 if current_version in ("1.0", "1.1") and target_version_int >= self.map_target_version_to_int["1.2"]:
321 if self.config['authentication']['backend'] == "internal":
322 self.db.del_list("roles")
323
324 version_data = {
325 "_id": "version",
326 "version_int": 1002,
327 "version": "1.2",
328 "date": "2019-06-11",
329 "description": "set new format for roles_operations"
330 }
331
332 self.db.set_one("admin", {"_id": "version"}, version_data)
333 current_version = "1.2"
334 # TODO add future migrations here
335
336 def init_db(self, target_version='1.0'):
337 """
338 Init database if empty. If not empty it checks that database version and migrates if needed
339 If empty, it creates a new user admin/admin at 'users' and a new entry at 'version'
340 :param target_version: check desired database version. Migrate to it if possible or raises exception
341 :return: None if ok, exception if error or if the version is different.
342 """
343
344 version_data = self.db.get_one("admin", {"_id": "version"}, fail_on_empty=False, fail_on_more=True)
345 # check database status is ok
346 if version_data and version_data.get("status") != 'ENABLED':
347 raise EngineException("Wrong database status '{}'".format(
348 version_data["status"]), HTTPStatus.INTERNAL_SERVER_ERROR)
349
350 # check version
351 db_version = None if not version_data else version_data.get("version")
352 if db_version != target_version:
353 self.upgrade_db(db_version, target_version)
354
355 return