blob: 02b3e1458cd12c4c1355fca4f79c37fabae5f893 [file] [log] [blame]
tiernoc94c3df2018-02-09 15:38:54 +01001# -*- coding: utf-8 -*-
2
tiernod125caf2018-11-22 16:05:54 +00003# 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
tiernoc94c3df2018-02-09 15:38:54 +010016import logging
garciadeblas4568a372021-03-24 09:19:48 +010017
tierno9e87a7f2020-03-23 09:24:10 +000018# import yaml
garciadeblas4568a372021-03-24 09:19:48 +010019from osm_common import (
20 dbmongo,
21 dbmemory,
22 fslocal,
23 fsmongo,
24 msglocal,
25 msgkafka,
26 version as common_version,
27)
tiernob24258a2018-10-04 18:39:49 +020028from osm_common.dbbase import DbException
tiernoa8d63632018-05-10 13:12:32 +020029from osm_common.fsbase import FsException
30from osm_common.msgbase import MsgException
tiernoc94c3df2018-02-09 15:38:54 +010031from http import HTTPStatus
Eduardo Sousa5c01e192019-05-08 02:35:47 +010032
tierno23acf402019-08-28 13:36:34 +000033from osm_nbi.authconn_keystone import AuthconnKeystone
34from osm_nbi.authconn_internal import AuthconnInternal
K Sai Kiran7ddb0732020-10-30 11:14:44 +053035from osm_nbi.authconn_tacacs import AuthconnTacacs
tierno23acf402019-08-28 13:36:34 +000036from osm_nbi.base_topic import EngineException, versiontuple
37from osm_nbi.admin_topics import VimAccountTopic, WimAccountTopic, SdnTopic
Felipe Vicensb66b0412020-05-06 10:11:00 +020038from osm_nbi.admin_topics import K8sClusterTopic, K8sRepoTopic, OsmRepoTopic
David Garciaecb41322021-03-31 19:10:46 +020039from osm_nbi.admin_topics import VcaTopic
tierno23acf402019-08-28 13:36:34 +000040from osm_nbi.admin_topics import UserTopicAuth, ProjectTopicAuth, RoleTopicAuth
garciadeblas4568a372021-03-24 09:19:48 +010041from osm_nbi.descriptor_topics import (
42 VnfdTopic,
43 NsdTopic,
44 PduTopic,
45 NstTopic,
46 VnfPkgOpTopic,
kayal2001f71c2e82024-06-25 15:26:24 +053047 NsConfigTemplateTopic,
garciadeblas4568a372021-03-24 09:19:48 +010048)
49from osm_nbi.instance_topics import (
50 NsrTopic,
51 VnfrTopic,
52 NsLcmOpTopic,
53 NsiTopic,
54 NsiLcmOpTopic,
55)
rshri2d386cb2024-07-05 14:35:51 +000056from osm_nbi.k8s_topics import (
57 K8sTopic,
58 InfraContTopic,
59 InfraConfTopic,
60 AppTopic,
61 ResourceTopic,
62 K8saddTopic,
yshah53cc9eb2024-07-05 13:06:31 +000063 KsusTopic,
64 OkaTopic,
rshri2d386cb2024-07-05 14:35:51 +000065)
almagiae47b9132022-05-17 14:12:22 +020066from osm_nbi.vnf_instance_topics import VnfInstances, VnfLcmOpTopic
tierno23acf402019-08-28 13:36:34 +000067from osm_nbi.pmjobs_topics import PmJobsTopic
preethika.p329b8182020-04-22 12:25:39 +053068from osm_nbi.subscription_topics import NslcmSubscriptionsTopic
selvi.jf1004592022-04-29 05:42:35 +000069from osm_nbi.osm_vnfm.vnf_subscription import VnflcmSubscriptionsTopic
tiernod985a8d2018-10-19 14:12:28 +020070from base64 import b64encode
garciadeblas4568a372021-03-24 09:19:48 +010071from os import urandom # , path
tierno04dbb0e2019-01-09 16:00:24 +000072from threading import Lock
tiernoc94c3df2018-02-09 15:38:54 +010073
74__author__ = "Alfonso Tierno <alfonso.tiernosepulveda@telefonica.com>"
tierno932499c2019-01-28 17:28:10 +000075min_common_version = "0.1.16"
tierno441dbbf2018-07-10 12:52:48 +020076
77
tiernoc94c3df2018-02-09 15:38:54 +010078class Engine(object):
tiernob24258a2018-10-04 18:39:49 +020079 map_from_topic_to_class = {
80 "vnfds": VnfdTopic,
81 "nsds": NsdTopic,
Felipe Vicensb57758d2018-10-16 16:00:20 +020082 "nsts": NstTopic,
tiernob24258a2018-10-04 18:39:49 +020083 "pdus": PduTopic,
84 "nsrs": NsrTopic,
85 "vnfrs": VnfrTopic,
86 "nslcmops": NsLcmOpTopic,
87 "vim_accounts": VimAccountTopic,
tierno55ba2e62018-12-11 17:22:22 +000088 "wim_accounts": WimAccountTopic,
tiernob24258a2018-10-04 18:39:49 +020089 "sdns": SdnTopic,
delacruzramofe598fe2019-10-23 18:25:11 +020090 "k8sclusters": K8sClusterTopic,
David Garciaecb41322021-03-31 19:10:46 +020091 "vca": VcaTopic,
delacruzramofe598fe2019-10-23 18:25:11 +020092 "k8srepos": K8sRepoTopic,
Felipe Vicensb66b0412020-05-06 10:11:00 +020093 "osmrepos": OsmRepoTopic,
garciadeblas4568a372021-03-24 09:19:48 +010094 "users": UserTopicAuth, # Valid for both internal and keystone authentication backends
95 "projects": ProjectTopicAuth, # Valid for both internal and keystone authentication backends
96 "roles": RoleTopicAuth, # Valid for both internal and keystone authentication backends
Felipe Vicensb57758d2018-10-16 16:00:20 +020097 "nsis": NsiTopic,
delacruzramo271d2002019-12-02 21:00:37 +010098 "nsilcmops": NsiLcmOpTopic,
99 "vnfpkgops": VnfPkgOpTopic,
preethika.p329b8182020-04-22 12:25:39 +0530100 "nslcm_subscriptions": NslcmSubscriptionsTopic,
almagiae47b9132022-05-17 14:12:22 +0200101 "vnf_instances": VnfInstances,
102 "vnflcmops": VnfLcmOpTopic,
selvi.jf1004592022-04-29 05:42:35 +0000103 "vnflcm_subscriptions": VnflcmSubscriptionsTopic,
kayal2001f71c2e82024-06-25 15:26:24 +0530104 "nsconfigtemps": NsConfigTemplateTopic,
rshri2d386cb2024-07-05 14:35:51 +0000105 "k8s": K8sTopic,
106 "infras_cont": InfraContTopic,
107 "infras_conf": InfraConfTopic,
108 "apps": AppTopic,
109 "resources": ResourceTopic,
110 "k8sops": K8saddTopic,
yshah53cc9eb2024-07-05 13:06:31 +0000111 "ksus": KsusTopic,
112 "oka_packages": OkaTopic,
tiernob24258a2018-10-04 18:39:49 +0200113 # [NEW_TOPIC]: add an entry here
vijay.r35ef2f72019-04-30 17:55:49 +0530114 # "pm_jobs": PmJobsTopic will be added manually because it needs other parameters
tiernob24258a2018-10-04 18:39:49 +0200115 }
tiernoc94c3df2018-02-09 15:38:54 +0100116
Eduardo Sousa044f4312019-05-20 15:17:35 +0100117 map_target_version_to_int = {
118 "1.0": 1000,
tierno1f029d82019-06-13 22:37:04 +0000119 "1.1": 1001,
120 "1.2": 1002,
Eduardo Sousa044f4312019-05-20 15:17:35 +0100121 # Add new versions here
122 }
123
delacruzramoad682a52019-12-10 16:26:34 +0100124 def __init__(self, authenticator):
tiernoc94c3df2018-02-09 15:38:54 +0100125 self.db = None
126 self.fs = None
127 self.msg = None
delacruzramoad682a52019-12-10 16:26:34 +0100128 self.authconn = None
tiernoc94c3df2018-02-09 15:38:54 +0100129 self.config = None
tierno9e87a7f2020-03-23 09:24:10 +0000130 # self.operations = None
tiernoc94c3df2018-02-09 15:38:54 +0100131 self.logger = logging.getLogger("nbi.engine")
tiernob24258a2018-10-04 18:39:49 +0200132 self.map_topic = {}
tierno04dbb0e2019-01-09 16:00:24 +0000133 self.write_lock = None
delacruzramoad682a52019-12-10 16:26:34 +0100134 # self.token_cache = token_cache
135 self.authenticator = authenticator
tiernoc94c3df2018-02-09 15:38:54 +0100136
137 def start(self, config):
138 """
139 Connect to database, filesystem storage, and messaging
140 :param config: two level dictionary with configuration. Top level should contain 'database', 'storage',
141 :return: None
142 """
143 self.config = config
tiernob24258a2018-10-04 18:39:49 +0200144 # check right version of common
145 if versiontuple(common_version) < versiontuple(min_common_version):
garciadeblas4568a372021-03-24 09:19:48 +0100146 raise EngineException(
147 "Not compatible osm/common version '{}'. Needed '{}' or higher".format(
148 common_version, min_common_version
149 )
150 )
tiernob24258a2018-10-04 18:39:49 +0200151
tiernoc94c3df2018-02-09 15:38:54 +0100152 try:
153 if not self.db:
154 if config["database"]["driver"] == "mongo":
155 self.db = dbmongo.DbMongo()
156 self.db.db_connect(config["database"])
157 elif config["database"]["driver"] == "memory":
158 self.db = dbmemory.DbMemory()
159 self.db.db_connect(config["database"])
160 else:
garciadeblas4568a372021-03-24 09:19:48 +0100161 raise EngineException(
162 "Invalid configuration param '{}' at '[database]':'driver'".format(
163 config["database"]["driver"]
164 )
165 )
tiernoc94c3df2018-02-09 15:38:54 +0100166 if not self.fs:
167 if config["storage"]["driver"] == "local":
168 self.fs = fslocal.FsLocal()
169 self.fs.fs_connect(config["storage"])
Eduardo Sousa7e0eb132019-06-21 11:50:21 +0100170 elif config["storage"]["driver"] == "mongo":
171 self.fs = fsmongo.FsMongo()
172 self.fs.fs_connect(config["storage"])
tiernoc94c3df2018-02-09 15:38:54 +0100173 else:
garciadeblas4568a372021-03-24 09:19:48 +0100174 raise EngineException(
175 "Invalid configuration param '{}' at '[storage]':'driver'".format(
176 config["storage"]["driver"]
177 )
178 )
tiernoc94c3df2018-02-09 15:38:54 +0100179 if not self.msg:
180 if config["message"]["driver"] == "local":
181 self.msg = msglocal.MsgLocal()
182 self.msg.connect(config["message"])
183 elif config["message"]["driver"] == "kafka":
184 self.msg = msgkafka.MsgKafka()
185 self.msg.connect(config["message"])
186 else:
garciadeblas4568a372021-03-24 09:19:48 +0100187 raise EngineException(
188 "Invalid configuration param '{}' at '[message]':'driver'".format(
189 config["message"]["driver"]
190 )
191 )
delacruzramoad682a52019-12-10 16:26:34 +0100192 if not self.authconn:
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100193 if config["authentication"]["backend"] == "keystone":
garciadeblas4568a372021-03-24 09:19:48 +0100194 self.authconn = AuthconnKeystone(
195 config["authentication"],
196 self.db,
197 self.authenticator.role_permissions,
198 )
K Sai Kiran7ddb0732020-10-30 11:14:44 +0530199 elif config["authentication"]["backend"] == "tacacs":
garciadeblas4568a372021-03-24 09:19:48 +0100200 self.authconn = AuthconnTacacs(
201 config["authentication"],
202 self.db,
203 self.authenticator.role_permissions,
204 )
delacruzramoceb8baf2019-06-21 14:25:38 +0200205 else:
garciadeblas4568a372021-03-24 09:19:48 +0100206 self.authconn = AuthconnInternal(
207 config["authentication"],
208 self.db,
209 self.authenticator.role_permissions,
210 )
tierno9e87a7f2020-03-23 09:24:10 +0000211 # if not self.operations:
212 # if "resources_to_operations" in config["rbac"]:
213 # resources_to_operations_file = config["rbac"]["resources_to_operations"]
214 # else:
215 # possible_paths = (
216 # __file__[:__file__.rfind("engine.py")] + "resources_to_operations.yml",
217 # "./resources_to_operations.yml"
218 # )
219 # for config_file in possible_paths:
220 # if path.isfile(config_file):
221 # resources_to_operations_file = config_file
222 # break
223 # if not resources_to_operations_file:
224 # raise EngineException("Invalid permission configuration:"
225 # "resources_to_operations file missing")
226 #
227 # with open(resources_to_operations_file, 'r') as f:
garciadeblas4cd875d2023-02-14 19:05:34 +0100228 # resources_to_operations = yaml.safeload(f)
tierno9e87a7f2020-03-23 09:24:10 +0000229 #
230 # self.operations = []
231 #
232 # for _, value in resources_to_operations["resources_to_operations"].items():
233 # if value not in self.operations:
234 # self.operations += [value]
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100235
tierno04dbb0e2019-01-09 16:00:24 +0000236 self.write_lock = Lock()
tiernob24258a2018-10-04 18:39:49 +0200237 # create one class per topic
238 for topic, topic_class in self.map_from_topic_to_class.items():
delacruzramo32bab472019-09-13 12:24:22 +0200239 # if self.auth and topic_class in (UserTopicAuth, ProjectTopicAuth):
240 # self.map_topic[topic] = topic_class(self.db, self.fs, self.msg, self.auth)
garciadeblas4568a372021-03-24 09:19:48 +0100241 self.map_topic[topic] = topic_class(
242 self.db, self.fs, self.msg, self.authconn
243 )
244
245 self.map_topic["pm_jobs"] = PmJobsTopic(
246 self.db,
247 config["prometheus"].get("host"),
248 config["prometheus"].get("port"),
249 )
tiernoc94c3df2018-02-09 15:38:54 +0100250 except (DbException, FsException, MsgException) as e:
251 raise EngineException(str(e), http_code=e.http_code)
252
253 def stop(self):
254 try:
255 if self.db:
256 self.db.db_disconnect()
257 if self.fs:
258 self.fs.fs_disconnect()
tierno932499c2019-01-28 17:28:10 +0000259 if self.msg:
260 self.msg.disconnect()
tierno04dbb0e2019-01-09 16:00:24 +0000261 self.write_lock = None
tiernoc94c3df2018-02-09 15:38:54 +0100262 except (DbException, FsException, MsgException) as e:
263 raise EngineException(str(e), http_code=e.http_code)
264
garciadeblas4568a372021-03-24 09:19:48 +0100265 def new_item(
266 self, rollback, session, topic, indata=None, kwargs=None, headers=None
267 ):
tiernoc94c3df2018-02-09 15:38:54 +0100268 """
tiernof27c79b2018-03-12 17:08:42 +0100269 Creates a new entry into database. For nsds and vnfds it creates an almost empty DISABLED entry,
270 that must be completed with a call to method upload_content
tiernob24258a2018-10-04 18:39:49 +0200271 :param rollback: list to append created items at database in case a rollback must to be done
tierno65ca36d2019-02-12 19:27:52 +0100272 :param session: contains the used login username and working project, force to avoid checkins, public
tiernob24258a2018-10-04 18:39:49 +0200273 :param topic: it can be: users, projects, vim_accounts, sdns, nsrs, nsds, vnfds
tiernoc94c3df2018-02-09 15:38:54 +0100274 :param indata: data to be inserted
275 :param kwargs: used to override the indata descriptor
276 :param headers: http request headers
tierno0ffaa992018-05-09 13:21:56 +0200277 :return: _id: identity of the inserted data.
tiernoc94c3df2018-02-09 15:38:54 +0100278 """
tiernob24258a2018-10-04 18:39:49 +0200279 if topic not in self.map_topic:
garciadeblas4568a372021-03-24 09:19:48 +0100280 raise EngineException(
281 "Unknown topic {}!!!".format(topic), HTTPStatus.INTERNAL_SERVER_ERROR
282 )
tierno04dbb0e2019-01-09 16:00:24 +0000283 with self.write_lock:
tierno65ca36d2019-02-12 19:27:52 +0100284 return self.map_topic[topic].new(rollback, session, indata, kwargs, headers)
tiernoc94c3df2018-02-09 15:38:54 +0100285
rshri2d386cb2024-07-05 14:35:51 +0000286 def add_item(
287 self, rollback, session, topic, indata=None, kwargs=None, headers=None
288 ):
289 """
290 register a cluster in the database.
291 :param rollback: list to append created items at database in case a rollback must to be done
292 :param session: contains the used login username and working project, force to avoid checkins, public
293 :param topic: it can be: cluster for adding cluster into database
294 :param indata: data to be inserted
295 :param kwargs: used to override the indata descriptor
296 :param headers: http request headers
297 :return: _id: identity of the inserted data.
298 """
299 if topic not in self.map_topic:
300 raise EngineException(
301 "Unknown topic {}!!!".format(topic), HTTPStatus.INTERNAL_SERVER_ERROR
302 )
303 with self.write_lock:
304 return self.map_topic[topic].add(rollback, session, indata, kwargs, headers)
305
tierno65ca36d2019-02-12 19:27:52 +0100306 def upload_content(self, session, topic, _id, indata, kwargs, headers):
tierno65acb4d2018-04-06 16:42:40 +0200307 """
tiernob24258a2018-10-04 18:39:49 +0200308 Upload content for an already created entry (_id)
tierno65acb4d2018-04-06 16:42:40 +0200309 :param session: contains the used login username and working project
tiernob24258a2018-10-04 18:39:49 +0200310 :param topic: it can be: users, projects, vnfds, nsds,
311 :param _id: server id of the item
312 :param indata: data to be inserted
tierno65acb4d2018-04-06 16:42:40 +0200313 :param kwargs: used to override the indata descriptor
tiernob24258a2018-10-04 18:39:49 +0200314 :param headers: http request headers
tiernob24258a2018-10-04 18:39:49 +0200315 :return: _id: identity of the inserted data.
tierno65acb4d2018-04-06 16:42:40 +0200316 """
tiernob24258a2018-10-04 18:39:49 +0200317 if topic not in self.map_topic:
garciadeblas4568a372021-03-24 09:19:48 +0100318 raise EngineException(
319 "Unknown topic {}!!!".format(topic), HTTPStatus.INTERNAL_SERVER_ERROR
320 )
tierno04dbb0e2019-01-09 16:00:24 +0000321 with self.write_lock:
garciadeblas4568a372021-03-24 09:19:48 +0100322 return self.map_topic[topic].upload_content(
323 session, _id, indata, kwargs, headers
324 )
tiernoc94c3df2018-02-09 15:38:54 +0100325
yshah53cc9eb2024-07-05 13:06:31 +0000326 def clone(
327 self, rollback, session, topic, _id, indata=None, kwargs=None, headers=None
328 ):
329 if topic not in self.map_topic:
330 raise EngineException(
331 "Unknown topic {}!!!".format(topic), HTTPStatus.INTERNAL_SERVER_ERROR
332 )
333 with self.write_lock:
334 return self.map_topic[topic].clone(
335 rollback, session, _id, indata, kwargs, headers
336 )
337
338 def move_ksu(self, session, topic, _id, indata=None, kwargs=None):
339 if topic not in self.map_topic:
340 raise EngineException(
341 "Unknown topic {}!!!".format(topic), HTTPStatus.INTERNAL_SERVER_ERROR
342 )
343
344 with self.write_lock:
345 return self.map_topic[topic].move_ksu(session, _id, indata, kwargs)
346
shahithya11664ac2024-10-17 05:51:39 +0000347 def get_cluster_creds_file(self, session, topic, _id, item, op_id):
yshah53cc9eb2024-07-05 13:06:31 +0000348 if topic not in self.map_topic:
349 raise EngineException(
350 "Unknown topic {}!!!".format(topic), HTTPStatus.INTERNAL_SERVER_ERROR
351 )
shahithya11664ac2024-10-17 05:51:39 +0000352 return self.map_topic[topic].get_cluster_creds_file(session, _id, item, op_id)
353
354 def get_cluster_creds(self, session, topic, _id, item):
355 if topic not in self.map_topic:
356 raise EngineException(
357 "Unknown topic {}!!!".format(topic), HTTPStatus.INTERNAL_SERVER_ERROR
358 )
359 return self.map_topic[topic].get_cluster_creds(session, _id, item)
yshah53cc9eb2024-07-05 13:06:31 +0000360
361 def update_cluster(self, session, topic, _id, item, indata):
362 if topic not in self.map_topic:
363 raise EngineException(
364 "Unknown topic {}!!!".format(topic), HTTPStatus.INTERNAL_SERVER_ERROR
365 )
366 return self.map_topic[topic].update_cluster(session, _id, item, indata)
367
368 def delete_ksu(self, session, topic, _id, indata):
369 if topic not in self.map_topic:
370 raise EngineException(
371 "Unknown topic {}!!!".format(topic), HTTPStatus.INTERNAL_SERVER_ERROR
372 )
373 with self.write_lock:
374 return self.map_topic[topic].delete_ksu(
375 session, _id, indata, not_send_msg=None
376 )
377
Frank Bryden19b97522020-07-10 12:32:02 +0000378 def get_item_list(self, session, topic, filter_q=None, api_req=False):
tiernoc94c3df2018-02-09 15:38:54 +0100379 """
380 Get a list of items
381 :param session: contains the used login username and working project
tiernob24258a2018-10-04 18:39:49 +0200382 :param topic: it can be: users, projects, vnfds, nsds, ...
383 :param filter_q: filter of data to be applied
Frank Bryden19b97522020-07-10 12:32:02 +0000384 :param api_req: True if this call is serving an external API request. False if serving internal request.
tiernob24258a2018-10-04 18:39:49 +0200385 :return: The list, it can be empty if no one match the filter_q.
tiernoc94c3df2018-02-09 15:38:54 +0100386 """
tiernob24258a2018-10-04 18:39:49 +0200387 if topic not in self.map_topic:
garciadeblasf2af4a12023-01-24 16:56:54 +0100388 raise EngineException(
389 "Unknown topic {}!!!".format(topic), HTTPStatus.INTERNAL_SERVER_ERROR
390 )
Frank Bryden19b97522020-07-10 12:32:02 +0000391 return self.map_topic[topic].list(session, filter_q, api_req)
tiernof27c79b2018-03-12 17:08:42 +0100392
K Sai Kiran57589552021-01-27 21:38:34 +0530393 def get_item(self, session, topic, _id, filter_q=None, api_req=False):
tiernoc94c3df2018-02-09 15:38:54 +0100394 """
tiernob24258a2018-10-04 18:39:49 +0200395 Get complete information on an item
tiernoc94c3df2018-02-09 15:38:54 +0100396 :param session: contains the used login username and working project
rshri2d386cb2024-07-05 14:35:51 +0000397 :param topic: it can be: users, projects, vnfds, nsds, clusters,
tiernoc94c3df2018-02-09 15:38:54 +0100398 :param _id: server id of the item
K Sai Kiran57589552021-01-27 21:38:34 +0530399 :param filter_q: other arguments
Frank Bryden19b97522020-07-10 12:32:02 +0000400 :param api_req: True if this call is serving an external API request. False if serving internal request.
tiernoc94c3df2018-02-09 15:38:54 +0100401 :return: dictionary, raise exception if not found.
402 """
tiernob24258a2018-10-04 18:39:49 +0200403 if topic not in self.map_topic:
garciadeblasf2af4a12023-01-24 16:56:54 +0100404 raise EngineException(
405 "Unknown topic {}!!!".format(topic), HTTPStatus.INTERNAL_SERVER_ERROR
406 )
K Sai Kiran57589552021-01-27 21:38:34 +0530407 return self.map_topic[topic].show(session, _id, filter_q, api_req)
tiernoc94c3df2018-02-09 15:38:54 +0100408
rshri2d386cb2024-07-05 14:35:51 +0000409 def get_one_item(self, session, topic, _id, profile, filter_q=None, api_req=False):
410 """
411 Get complete information on an item
412 :param session: contains the used login username and working project
413 :param topic: it can be: users, projects, vnfds, nsds, clusters profile,
414 :param _id: server id of the item
415 :param profile: contains the profile type
416 :param filter_q: other arguments
417 :param api_req: True if this call is serving an external API request. False if serving internal request.
418 :return: dictionary, raise exception if not found.
419 """
420 if topic not in self.map_topic:
421 raise EngineException(
422 "Unknown topic {}!!!".format(topic), HTTPStatus.INTERNAL_SERVER_ERROR
423 )
424 return self.map_topic[topic].show_one(session, _id, profile, filter_q, api_req)
425
tierno87006042018-10-24 12:50:20 +0200426 def get_file(self, session, topic, _id, path=None, accept_header=None):
427 """
428 Get descriptor package or artifact file content
429 :param session: contains the used login username and working project
430 :param topic: it can be: users, projects, vnfds, nsds,
431 :param _id: server id of the item
432 :param path: artifact path or "$DESCRIPTOR" or None
433 :param accept_header: Content of Accept header. Must contain applition/zip or/and text/plain
434 :return: opened file plus Accept format or raises an exception
435 """
436 if topic not in self.map_topic:
garciadeblas4568a372021-03-24 09:19:48 +0100437 raise EngineException(
438 "Unknown topic {}!!!".format(topic), HTTPStatus.INTERNAL_SERVER_ERROR
439 )
tierno87006042018-10-24 12:50:20 +0200440 return self.map_topic[topic].get_file(session, _id, path, accept_header)
441
tiernob24258a2018-10-04 18:39:49 +0200442 def del_item_list(self, session, topic, _filter=None):
tiernoc94c3df2018-02-09 15:38:54 +0100443 """
444 Delete a list of items
445 :param session: contains the used login username and working project
tiernob24258a2018-10-04 18:39:49 +0200446 :param topic: it can be: users, projects, vnfds, nsds, ...
447 :param _filter: filter of data to be applied
448 :return: The deleted list, it can be empty if no one match the _filter.
tiernoc94c3df2018-02-09 15:38:54 +0100449 """
tiernob24258a2018-10-04 18:39:49 +0200450 if topic not in self.map_topic:
garciadeblas4568a372021-03-24 09:19:48 +0100451 raise EngineException(
452 "Unknown topic {}!!!".format(topic), HTTPStatus.INTERNAL_SERVER_ERROR
453 )
tierno04dbb0e2019-01-09 16:00:24 +0000454 with self.write_lock:
455 return self.map_topic[topic].delete_list(session, _filter)
tiernoc94c3df2018-02-09 15:38:54 +0100456
tiernobee3bad2019-12-05 12:26:01 +0000457 def del_item(self, session, topic, _id, not_send_msg=None):
tiernoc94c3df2018-02-09 15:38:54 +0100458 """
tiernob92094f2018-05-11 13:44:22 +0200459 Delete item by its internal id
tiernoc94c3df2018-02-09 15:38:54 +0100460 :param session: contains the used login username and working project
tiernob24258a2018-10-04 18:39:49 +0200461 :param topic: it can be: users, projects, vnfds, nsds, ...
tiernoc94c3df2018-02-09 15:38:54 +0100462 :param _id: server id of the item
tiernobee3bad2019-12-05 12:26:01 +0000463 :param not_send_msg: If False, message will not be sent to kafka.
464 If a list, message is not sent, but content is stored in this variable so that the caller can send this
465 message using its own loop. If None, message is sent
delacruzramo01b15d32019-07-02 14:37:47 +0200466 :return: dictionary with deleted item _id. It raises exception if not found.
tiernoc94c3df2018-02-09 15:38:54 +0100467 """
tiernob24258a2018-10-04 18:39:49 +0200468 if topic not in self.map_topic:
garciadeblas4568a372021-03-24 09:19:48 +0100469 raise EngineException(
470 "Unknown topic {}!!!".format(topic), HTTPStatus.INTERNAL_SERVER_ERROR
471 )
tierno04dbb0e2019-01-09 16:00:24 +0000472 with self.write_lock:
tiernobee3bad2019-12-05 12:26:01 +0000473 return self.map_topic[topic].delete(session, _id, not_send_msg=not_send_msg)
tiernoc94c3df2018-02-09 15:38:54 +0100474
rshri2d386cb2024-07-05 14:35:51 +0000475 def remove(self, session, topic, _id, not_send_msg=None):
476 """
477 Delete item by its internal id
478 :param session: contains the used login username and working project
479 :param topic: it can be: users, projects, vnfds, nsds, clusters,
480 :param _id: server id of the item
481 :param not_send_msg: If False, message will not be sent to kafka.
482 If a list, message is not sent, but content is stored in this variable so that the caller can send this
483 message using its own loop. If None, message is sent
484 :return: dictionary with deleted item _id. It raises exception if not found.
485 """
486 if topic not in self.map_topic:
487 raise EngineException(
488 "Unknown topic {}!!!".format(topic), HTTPStatus.INTERNAL_SERVER_ERROR
489 )
490 with self.write_lock:
491 return self.map_topic[topic].remove(session, _id, not_send_msg=not_send_msg)
492
tierno65ca36d2019-02-12 19:27:52 +0100493 def edit_item(self, session, topic, _id, indata=None, kwargs=None):
tiernob24258a2018-10-04 18:39:49 +0200494 """
495 Update an existing entry at database
496 :param session: contains the used login username and working project
497 :param topic: it can be: users, projects, vnfds, nsds, ...
498 :param _id: identifier to be updated
499 :param indata: data to be inserted
500 :param kwargs: used to override the indata descriptor
delacruzramo01b15d32019-07-02 14:37:47 +0200501 :return: dictionary with edited item _id, raise exception if not found.
tiernob24258a2018-10-04 18:39:49 +0200502 """
503 if topic not in self.map_topic:
garciadeblas4568a372021-03-24 09:19:48 +0100504 raise EngineException(
505 "Unknown topic {}!!!".format(topic), HTTPStatus.INTERNAL_SERVER_ERROR
506 )
tierno04dbb0e2019-01-09 16:00:24 +0000507 with self.write_lock:
tierno65ca36d2019-02-12 19:27:52 +0100508 return self.map_topic[topic].edit(session, _id, indata, kwargs)
tiernoc94c3df2018-02-09 15:38:54 +0100509
rshri2d386cb2024-07-05 14:35:51 +0000510 def edit(self, session, topic, _id, item, indata=None, kwargs=None):
511 """
512 Update an existing entry at database
513 :param session: contains the used login username and working project
514 :param topic: it can be: users, projects, vnfds, nsds, ...
515 :param _id: identifier to be updated
516 :param item: it shows the type of profiles
517 :param indata: data to be inserted
518 :param kwargs: used to override the indata descriptor
519 :return: dictionary with edited item _id, raise exception if not found.
520 """
521 if topic not in self.map_topic:
522 raise EngineException(
523 "Unknown topic {}!!!".format(topic), HTTPStatus.INTERNAL_SERVER_ERROR
524 )
525 with self.write_lock:
526 return self.map_topic[topic].edit(session, _id, item, indata, kwargs)
527
Gabriel Cuba84a60df2023-10-30 14:01:54 -0500528 def cancel_item(
529 self, rollback, session, topic, indata=None, kwargs=None, headers=None
530 ):
531 """
532 Cancels an item
533 :param rollback: list to append created items at database in case a rollback must to be done
534 :param session: contains the used login username and working project, force to avoid checkins, public
535 :param topic: it can be: users, projects, vim_accounts, sdns, nsrs, nsds, vnfds
536 :param indata: data to be inserted
537 :param kwargs: used to override the indata descriptor
538 :param headers: http request headers
539 :return: _id: identity of the inserted data.
540 """
541 if topic not in self.map_topic:
542 raise EngineException(
543 "Unknown topic {}!!!".format(topic), HTTPStatus.INTERNAL_SERVER_ERROR
544 )
545 with self.write_lock:
546 self.map_topic[topic].cancel(rollback, session, indata, kwargs, headers)
547
tiernod985a8d2018-10-19 14:12:28 +0200548 def upgrade_db(self, current_version, target_version):
Eduardo Sousa044f4312019-05-20 15:17:35 +0100549 if target_version not in self.map_target_version_to_int.keys():
garciadeblas4568a372021-03-24 09:19:48 +0100550 raise EngineException(
551 "Cannot upgrade to version '{}' with this version of code".format(
552 target_version
553 ),
554 http_code=HTTPStatus.INTERNAL_SERVER_ERROR,
555 )
tiernod985a8d2018-10-19 14:12:28 +0200556
Eduardo Sousa044f4312019-05-20 15:17:35 +0100557 if current_version == target_version:
558 return
garciadeblas4568a372021-03-24 09:19:48 +0100559
Eduardo Sousa044f4312019-05-20 15:17:35 +0100560 target_version_int = self.map_target_version_to_int[target_version]
561
562 if not current_version:
563 # create database version
564 serial = urandom(32)
565 version_data = {
garciadeblas4568a372021-03-24 09:19:48 +0100566 "_id": "version", # Always "version"
567 "version_int": 1000, # version number
568 "version": "1.0", # version text
569 "date": "2018-10-25", # version date
Eduardo Sousa044f4312019-05-20 15:17:35 +0100570 "description": "added serial", # changes in this version
garciadeblas4568a372021-03-24 09:19:48 +0100571 "status": "ENABLED", # ENABLED, DISABLED (migration in process), ERROR,
572 "serial": b64encode(serial),
Eduardo Sousa044f4312019-05-20 15:17:35 +0100573 }
574 self.db.create("admin", version_data)
575 self.db.set_secret_key(serial)
576 current_version = "1.0"
garciadeblas4568a372021-03-24 09:19:48 +0100577
578 if (
579 current_version in ("1.0", "1.1")
580 and target_version_int >= self.map_target_version_to_int["1.2"]
581 ):
582 if self.config["authentication"]["backend"] == "internal":
delacruzramo01b15d32019-07-02 14:37:47 +0200583 self.db.del_list("roles")
584
Eduardo Sousa044f4312019-05-20 15:17:35 +0100585 version_data = {
586 "_id": "version",
tierno1f029d82019-06-13 22:37:04 +0000587 "version_int": 1002,
588 "version": "1.2",
589 "date": "2019-06-11",
garciadeblas4568a372021-03-24 09:19:48 +0100590 "description": "set new format for roles_operations",
Eduardo Sousa044f4312019-05-20 15:17:35 +0100591 }
592
593 self.db.set_one("admin", {"_id": "version"}, version_data)
tierno1f029d82019-06-13 22:37:04 +0000594 current_version = "1.2"
Eduardo Sousa044f4312019-05-20 15:17:35 +0100595 # TODO add future migrations here
tiernod985a8d2018-10-19 14:12:28 +0200596
garciadeblas4568a372021-03-24 09:19:48 +0100597 def init_db(self, target_version="1.0"):
tierno4a946e42018-04-12 17:48:49 +0200598 """
tiernod985a8d2018-10-19 14:12:28 +0200599 Init database if empty. If not empty it checks that database version and migrates if needed
tierno4a946e42018-04-12 17:48:49 +0200600 If empty, it creates a new user admin/admin at 'users' and a new entry at 'version'
tiernod985a8d2018-10-19 14:12:28 +0200601 :param target_version: check desired database version. Migrate to it if possible or raises exception
tierno4a946e42018-04-12 17:48:49 +0200602 :return: None if ok, exception if error or if the version is different.
603 """
tiernod985a8d2018-10-19 14:12:28 +0200604
garciadeblas4568a372021-03-24 09:19:48 +0100605 version_data = self.db.get_one(
606 "admin", {"_id": "version"}, fail_on_empty=False, fail_on_more=True
607 )
tiernod985a8d2018-10-19 14:12:28 +0200608 # check database status is ok
garciadeblas4568a372021-03-24 09:19:48 +0100609 if version_data and version_data.get("status") != "ENABLED":
610 raise EngineException(
611 "Wrong database status '{}'".format(version_data["status"]),
612 HTTPStatus.INTERNAL_SERVER_ERROR,
613 )
tiernod985a8d2018-10-19 14:12:28 +0200614
615 # check version
616 db_version = None if not version_data else version_data.get("version")
617 if db_version != target_version:
618 self.upgrade_db(db_version, target_version)
619
tierno4a946e42018-04-12 17:48:49 +0200620 return