Addition of PaaS
[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
18 # import yaml
19 from osm_common import (
20 dbmongo,
21 dbmemory,
22 fslocal,
23 fsmongo,
24 msglocal,
25 msgkafka,
26 version as common_version,
27 )
28 from osm_common.dbbase import DbException
29 from osm_common.fsbase import FsException
30 from osm_common.msgbase import MsgException
31 from http import HTTPStatus
32
33 from osm_nbi.authconn_keystone import AuthconnKeystone
34 from osm_nbi.authconn_internal import AuthconnInternal
35 from osm_nbi.authconn_tacacs import AuthconnTacacs
36 from osm_nbi.base_topic import EngineException, versiontuple
37 from osm_nbi.admin_topics import VimAccountTopic, WimAccountTopic, SdnTopic
38 from osm_nbi.admin_topics import K8sClusterTopic, K8sRepoTopic, OsmRepoTopic
39 from osm_nbi.admin_topics import VcaTopic, PaasTopic
40 from osm_nbi.admin_topics import UserTopicAuth, ProjectTopicAuth, RoleTopicAuth
41 from osm_nbi.descriptor_topics import (
42 VnfdTopic,
43 NsdTopic,
44 PduTopic,
45 NstTopic,
46 VnfPkgOpTopic,
47 )
48 from osm_nbi.instance_topics import (
49 NsrTopic,
50 VnfrTopic,
51 NsLcmOpTopic,
52 NsiTopic,
53 NsiLcmOpTopic,
54 )
55 from osm_nbi.vnf_instance_topics import VnfInstances, VnfLcmOpTopic
56 from osm_nbi.pmjobs_topics import PmJobsTopic
57 from osm_nbi.subscription_topics import NslcmSubscriptionsTopic
58 from osm_nbi.osm_vnfm.vnf_subscription import VnflcmSubscriptionsTopic
59 from base64 import b64encode
60 from os import urandom # , path
61 from threading import Lock
62
63 __author__ = "Alfonso Tierno <alfonso.tiernosepulveda@telefonica.com>"
64 min_common_version = "0.1.16"
65
66
67 class Engine(object):
68 map_from_topic_to_class = {
69 "vnfds": VnfdTopic,
70 "nsds": NsdTopic,
71 "nsts": NstTopic,
72 "pdus": PduTopic,
73 "nsrs": NsrTopic,
74 "vnfrs": VnfrTopic,
75 "nslcmops": NsLcmOpTopic,
76 "vim_accounts": VimAccountTopic,
77 "wim_accounts": WimAccountTopic,
78 "sdns": SdnTopic,
79 "k8sclusters": K8sClusterTopic,
80 "vca": VcaTopic,
81 "paas": PaasTopic,
82 "k8srepos": K8sRepoTopic,
83 "osmrepos": OsmRepoTopic,
84 "users": UserTopicAuth, # Valid for both internal and keystone authentication backends
85 "projects": ProjectTopicAuth, # Valid for both internal and keystone authentication backends
86 "roles": RoleTopicAuth, # Valid for both internal and keystone authentication backends
87 "nsis": NsiTopic,
88 "nsilcmops": NsiLcmOpTopic,
89 "vnfpkgops": VnfPkgOpTopic,
90 "nslcm_subscriptions": NslcmSubscriptionsTopic,
91 "vnf_instances": VnfInstances,
92 "vnflcmops": VnfLcmOpTopic,
93 "vnflcm_subscriptions": VnflcmSubscriptionsTopic,
94 # [NEW_TOPIC]: add an entry here
95 # "pm_jobs": PmJobsTopic will be added manually because it needs other parameters
96 }
97
98 map_target_version_to_int = {
99 "1.0": 1000,
100 "1.1": 1001,
101 "1.2": 1002,
102 # Add new versions here
103 }
104
105 def __init__(self, authenticator):
106 self.db = None
107 self.fs = None
108 self.msg = None
109 self.authconn = None
110 self.config = None
111 # self.operations = None
112 self.logger = logging.getLogger("nbi.engine")
113 self.map_topic = {}
114 self.write_lock = None
115 # self.token_cache = token_cache
116 self.authenticator = authenticator
117
118 def start(self, config):
119 """
120 Connect to database, filesystem storage, and messaging
121 :param config: two level dictionary with configuration. Top level should contain 'database', 'storage',
122 :return: None
123 """
124 self.config = config
125 # check right version of common
126 if versiontuple(common_version) < versiontuple(min_common_version):
127 raise EngineException(
128 "Not compatible osm/common version '{}'. Needed '{}' or higher".format(
129 common_version, min_common_version
130 )
131 )
132
133 try:
134 if not self.db:
135 if config["database"]["driver"] == "mongo":
136 self.db = dbmongo.DbMongo()
137 self.db.db_connect(config["database"])
138 elif config["database"]["driver"] == "memory":
139 self.db = dbmemory.DbMemory()
140 self.db.db_connect(config["database"])
141 else:
142 raise EngineException(
143 "Invalid configuration param '{}' at '[database]':'driver'".format(
144 config["database"]["driver"]
145 )
146 )
147 if not self.fs:
148 if config["storage"]["driver"] == "local":
149 self.fs = fslocal.FsLocal()
150 self.fs.fs_connect(config["storage"])
151 elif config["storage"]["driver"] == "mongo":
152 self.fs = fsmongo.FsMongo()
153 self.fs.fs_connect(config["storage"])
154 else:
155 raise EngineException(
156 "Invalid configuration param '{}' at '[storage]':'driver'".format(
157 config["storage"]["driver"]
158 )
159 )
160 if not self.msg:
161 if config["message"]["driver"] == "local":
162 self.msg = msglocal.MsgLocal()
163 self.msg.connect(config["message"])
164 elif config["message"]["driver"] == "kafka":
165 self.msg = msgkafka.MsgKafka()
166 self.msg.connect(config["message"])
167 else:
168 raise EngineException(
169 "Invalid configuration param '{}' at '[message]':'driver'".format(
170 config["message"]["driver"]
171 )
172 )
173 if not self.authconn:
174 if config["authentication"]["backend"] == "keystone":
175 self.authconn = AuthconnKeystone(
176 config["authentication"],
177 self.db,
178 self.authenticator.role_permissions,
179 )
180 elif config["authentication"]["backend"] == "tacacs":
181 self.authconn = AuthconnTacacs(
182 config["authentication"],
183 self.db,
184 self.authenticator.role_permissions,
185 )
186 else:
187 self.authconn = AuthconnInternal(
188 config["authentication"],
189 self.db,
190 self.authenticator.role_permissions,
191 )
192 # if not self.operations:
193 # if "resources_to_operations" in config["rbac"]:
194 # resources_to_operations_file = config["rbac"]["resources_to_operations"]
195 # else:
196 # possible_paths = (
197 # __file__[:__file__.rfind("engine.py")] + "resources_to_operations.yml",
198 # "./resources_to_operations.yml"
199 # )
200 # for config_file in possible_paths:
201 # if path.isfile(config_file):
202 # resources_to_operations_file = config_file
203 # break
204 # if not resources_to_operations_file:
205 # raise EngineException("Invalid permission configuration:"
206 # "resources_to_operations file missing")
207 #
208 # with open(resources_to_operations_file, 'r') as f:
209 # resources_to_operations = yaml.load(f, Loader=yaml.Loader)
210 #
211 # self.operations = []
212 #
213 # for _, value in resources_to_operations["resources_to_operations"].items():
214 # if value not in self.operations:
215 # self.operations += [value]
216
217 self.write_lock = Lock()
218 # create one class per topic
219 for topic, topic_class in self.map_from_topic_to_class.items():
220 # if self.auth and topic_class in (UserTopicAuth, ProjectTopicAuth):
221 # self.map_topic[topic] = topic_class(self.db, self.fs, self.msg, self.auth)
222 self.map_topic[topic] = topic_class(
223 self.db, self.fs, self.msg, self.authconn
224 )
225
226 self.map_topic["pm_jobs"] = PmJobsTopic(
227 self.db,
228 config["prometheus"].get("host"),
229 config["prometheus"].get("port"),
230 )
231 except (DbException, FsException, MsgException) as e:
232 raise EngineException(str(e), http_code=e.http_code)
233
234 def stop(self):
235 try:
236 if self.db:
237 self.db.db_disconnect()
238 if self.fs:
239 self.fs.fs_disconnect()
240 if self.msg:
241 self.msg.disconnect()
242 self.write_lock = None
243 except (DbException, FsException, MsgException) as e:
244 raise EngineException(str(e), http_code=e.http_code)
245
246 def new_item(
247 self, rollback, session, topic, indata=None, kwargs=None, headers=None
248 ):
249 """
250 Creates a new entry into database. For nsds and vnfds it creates an almost empty DISABLED entry,
251 that must be completed with a call to method upload_content
252 :param rollback: list to append created items at database in case a rollback must to be done
253 :param session: contains the used login username and working project, force to avoid checkins, public
254 :param topic: it can be: users, projects, vim_accounts, sdns, nsrs, nsds, vnfds
255 :param indata: data to be inserted
256 :param kwargs: used to override the indata descriptor
257 :param headers: http request headers
258 :return: _id: identity of the inserted data.
259 """
260 if topic not in self.map_topic:
261 raise EngineException(
262 "Unknown topic {}!!!".format(topic), HTTPStatus.INTERNAL_SERVER_ERROR
263 )
264 with self.write_lock:
265 return self.map_topic[topic].new(rollback, session, indata, kwargs, headers)
266
267 def upload_content(self, session, topic, _id, indata, kwargs, headers):
268 """
269 Upload content for an already created entry (_id)
270 :param session: contains the used login username and working project
271 :param topic: it can be: users, projects, vnfds, nsds,
272 :param _id: server id of the item
273 :param indata: data to be inserted
274 :param kwargs: used to override the indata descriptor
275 :param headers: http request headers
276 :return: _id: identity of the inserted data.
277 """
278 if topic not in self.map_topic:
279 raise EngineException(
280 "Unknown topic {}!!!".format(topic), HTTPStatus.INTERNAL_SERVER_ERROR
281 )
282 with self.write_lock:
283 return self.map_topic[topic].upload_content(
284 session, _id, indata, kwargs, headers
285 )
286
287 def get_item_list(self, session, topic, filter_q=None, api_req=False):
288 """
289 Get a list of items
290 :param session: contains the used login username and working project
291 :param topic: it can be: users, projects, vnfds, nsds, ...
292 :param filter_q: filter of data to be applied
293 :param api_req: True if this call is serving an external API request. False if serving internal request.
294 :return: The list, it can be empty if no one match the filter_q.
295 """
296 if topic not in self.map_topic:
297 raise EngineException(
298 "Unknown topic {}!!!".format(topic), HTTPStatus.INTERNAL_SERVER_ERROR
299 )
300 return self.map_topic[topic].list(session, filter_q, api_req)
301
302 def get_item(self, session, topic, _id, filter_q=None, api_req=False):
303 """
304 Get complete information on an item
305 :param session: contains the used login username and working project
306 :param topic: it can be: users, projects, vnfds, nsds,
307 :param _id: server id of the item
308 :param filter_q: other arguments
309 :param api_req: True if this call is serving an external API request. False if serving internal request.
310 :return: dictionary, raise exception if not found.
311 """
312 if topic not in self.map_topic:
313 raise EngineException(
314 "Unknown topic {}!!!".format(topic), HTTPStatus.INTERNAL_SERVER_ERROR
315 )
316 return self.map_topic[topic].show(session, _id, filter_q, api_req)
317
318 def get_file(self, session, topic, _id, path=None, accept_header=None):
319 """
320 Get descriptor package or artifact file content
321 :param session: contains the used login username and working project
322 :param topic: it can be: users, projects, vnfds, nsds,
323 :param _id: server id of the item
324 :param path: artifact path or "$DESCRIPTOR" or None
325 :param accept_header: Content of Accept header. Must contain applition/zip or/and text/plain
326 :return: opened file plus Accept format or raises an exception
327 """
328 if topic not in self.map_topic:
329 raise EngineException(
330 "Unknown topic {}!!!".format(topic), HTTPStatus.INTERNAL_SERVER_ERROR
331 )
332 return self.map_topic[topic].get_file(session, _id, path, accept_header)
333
334 def del_item_list(self, session, topic, _filter=None):
335 """
336 Delete a list of items
337 :param session: contains the used login username and working project
338 :param topic: it can be: users, projects, vnfds, nsds, ...
339 :param _filter: filter of data to be applied
340 :return: The deleted list, it can be empty if no one match the _filter.
341 """
342 if topic not in self.map_topic:
343 raise EngineException(
344 "Unknown topic {}!!!".format(topic), HTTPStatus.INTERNAL_SERVER_ERROR
345 )
346 with self.write_lock:
347 return self.map_topic[topic].delete_list(session, _filter)
348
349 def del_item(self, session, topic, _id, not_send_msg=None):
350 """
351 Delete item by its internal id
352 :param session: contains the used login username and working project
353 :param topic: it can be: users, projects, vnfds, nsds, ...
354 :param _id: server id of the item
355 :param not_send_msg: If False, message will not be sent to kafka.
356 If a list, message is not sent, but content is stored in this variable so that the caller can send this
357 message using its own loop. If None, message is sent
358 :return: dictionary with deleted item _id. It raises exception if not found.
359 """
360 if topic not in self.map_topic:
361 raise EngineException(
362 "Unknown topic {}!!!".format(topic), HTTPStatus.INTERNAL_SERVER_ERROR
363 )
364 with self.write_lock:
365 return self.map_topic[topic].delete(session, _id, not_send_msg=not_send_msg)
366
367 def edit_item(self, session, topic, _id, indata=None, kwargs=None):
368 """
369 Update an existing entry at database
370 :param session: contains the used login username and working project
371 :param topic: it can be: users, projects, vnfds, nsds, ...
372 :param _id: identifier to be updated
373 :param indata: data to be inserted
374 :param kwargs: used to override the indata descriptor
375 :return: dictionary with edited item _id, raise exception if not found.
376 """
377 if topic not in self.map_topic:
378 raise EngineException(
379 "Unknown topic {}!!!".format(topic), HTTPStatus.INTERNAL_SERVER_ERROR
380 )
381 with self.write_lock:
382 return self.map_topic[topic].edit(session, _id, indata, kwargs)
383
384 def upgrade_db(self, current_version, target_version):
385 if target_version not in self.map_target_version_to_int.keys():
386 raise EngineException(
387 "Cannot upgrade to version '{}' with this version of code".format(
388 target_version
389 ),
390 http_code=HTTPStatus.INTERNAL_SERVER_ERROR,
391 )
392
393 if current_version == target_version:
394 return
395
396 target_version_int = self.map_target_version_to_int[target_version]
397
398 if not current_version:
399 # create database version
400 serial = urandom(32)
401 version_data = {
402 "_id": "version", # Always "version"
403 "version_int": 1000, # version number
404 "version": "1.0", # version text
405 "date": "2018-10-25", # version date
406 "description": "added serial", # changes in this version
407 "status": "ENABLED", # ENABLED, DISABLED (migration in process), ERROR,
408 "serial": b64encode(serial),
409 }
410 self.db.create("admin", version_data)
411 self.db.set_secret_key(serial)
412 current_version = "1.0"
413
414 if (
415 current_version in ("1.0", "1.1")
416 and target_version_int >= self.map_target_version_to_int["1.2"]
417 ):
418 if self.config["authentication"]["backend"] == "internal":
419 self.db.del_list("roles")
420
421 version_data = {
422 "_id": "version",
423 "version_int": 1002,
424 "version": "1.2",
425 "date": "2019-06-11",
426 "description": "set new format for roles_operations",
427 }
428
429 self.db.set_one("admin", {"_id": "version"}, version_data)
430 current_version = "1.2"
431 # TODO add future migrations here
432
433 def init_db(self, target_version="1.0"):
434 """
435 Init database if empty. If not empty it checks that database version and migrates if needed
436 If empty, it creates a new user admin/admin at 'users' and a new entry at 'version'
437 :param target_version: check desired database version. Migrate to it if possible or raises exception
438 :return: None if ok, exception if error or if the version is different.
439 """
440
441 version_data = self.db.get_one(
442 "admin", {"_id": "version"}, fail_on_empty=False, fail_on_more=True
443 )
444 # check database status is ok
445 if version_data and version_data.get("status") != "ENABLED":
446 raise EngineException(
447 "Wrong database status '{}'".format(version_data["status"]),
448 HTTPStatus.INTERNAL_SERVER_ERROR,
449 )
450
451 # check version
452 db_version = None if not version_data else version_data.get("version")
453 if db_version != target_version:
454 self.upgrade_db(db_version, target_version)
455
456 return