blob: f9a1502811c9b4e46260a13922f1ddd529956533 [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 (
shrinithi28d887f2025-01-08 05:27:19 +000057 ClusterTopic,
rshri2d386cb2024-07-05 14:35:51 +000058 InfraContTopic,
59 InfraConfTopic,
garciadeblasb798f452025-08-05 18:21:26 +020060 AppProfileTopic,
rshri2d386cb2024-07-05 14:35:51 +000061 ResourceTopic,
shrinithi28d887f2025-01-08 05:27:19 +000062 ClusterOpsTopic,
yshah53cc9eb2024-07-05 13:06:31 +000063 KsusTopic,
garciadeblasb798f452025-08-05 18:21:26 +020064 AppInstanceTopic,
yshah53cc9eb2024-07-05 13:06:31 +000065 OkaTopic,
yshahd23c6a52025-06-13 05:49:31 +000066 NodeGroupTopic,
rshri2d386cb2024-07-05 14:35:51 +000067)
almagiae47b9132022-05-17 14:12:22 +020068from osm_nbi.vnf_instance_topics import VnfInstances, VnfLcmOpTopic
tierno23acf402019-08-28 13:36:34 +000069from osm_nbi.pmjobs_topics import PmJobsTopic
preethika.p329b8182020-04-22 12:25:39 +053070from osm_nbi.subscription_topics import NslcmSubscriptionsTopic
selvi.jf1004592022-04-29 05:42:35 +000071from osm_nbi.osm_vnfm.vnf_subscription import VnflcmSubscriptionsTopic
tiernod985a8d2018-10-19 14:12:28 +020072from base64 import b64encode
garciadeblas4568a372021-03-24 09:19:48 +010073from os import urandom # , path
tierno04dbb0e2019-01-09 16:00:24 +000074from threading import Lock
tiernoc94c3df2018-02-09 15:38:54 +010075
76__author__ = "Alfonso Tierno <alfonso.tiernosepulveda@telefonica.com>"
tierno932499c2019-01-28 17:28:10 +000077min_common_version = "0.1.16"
tierno441dbbf2018-07-10 12:52:48 +020078
79
tiernoc94c3df2018-02-09 15:38:54 +010080class Engine(object):
tiernob24258a2018-10-04 18:39:49 +020081 map_from_topic_to_class = {
82 "vnfds": VnfdTopic,
83 "nsds": NsdTopic,
Felipe Vicensb57758d2018-10-16 16:00:20 +020084 "nsts": NstTopic,
tiernob24258a2018-10-04 18:39:49 +020085 "pdus": PduTopic,
86 "nsrs": NsrTopic,
87 "vnfrs": VnfrTopic,
88 "nslcmops": NsLcmOpTopic,
89 "vim_accounts": VimAccountTopic,
tierno55ba2e62018-12-11 17:22:22 +000090 "wim_accounts": WimAccountTopic,
tiernob24258a2018-10-04 18:39:49 +020091 "sdns": SdnTopic,
delacruzramofe598fe2019-10-23 18:25:11 +020092 "k8sclusters": K8sClusterTopic,
David Garciaecb41322021-03-31 19:10:46 +020093 "vca": VcaTopic,
delacruzramofe598fe2019-10-23 18:25:11 +020094 "k8srepos": K8sRepoTopic,
Felipe Vicensb66b0412020-05-06 10:11:00 +020095 "osmrepos": OsmRepoTopic,
garciadeblas4568a372021-03-24 09:19:48 +010096 "users": UserTopicAuth, # Valid for both internal and keystone authentication backends
97 "projects": ProjectTopicAuth, # Valid for both internal and keystone authentication backends
98 "roles": RoleTopicAuth, # Valid for both internal and keystone authentication backends
Felipe Vicensb57758d2018-10-16 16:00:20 +020099 "nsis": NsiTopic,
delacruzramo271d2002019-12-02 21:00:37 +0100100 "nsilcmops": NsiLcmOpTopic,
101 "vnfpkgops": VnfPkgOpTopic,
preethika.p329b8182020-04-22 12:25:39 +0530102 "nslcm_subscriptions": NslcmSubscriptionsTopic,
almagiae47b9132022-05-17 14:12:22 +0200103 "vnf_instances": VnfInstances,
104 "vnflcmops": VnfLcmOpTopic,
selvi.jf1004592022-04-29 05:42:35 +0000105 "vnflcm_subscriptions": VnflcmSubscriptionsTopic,
kayal2001f71c2e82024-06-25 15:26:24 +0530106 "nsconfigtemps": NsConfigTemplateTopic,
shrinithi28d887f2025-01-08 05:27:19 +0000107 "cluster": ClusterTopic,
rshri2d386cb2024-07-05 14:35:51 +0000108 "infras_cont": InfraContTopic,
109 "infras_conf": InfraConfTopic,
garciadeblasb798f452025-08-05 18:21:26 +0200110 "apps": AppProfileTopic,
rshri2d386cb2024-07-05 14:35:51 +0000111 "resources": ResourceTopic,
shrinithi28d887f2025-01-08 05:27:19 +0000112 "clusterops": ClusterOpsTopic,
yshah53cc9eb2024-07-05 13:06:31 +0000113 "ksus": KsusTopic,
garciadeblasb798f452025-08-05 18:21:26 +0200114 "appinstances": AppInstanceTopic,
yshah53cc9eb2024-07-05 13:06:31 +0000115 "oka_packages": OkaTopic,
yshahd23c6a52025-06-13 05:49:31 +0000116 "node_groups": NodeGroupTopic,
tiernob24258a2018-10-04 18:39:49 +0200117 # [NEW_TOPIC]: add an entry here
vijay.r35ef2f72019-04-30 17:55:49 +0530118 # "pm_jobs": PmJobsTopic will be added manually because it needs other parameters
tiernob24258a2018-10-04 18:39:49 +0200119 }
tiernoc94c3df2018-02-09 15:38:54 +0100120
Eduardo Sousa044f4312019-05-20 15:17:35 +0100121 map_target_version_to_int = {
122 "1.0": 1000,
tierno1f029d82019-06-13 22:37:04 +0000123 "1.1": 1001,
124 "1.2": 1002,
Eduardo Sousa044f4312019-05-20 15:17:35 +0100125 # Add new versions here
126 }
127
delacruzramoad682a52019-12-10 16:26:34 +0100128 def __init__(self, authenticator):
tiernoc94c3df2018-02-09 15:38:54 +0100129 self.db = None
130 self.fs = None
131 self.msg = None
delacruzramoad682a52019-12-10 16:26:34 +0100132 self.authconn = None
tiernoc94c3df2018-02-09 15:38:54 +0100133 self.config = None
tierno9e87a7f2020-03-23 09:24:10 +0000134 # self.operations = None
tiernoc94c3df2018-02-09 15:38:54 +0100135 self.logger = logging.getLogger("nbi.engine")
tiernob24258a2018-10-04 18:39:49 +0200136 self.map_topic = {}
tierno04dbb0e2019-01-09 16:00:24 +0000137 self.write_lock = None
delacruzramoad682a52019-12-10 16:26:34 +0100138 # self.token_cache = token_cache
139 self.authenticator = authenticator
tiernoc94c3df2018-02-09 15:38:54 +0100140
141 def start(self, config):
142 """
143 Connect to database, filesystem storage, and messaging
144 :param config: two level dictionary with configuration. Top level should contain 'database', 'storage',
145 :return: None
146 """
147 self.config = config
tiernob24258a2018-10-04 18:39:49 +0200148 # check right version of common
149 if versiontuple(common_version) < versiontuple(min_common_version):
garciadeblas4568a372021-03-24 09:19:48 +0100150 raise EngineException(
151 "Not compatible osm/common version '{}'. Needed '{}' or higher".format(
152 common_version, min_common_version
153 )
154 )
tiernob24258a2018-10-04 18:39:49 +0200155
tiernoc94c3df2018-02-09 15:38:54 +0100156 try:
157 if not self.db:
158 if config["database"]["driver"] == "mongo":
159 self.db = dbmongo.DbMongo()
160 self.db.db_connect(config["database"])
161 elif config["database"]["driver"] == "memory":
162 self.db = dbmemory.DbMemory()
163 self.db.db_connect(config["database"])
164 else:
garciadeblas4568a372021-03-24 09:19:48 +0100165 raise EngineException(
166 "Invalid configuration param '{}' at '[database]':'driver'".format(
167 config["database"]["driver"]
168 )
169 )
tiernoc94c3df2018-02-09 15:38:54 +0100170 if not self.fs:
171 if config["storage"]["driver"] == "local":
172 self.fs = fslocal.FsLocal()
173 self.fs.fs_connect(config["storage"])
Eduardo Sousa7e0eb132019-06-21 11:50:21 +0100174 elif config["storage"]["driver"] == "mongo":
175 self.fs = fsmongo.FsMongo()
176 self.fs.fs_connect(config["storage"])
tiernoc94c3df2018-02-09 15:38:54 +0100177 else:
garciadeblas4568a372021-03-24 09:19:48 +0100178 raise EngineException(
179 "Invalid configuration param '{}' at '[storage]':'driver'".format(
180 config["storage"]["driver"]
181 )
182 )
tiernoc94c3df2018-02-09 15:38:54 +0100183 if not self.msg:
184 if config["message"]["driver"] == "local":
185 self.msg = msglocal.MsgLocal()
186 self.msg.connect(config["message"])
187 elif config["message"]["driver"] == "kafka":
188 self.msg = msgkafka.MsgKafka()
189 self.msg.connect(config["message"])
190 else:
garciadeblas4568a372021-03-24 09:19:48 +0100191 raise EngineException(
192 "Invalid configuration param '{}' at '[message]':'driver'".format(
193 config["message"]["driver"]
194 )
195 )
delacruzramoad682a52019-12-10 16:26:34 +0100196 if not self.authconn:
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100197 if config["authentication"]["backend"] == "keystone":
garciadeblas4568a372021-03-24 09:19:48 +0100198 self.authconn = AuthconnKeystone(
199 config["authentication"],
200 self.db,
201 self.authenticator.role_permissions,
202 )
K Sai Kiran7ddb0732020-10-30 11:14:44 +0530203 elif config["authentication"]["backend"] == "tacacs":
garciadeblas4568a372021-03-24 09:19:48 +0100204 self.authconn = AuthconnTacacs(
205 config["authentication"],
206 self.db,
207 self.authenticator.role_permissions,
208 )
delacruzramoceb8baf2019-06-21 14:25:38 +0200209 else:
garciadeblas4568a372021-03-24 09:19:48 +0100210 self.authconn = AuthconnInternal(
211 config["authentication"],
212 self.db,
213 self.authenticator.role_permissions,
214 )
tierno9e87a7f2020-03-23 09:24:10 +0000215 # if not self.operations:
216 # if "resources_to_operations" in config["rbac"]:
217 # resources_to_operations_file = config["rbac"]["resources_to_operations"]
218 # else:
219 # possible_paths = (
220 # __file__[:__file__.rfind("engine.py")] + "resources_to_operations.yml",
221 # "./resources_to_operations.yml"
222 # )
223 # for config_file in possible_paths:
224 # if path.isfile(config_file):
225 # resources_to_operations_file = config_file
226 # break
227 # if not resources_to_operations_file:
228 # raise EngineException("Invalid permission configuration:"
229 # "resources_to_operations file missing")
230 #
231 # with open(resources_to_operations_file, 'r') as f:
garciadeblas4cd875d2023-02-14 19:05:34 +0100232 # resources_to_operations = yaml.safeload(f)
tierno9e87a7f2020-03-23 09:24:10 +0000233 #
234 # self.operations = []
235 #
236 # for _, value in resources_to_operations["resources_to_operations"].items():
237 # if value not in self.operations:
238 # self.operations += [value]
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100239
tierno04dbb0e2019-01-09 16:00:24 +0000240 self.write_lock = Lock()
tiernob24258a2018-10-04 18:39:49 +0200241 # create one class per topic
242 for topic, topic_class in self.map_from_topic_to_class.items():
delacruzramo32bab472019-09-13 12:24:22 +0200243 # if self.auth and topic_class in (UserTopicAuth, ProjectTopicAuth):
244 # self.map_topic[topic] = topic_class(self.db, self.fs, self.msg, self.auth)
garciadeblas4568a372021-03-24 09:19:48 +0100245 self.map_topic[topic] = topic_class(
246 self.db, self.fs, self.msg, self.authconn
247 )
248
249 self.map_topic["pm_jobs"] = PmJobsTopic(
250 self.db,
251 config["prometheus"].get("host"),
252 config["prometheus"].get("port"),
253 )
tiernoc94c3df2018-02-09 15:38:54 +0100254 except (DbException, FsException, MsgException) as e:
255 raise EngineException(str(e), http_code=e.http_code)
256
257 def stop(self):
258 try:
259 if self.db:
260 self.db.db_disconnect()
261 if self.fs:
262 self.fs.fs_disconnect()
tierno932499c2019-01-28 17:28:10 +0000263 if self.msg:
264 self.msg.disconnect()
tierno04dbb0e2019-01-09 16:00:24 +0000265 self.write_lock = None
tiernoc94c3df2018-02-09 15:38:54 +0100266 except (DbException, FsException, MsgException) as e:
267 raise EngineException(str(e), http_code=e.http_code)
268
garciadeblas4568a372021-03-24 09:19:48 +0100269 def new_item(
270 self, rollback, session, topic, indata=None, kwargs=None, headers=None
271 ):
tiernoc94c3df2018-02-09 15:38:54 +0100272 """
tiernof27c79b2018-03-12 17:08:42 +0100273 Creates a new entry into database. For nsds and vnfds it creates an almost empty DISABLED entry,
274 that must be completed with a call to method upload_content
tiernob24258a2018-10-04 18:39:49 +0200275 :param rollback: list to append created items at database in case a rollback must to be done
tierno65ca36d2019-02-12 19:27:52 +0100276 :param session: contains the used login username and working project, force to avoid checkins, public
tiernob24258a2018-10-04 18:39:49 +0200277 :param topic: it can be: users, projects, vim_accounts, sdns, nsrs, nsds, vnfds
tiernoc94c3df2018-02-09 15:38:54 +0100278 :param indata: data to be inserted
279 :param kwargs: used to override the indata descriptor
280 :param headers: http request headers
tierno0ffaa992018-05-09 13:21:56 +0200281 :return: _id: identity of the inserted data.
tiernoc94c3df2018-02-09 15:38:54 +0100282 """
tiernob24258a2018-10-04 18:39:49 +0200283 if topic not in self.map_topic:
garciadeblas4568a372021-03-24 09:19:48 +0100284 raise EngineException(
285 "Unknown topic {}!!!".format(topic), HTTPStatus.INTERNAL_SERVER_ERROR
286 )
tierno04dbb0e2019-01-09 16:00:24 +0000287 with self.write_lock:
tierno65ca36d2019-02-12 19:27:52 +0100288 return self.map_topic[topic].new(rollback, session, indata, kwargs, headers)
tiernoc94c3df2018-02-09 15:38:54 +0100289
rshri2d386cb2024-07-05 14:35:51 +0000290 def add_item(
291 self, rollback, session, topic, indata=None, kwargs=None, headers=None
292 ):
293 """
294 register a cluster in the database.
295 :param rollback: list to append created items at database in case a rollback must to be done
296 :param session: contains the used login username and working project, force to avoid checkins, public
297 :param topic: it can be: cluster for adding cluster into database
298 :param indata: data to be inserted
299 :param kwargs: used to override the indata descriptor
300 :param headers: http request headers
301 :return: _id: identity of the inserted data.
302 """
303 if topic not in self.map_topic:
304 raise EngineException(
305 "Unknown topic {}!!!".format(topic), HTTPStatus.INTERNAL_SERVER_ERROR
306 )
307 with self.write_lock:
308 return self.map_topic[topic].add(rollback, session, indata, kwargs, headers)
309
tierno65ca36d2019-02-12 19:27:52 +0100310 def upload_content(self, session, topic, _id, indata, kwargs, headers):
tierno65acb4d2018-04-06 16:42:40 +0200311 """
tiernob24258a2018-10-04 18:39:49 +0200312 Upload content for an already created entry (_id)
tierno65acb4d2018-04-06 16:42:40 +0200313 :param session: contains the used login username and working project
tiernob24258a2018-10-04 18:39:49 +0200314 :param topic: it can be: users, projects, vnfds, nsds,
315 :param _id: server id of the item
316 :param indata: data to be inserted
tierno65acb4d2018-04-06 16:42:40 +0200317 :param kwargs: used to override the indata descriptor
tiernob24258a2018-10-04 18:39:49 +0200318 :param headers: http request headers
tiernob24258a2018-10-04 18:39:49 +0200319 :return: _id: identity of the inserted data.
tierno65acb4d2018-04-06 16:42:40 +0200320 """
tiernob24258a2018-10-04 18:39:49 +0200321 if topic not in self.map_topic:
garciadeblas4568a372021-03-24 09:19:48 +0100322 raise EngineException(
323 "Unknown topic {}!!!".format(topic), HTTPStatus.INTERNAL_SERVER_ERROR
324 )
tierno04dbb0e2019-01-09 16:00:24 +0000325 with self.write_lock:
garciadeblas4568a372021-03-24 09:19:48 +0100326 return self.map_topic[topic].upload_content(
327 session, _id, indata, kwargs, headers
328 )
tiernoc94c3df2018-02-09 15:38:54 +0100329
yshah53cc9eb2024-07-05 13:06:31 +0000330 def clone(
331 self, rollback, session, topic, _id, indata=None, kwargs=None, headers=None
332 ):
333 if topic not in self.map_topic:
334 raise EngineException(
335 "Unknown topic {}!!!".format(topic), HTTPStatus.INTERNAL_SERVER_ERROR
336 )
337 with self.write_lock:
338 return self.map_topic[topic].clone(
339 rollback, session, _id, indata, kwargs, headers
340 )
341
342 def move_ksu(self, session, topic, _id, indata=None, kwargs=None):
343 if topic not in self.map_topic:
344 raise EngineException(
345 "Unknown topic {}!!!".format(topic), HTTPStatus.INTERNAL_SERVER_ERROR
346 )
347
348 with self.write_lock:
349 return self.map_topic[topic].move_ksu(session, _id, indata, kwargs)
350
shahithyab9eb4142024-10-17 05:51:39 +0000351 def get_cluster_creds_file(self, session, topic, _id, item, op_id):
yshah53cc9eb2024-07-05 13:06:31 +0000352 if topic not in self.map_topic:
353 raise EngineException(
354 "Unknown topic {}!!!".format(topic), HTTPStatus.INTERNAL_SERVER_ERROR
355 )
shahithyab9eb4142024-10-17 05:51:39 +0000356 return self.map_topic[topic].get_cluster_creds_file(session, _id, item, op_id)
357
358 def get_cluster_creds(self, session, topic, _id, item):
359 if topic not in self.map_topic:
360 raise EngineException(
361 "Unknown topic {}!!!".format(topic), HTTPStatus.INTERNAL_SERVER_ERROR
362 )
363 return self.map_topic[topic].get_cluster_creds(session, _id, item)
yshah53cc9eb2024-07-05 13:06:31 +0000364
yshahd23c6a52025-06-13 05:49:31 +0000365 def update_item(self, session, topic, _id, item, indata):
yshah53cc9eb2024-07-05 13:06:31 +0000366 if topic not in self.map_topic:
367 raise EngineException(
368 "Unknown topic {}!!!".format(topic), HTTPStatus.INTERNAL_SERVER_ERROR
369 )
yshahd23c6a52025-06-13 05:49:31 +0000370 return self.map_topic[topic].update_item(session, _id, item, indata)
yshah53cc9eb2024-07-05 13:06:31 +0000371
372 def delete_ksu(self, session, topic, _id, indata):
373 if topic not in self.map_topic:
374 raise EngineException(
375 "Unknown topic {}!!!".format(topic), HTTPStatus.INTERNAL_SERVER_ERROR
376 )
377 with self.write_lock:
378 return self.map_topic[topic].delete_ksu(
379 session, _id, indata, not_send_msg=None
380 )
381
garciadeblasb798f452025-08-05 18:21:26 +0200382 def update_appinstance(self, session, topic, _id, item, indata):
383 if topic not in self.map_topic:
384 raise EngineException(
385 "Unknown topic {}!!!".format(topic), HTTPStatus.INTERNAL_SERVER_ERROR
386 )
387 return self.map_topic[topic].update_appinstance(session, _id, item, indata)
388
Frank Bryden19b97522020-07-10 12:32:02 +0000389 def get_item_list(self, session, topic, filter_q=None, api_req=False):
tiernoc94c3df2018-02-09 15:38:54 +0100390 """
391 Get a list of items
392 :param session: contains the used login username and working project
tiernob24258a2018-10-04 18:39:49 +0200393 :param topic: it can be: users, projects, vnfds, nsds, ...
394 :param filter_q: filter of data to be applied
Frank Bryden19b97522020-07-10 12:32:02 +0000395 :param api_req: True if this call is serving an external API request. False if serving internal request.
tiernob24258a2018-10-04 18:39:49 +0200396 :return: The list, it can be empty if no one match the filter_q.
tiernoc94c3df2018-02-09 15:38:54 +0100397 """
shrinithi28d887f2025-01-08 05:27:19 +0000398 self.logger.info("it is getting into item list")
tiernob24258a2018-10-04 18:39:49 +0200399 if topic not in self.map_topic:
garciadeblasf2af4a12023-01-24 16:56:54 +0100400 raise EngineException(
401 "Unknown topic {}!!!".format(topic), HTTPStatus.INTERNAL_SERVER_ERROR
402 )
Frank Bryden19b97522020-07-10 12:32:02 +0000403 return self.map_topic[topic].list(session, filter_q, api_req)
tiernof27c79b2018-03-12 17:08:42 +0100404
shrinithi28d887f2025-01-08 05:27:19 +0000405 def get_item_list_cluster(self, session, topic, filter_q=None, api_req=False):
406 """
407 Get a list of items
408 :param session: contains the used login username and working project
409 :param topic: it can be: users, projects, vnfds, nsds, ...
410 :param filter_q: filter of data to be applied
411 :param api_req: True if this call is serving an external API request. False if serving internal request.
412 :return: The list, it can be empty if no one match the filter_q.
413 """
414 self.logger.info("it is getting into item list cluster")
415 if topic not in self.map_topic:
416 raise EngineException(
417 "Unknown topic {}!!!".format(topic), HTTPStatus.INTERNAL_SERVER_ERROR
418 )
419 return self.map_topic[topic].list_both(session, filter_q, api_req)
420
K Sai Kiran57589552021-01-27 21:38:34 +0530421 def get_item(self, session, topic, _id, filter_q=None, api_req=False):
tiernoc94c3df2018-02-09 15:38:54 +0100422 """
tiernob24258a2018-10-04 18:39:49 +0200423 Get complete information on an item
tiernoc94c3df2018-02-09 15:38:54 +0100424 :param session: contains the used login username and working project
rshri2d386cb2024-07-05 14:35:51 +0000425 :param topic: it can be: users, projects, vnfds, nsds, clusters,
tiernoc94c3df2018-02-09 15:38:54 +0100426 :param _id: server id of the item
K Sai Kiran57589552021-01-27 21:38:34 +0530427 :param filter_q: other arguments
Frank Bryden19b97522020-07-10 12:32:02 +0000428 :param api_req: True if this call is serving an external API request. False if serving internal request.
tiernoc94c3df2018-02-09 15:38:54 +0100429 :return: dictionary, raise exception if not found.
430 """
tiernob24258a2018-10-04 18:39:49 +0200431 if topic not in self.map_topic:
garciadeblasf2af4a12023-01-24 16:56:54 +0100432 raise EngineException(
433 "Unknown topic {}!!!".format(topic), HTTPStatus.INTERNAL_SERVER_ERROR
434 )
K Sai Kiran57589552021-01-27 21:38:34 +0530435 return self.map_topic[topic].show(session, _id, filter_q, api_req)
tiernoc94c3df2018-02-09 15:38:54 +0100436
rshri2d386cb2024-07-05 14:35:51 +0000437 def get_one_item(self, session, topic, _id, profile, filter_q=None, api_req=False):
438 """
439 Get complete information on an item
440 :param session: contains the used login username and working project
441 :param topic: it can be: users, projects, vnfds, nsds, clusters profile,
442 :param _id: server id of the item
443 :param profile: contains the profile type
444 :param filter_q: other arguments
445 :param api_req: True if this call is serving an external API request. False if serving internal request.
446 :return: dictionary, raise exception if not found.
447 """
448 if topic not in self.map_topic:
449 raise EngineException(
450 "Unknown topic {}!!!".format(topic), HTTPStatus.INTERNAL_SERVER_ERROR
451 )
452 return self.map_topic[topic].show_one(session, _id, profile, filter_q, api_req)
453
tierno87006042018-10-24 12:50:20 +0200454 def get_file(self, session, topic, _id, path=None, accept_header=None):
455 """
456 Get descriptor package or artifact file content
457 :param session: contains the used login username and working project
458 :param topic: it can be: users, projects, vnfds, nsds,
459 :param _id: server id of the item
460 :param path: artifact path or "$DESCRIPTOR" or None
461 :param accept_header: Content of Accept header. Must contain applition/zip or/and text/plain
462 :return: opened file plus Accept format or raises an exception
463 """
464 if topic not in self.map_topic:
garciadeblas4568a372021-03-24 09:19:48 +0100465 raise EngineException(
466 "Unknown topic {}!!!".format(topic), HTTPStatus.INTERNAL_SERVER_ERROR
467 )
tierno87006042018-10-24 12:50:20 +0200468 return self.map_topic[topic].get_file(session, _id, path, accept_header)
469
yshahd23c6a52025-06-13 05:49:31 +0000470 def get_cluster_list_ksu(self, session, topic, filter_q=None, api_req=False):
471 """
472 Get a list of items
473 :param session: contains the used login username and working project
474 :param topic: it can be: users, projects, vnfds, nsds, ...
475 :param filter_q: filter of data to be applied
476 :param api_req: True if this call is serving an external API request. False if serving internal request.
477 :return: The list, it can be empty if no one match the filter_q.
478 """
479 self.logger.info("it is getting into item list cluster")
480 if topic not in self.map_topic:
481 raise EngineException(
482 "Unknown topic {}!!!".format(topic), HTTPStatus.INTERNAL_SERVER_ERROR
483 )
484 return self.map_topic[topic].cluster_list_ksu(session, filter_q, api_req)
485
tiernob24258a2018-10-04 18:39:49 +0200486 def del_item_list(self, session, topic, _filter=None):
tiernoc94c3df2018-02-09 15:38:54 +0100487 """
488 Delete a list of items
489 :param session: contains the used login username and working project
tiernob24258a2018-10-04 18:39:49 +0200490 :param topic: it can be: users, projects, vnfds, nsds, ...
491 :param _filter: filter of data to be applied
492 :return: The deleted list, it can be empty if no one match the _filter.
tiernoc94c3df2018-02-09 15:38:54 +0100493 """
tiernob24258a2018-10-04 18:39:49 +0200494 if topic not in self.map_topic:
garciadeblas4568a372021-03-24 09:19:48 +0100495 raise EngineException(
496 "Unknown topic {}!!!".format(topic), HTTPStatus.INTERNAL_SERVER_ERROR
497 )
tierno04dbb0e2019-01-09 16:00:24 +0000498 with self.write_lock:
499 return self.map_topic[topic].delete_list(session, _filter)
tiernoc94c3df2018-02-09 15:38:54 +0100500
tiernobee3bad2019-12-05 12:26:01 +0000501 def del_item(self, session, topic, _id, not_send_msg=None):
tiernoc94c3df2018-02-09 15:38:54 +0100502 """
tiernob92094f2018-05-11 13:44:22 +0200503 Delete item by its internal id
tiernoc94c3df2018-02-09 15:38:54 +0100504 :param session: contains the used login username and working project
tiernob24258a2018-10-04 18:39:49 +0200505 :param topic: it can be: users, projects, vnfds, nsds, ...
tiernoc94c3df2018-02-09 15:38:54 +0100506 :param _id: server id of the item
tiernobee3bad2019-12-05 12:26:01 +0000507 :param not_send_msg: If False, message will not be sent to kafka.
508 If a list, message is not sent, but content is stored in this variable so that the caller can send this
509 message using its own loop. If None, message is sent
delacruzramo01b15d32019-07-02 14:37:47 +0200510 :return: dictionary with deleted item _id. It raises exception if not found.
tiernoc94c3df2018-02-09 15:38:54 +0100511 """
tiernob24258a2018-10-04 18:39:49 +0200512 if topic not in self.map_topic:
garciadeblas4568a372021-03-24 09:19:48 +0100513 raise EngineException(
514 "Unknown topic {}!!!".format(topic), HTTPStatus.INTERNAL_SERVER_ERROR
515 )
tierno04dbb0e2019-01-09 16:00:24 +0000516 with self.write_lock:
tiernobee3bad2019-12-05 12:26:01 +0000517 return self.map_topic[topic].delete(session, _id, not_send_msg=not_send_msg)
tiernoc94c3df2018-02-09 15:38:54 +0100518
rshri2d386cb2024-07-05 14:35:51 +0000519 def remove(self, session, topic, _id, not_send_msg=None):
520 """
521 Delete item by its internal id
522 :param session: contains the used login username and working project
523 :param topic: it can be: users, projects, vnfds, nsds, clusters,
524 :param _id: server id of the item
525 :param not_send_msg: If False, message will not be sent to kafka.
526 If a list, message is not sent, but content is stored in this variable so that the caller can send this
527 message using its own loop. If None, message is sent
528 :return: dictionary with deleted item _id. It raises exception if not found.
529 """
530 if topic not in self.map_topic:
531 raise EngineException(
532 "Unknown topic {}!!!".format(topic), HTTPStatus.INTERNAL_SERVER_ERROR
533 )
534 with self.write_lock:
535 return self.map_topic[topic].remove(session, _id, not_send_msg=not_send_msg)
536
tierno65ca36d2019-02-12 19:27:52 +0100537 def edit_item(self, session, topic, _id, indata=None, kwargs=None):
tiernob24258a2018-10-04 18:39:49 +0200538 """
539 Update an existing entry at database
540 :param session: contains the used login username and working project
541 :param topic: it can be: users, projects, vnfds, nsds, ...
542 :param _id: identifier to be updated
543 :param indata: data to be inserted
544 :param kwargs: used to override the indata descriptor
delacruzramo01b15d32019-07-02 14:37:47 +0200545 :return: dictionary with edited item _id, raise exception if not found.
tiernob24258a2018-10-04 18:39:49 +0200546 """
547 if topic not in self.map_topic:
garciadeblas4568a372021-03-24 09:19:48 +0100548 raise EngineException(
549 "Unknown topic {}!!!".format(topic), HTTPStatus.INTERNAL_SERVER_ERROR
550 )
tierno04dbb0e2019-01-09 16:00:24 +0000551 with self.write_lock:
tierno65ca36d2019-02-12 19:27:52 +0100552 return self.map_topic[topic].edit(session, _id, indata, kwargs)
tiernoc94c3df2018-02-09 15:38:54 +0100553
rshri2d386cb2024-07-05 14:35:51 +0000554 def edit(self, session, topic, _id, item, indata=None, kwargs=None):
555 """
556 Update an existing entry at database
557 :param session: contains the used login username and working project
558 :param topic: it can be: users, projects, vnfds, nsds, ...
559 :param _id: identifier to be updated
560 :param item: it shows the type of profiles
561 :param indata: data to be inserted
562 :param kwargs: used to override the indata descriptor
563 :return: dictionary with edited item _id, raise exception if not found.
564 """
565 if topic not in self.map_topic:
566 raise EngineException(
567 "Unknown topic {}!!!".format(topic), HTTPStatus.INTERNAL_SERVER_ERROR
568 )
569 with self.write_lock:
570 return self.map_topic[topic].edit(session, _id, item, indata, kwargs)
571
Gabriel Cuba84a60df2023-10-30 14:01:54 -0500572 def cancel_item(
573 self, rollback, session, topic, indata=None, kwargs=None, headers=None
574 ):
575 """
576 Cancels an item
577 :param rollback: list to append created items at database in case a rollback must to be done
578 :param session: contains the used login username and working project, force to avoid checkins, public
579 :param topic: it can be: users, projects, vim_accounts, sdns, nsrs, nsds, vnfds
580 :param indata: data to be inserted
581 :param kwargs: used to override the indata descriptor
582 :param headers: http request headers
583 :return: _id: identity of the inserted data.
584 """
585 if topic not in self.map_topic:
586 raise EngineException(
587 "Unknown topic {}!!!".format(topic), HTTPStatus.INTERNAL_SERVER_ERROR
588 )
589 with self.write_lock:
590 self.map_topic[topic].cancel(rollback, session, indata, kwargs, headers)
591
tiernod985a8d2018-10-19 14:12:28 +0200592 def upgrade_db(self, current_version, target_version):
Eduardo Sousa044f4312019-05-20 15:17:35 +0100593 if target_version not in self.map_target_version_to_int.keys():
garciadeblas4568a372021-03-24 09:19:48 +0100594 raise EngineException(
595 "Cannot upgrade to version '{}' with this version of code".format(
596 target_version
597 ),
598 http_code=HTTPStatus.INTERNAL_SERVER_ERROR,
599 )
tiernod985a8d2018-10-19 14:12:28 +0200600
Eduardo Sousa044f4312019-05-20 15:17:35 +0100601 if current_version == target_version:
602 return
garciadeblas4568a372021-03-24 09:19:48 +0100603
Eduardo Sousa044f4312019-05-20 15:17:35 +0100604 target_version_int = self.map_target_version_to_int[target_version]
605
606 if not current_version:
607 # create database version
608 serial = urandom(32)
609 version_data = {
garciadeblas4568a372021-03-24 09:19:48 +0100610 "_id": "version", # Always "version"
611 "version_int": 1000, # version number
612 "version": "1.0", # version text
613 "date": "2018-10-25", # version date
Eduardo Sousa044f4312019-05-20 15:17:35 +0100614 "description": "added serial", # changes in this version
garciadeblas4568a372021-03-24 09:19:48 +0100615 "status": "ENABLED", # ENABLED, DISABLED (migration in process), ERROR,
616 "serial": b64encode(serial),
Eduardo Sousa044f4312019-05-20 15:17:35 +0100617 }
618 self.db.create("admin", version_data)
619 self.db.set_secret_key(serial)
620 current_version = "1.0"
garciadeblas4568a372021-03-24 09:19:48 +0100621
622 if (
623 current_version in ("1.0", "1.1")
624 and target_version_int >= self.map_target_version_to_int["1.2"]
625 ):
626 if self.config["authentication"]["backend"] == "internal":
delacruzramo01b15d32019-07-02 14:37:47 +0200627 self.db.del_list("roles")
628
Eduardo Sousa044f4312019-05-20 15:17:35 +0100629 version_data = {
630 "_id": "version",
tierno1f029d82019-06-13 22:37:04 +0000631 "version_int": 1002,
632 "version": "1.2",
633 "date": "2019-06-11",
garciadeblas4568a372021-03-24 09:19:48 +0100634 "description": "set new format for roles_operations",
Eduardo Sousa044f4312019-05-20 15:17:35 +0100635 }
636
637 self.db.set_one("admin", {"_id": "version"}, version_data)
tierno1f029d82019-06-13 22:37:04 +0000638 current_version = "1.2"
Eduardo Sousa044f4312019-05-20 15:17:35 +0100639 # TODO add future migrations here
tiernod985a8d2018-10-19 14:12:28 +0200640
garciadeblas4568a372021-03-24 09:19:48 +0100641 def init_db(self, target_version="1.0"):
tierno4a946e42018-04-12 17:48:49 +0200642 """
tiernod985a8d2018-10-19 14:12:28 +0200643 Init database if empty. If not empty it checks that database version and migrates if needed
tierno4a946e42018-04-12 17:48:49 +0200644 If empty, it creates a new user admin/admin at 'users' and a new entry at 'version'
tiernod985a8d2018-10-19 14:12:28 +0200645 :param target_version: check desired database version. Migrate to it if possible or raises exception
tierno4a946e42018-04-12 17:48:49 +0200646 :return: None if ok, exception if error or if the version is different.
647 """
tiernod985a8d2018-10-19 14:12:28 +0200648
garciadeblas4568a372021-03-24 09:19:48 +0100649 version_data = self.db.get_one(
650 "admin", {"_id": "version"}, fail_on_empty=False, fail_on_more=True
651 )
tiernod985a8d2018-10-19 14:12:28 +0200652 # check database status is ok
garciadeblas4568a372021-03-24 09:19:48 +0100653 if version_data and version_data.get("status") != "ENABLED":
654 raise EngineException(
655 "Wrong database status '{}'".format(version_data["status"]),
656 HTTPStatus.INTERNAL_SERVER_ERROR,
657 )
tiernod985a8d2018-10-19 14:12:28 +0200658
659 # check version
660 db_version = None if not version_data else version_data.get("version")
661 if db_version != target_version:
662 self.upgrade_db(db_version, target_version)
663
tierno4a946e42018-04-12 17:48:49 +0200664 return