blob: 129f709422742a9ada7c95b55cc028219319b832 [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,
garciadeblas4568a372021-03-24 09:19:48 +010026)
garciadeblasb9f2ee72025-12-10 23:38:15 +010027from osm_common._version import version as common_version
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
Frank Bryden19b97522020-07-10 12:32:02 +0000382 def get_item_list(self, session, topic, filter_q=None, api_req=False):
tiernoc94c3df2018-02-09 15:38:54 +0100383 """
384 Get a list of items
385 :param session: contains the used login username and working project
tiernob24258a2018-10-04 18:39:49 +0200386 :param topic: it can be: users, projects, vnfds, nsds, ...
387 :param filter_q: filter of data to be applied
Frank Bryden19b97522020-07-10 12:32:02 +0000388 :param api_req: True if this call is serving an external API request. False if serving internal request.
tiernob24258a2018-10-04 18:39:49 +0200389 :return: The list, it can be empty if no one match the filter_q.
tiernoc94c3df2018-02-09 15:38:54 +0100390 """
shrinithi28d887f2025-01-08 05:27:19 +0000391 self.logger.info("it is getting into item list")
tiernob24258a2018-10-04 18:39:49 +0200392 if topic not in self.map_topic:
garciadeblasf2af4a12023-01-24 16:56:54 +0100393 raise EngineException(
394 "Unknown topic {}!!!".format(topic), HTTPStatus.INTERNAL_SERVER_ERROR
395 )
Frank Bryden19b97522020-07-10 12:32:02 +0000396 return self.map_topic[topic].list(session, filter_q, api_req)
tiernof27c79b2018-03-12 17:08:42 +0100397
shrinithi28d887f2025-01-08 05:27:19 +0000398 def get_item_list_cluster(self, session, topic, filter_q=None, api_req=False):
399 """
400 Get a list of items
401 :param session: contains the used login username and working project
402 :param topic: it can be: users, projects, vnfds, nsds, ...
403 :param filter_q: filter of data to be applied
404 :param api_req: True if this call is serving an external API request. False if serving internal request.
405 :return: The list, it can be empty if no one match the filter_q.
406 """
407 self.logger.info("it is getting into item list cluster")
408 if topic not in self.map_topic:
409 raise EngineException(
410 "Unknown topic {}!!!".format(topic), HTTPStatus.INTERNAL_SERVER_ERROR
411 )
412 return self.map_topic[topic].list_both(session, filter_q, api_req)
413
K Sai Kiran57589552021-01-27 21:38:34 +0530414 def get_item(self, session, topic, _id, filter_q=None, api_req=False):
tiernoc94c3df2018-02-09 15:38:54 +0100415 """
tiernob24258a2018-10-04 18:39:49 +0200416 Get complete information on an item
tiernoc94c3df2018-02-09 15:38:54 +0100417 :param session: contains the used login username and working project
rshri2d386cb2024-07-05 14:35:51 +0000418 :param topic: it can be: users, projects, vnfds, nsds, clusters,
tiernoc94c3df2018-02-09 15:38:54 +0100419 :param _id: server id of the item
K Sai Kiran57589552021-01-27 21:38:34 +0530420 :param filter_q: other arguments
Frank Bryden19b97522020-07-10 12:32:02 +0000421 :param api_req: True if this call is serving an external API request. False if serving internal request.
tiernoc94c3df2018-02-09 15:38:54 +0100422 :return: dictionary, raise exception if not found.
423 """
tiernob24258a2018-10-04 18:39:49 +0200424 if topic not in self.map_topic:
garciadeblasf2af4a12023-01-24 16:56:54 +0100425 raise EngineException(
426 "Unknown topic {}!!!".format(topic), HTTPStatus.INTERNAL_SERVER_ERROR
427 )
K Sai Kiran57589552021-01-27 21:38:34 +0530428 return self.map_topic[topic].show(session, _id, filter_q, api_req)
tiernoc94c3df2018-02-09 15:38:54 +0100429
rshri2d386cb2024-07-05 14:35:51 +0000430 def get_one_item(self, session, topic, _id, profile, filter_q=None, api_req=False):
431 """
432 Get complete information on an item
433 :param session: contains the used login username and working project
434 :param topic: it can be: users, projects, vnfds, nsds, clusters profile,
435 :param _id: server id of the item
436 :param profile: contains the profile type
437 :param filter_q: other arguments
438 :param api_req: True if this call is serving an external API request. False if serving internal request.
439 :return: dictionary, raise exception if not found.
440 """
441 if topic not in self.map_topic:
442 raise EngineException(
443 "Unknown topic {}!!!".format(topic), HTTPStatus.INTERNAL_SERVER_ERROR
444 )
445 return self.map_topic[topic].show_one(session, _id, profile, filter_q, api_req)
446
tierno87006042018-10-24 12:50:20 +0200447 def get_file(self, session, topic, _id, path=None, accept_header=None):
448 """
449 Get descriptor package or artifact file content
450 :param session: contains the used login username and working project
451 :param topic: it can be: users, projects, vnfds, nsds,
452 :param _id: server id of the item
453 :param path: artifact path or "$DESCRIPTOR" or None
454 :param accept_header: Content of Accept header. Must contain applition/zip or/and text/plain
455 :return: opened file plus Accept format or raises an exception
456 """
457 if topic not in self.map_topic:
garciadeblas4568a372021-03-24 09:19:48 +0100458 raise EngineException(
459 "Unknown topic {}!!!".format(topic), HTTPStatus.INTERNAL_SERVER_ERROR
460 )
tierno87006042018-10-24 12:50:20 +0200461 return self.map_topic[topic].get_file(session, _id, path, accept_header)
462
yshahd23c6a52025-06-13 05:49:31 +0000463 def get_cluster_list_ksu(self, session, topic, filter_q=None, api_req=False):
464 """
465 Get a list of items
466 :param session: contains the used login username and working project
467 :param topic: it can be: users, projects, vnfds, nsds, ...
468 :param filter_q: filter of data to be applied
469 :param api_req: True if this call is serving an external API request. False if serving internal request.
470 :return: The list, it can be empty if no one match the filter_q.
471 """
472 self.logger.info("it is getting into item list cluster")
473 if topic not in self.map_topic:
474 raise EngineException(
475 "Unknown topic {}!!!".format(topic), HTTPStatus.INTERNAL_SERVER_ERROR
476 )
477 return self.map_topic[topic].cluster_list_ksu(session, filter_q, api_req)
478
tiernob24258a2018-10-04 18:39:49 +0200479 def del_item_list(self, session, topic, _filter=None):
tiernoc94c3df2018-02-09 15:38:54 +0100480 """
481 Delete a list of items
482 :param session: contains the used login username and working project
tiernob24258a2018-10-04 18:39:49 +0200483 :param topic: it can be: users, projects, vnfds, nsds, ...
484 :param _filter: filter of data to be applied
485 :return: The deleted list, it can be empty if no one match the _filter.
tiernoc94c3df2018-02-09 15:38:54 +0100486 """
tiernob24258a2018-10-04 18:39:49 +0200487 if topic not in self.map_topic:
garciadeblas4568a372021-03-24 09:19:48 +0100488 raise EngineException(
489 "Unknown topic {}!!!".format(topic), HTTPStatus.INTERNAL_SERVER_ERROR
490 )
tierno04dbb0e2019-01-09 16:00:24 +0000491 with self.write_lock:
492 return self.map_topic[topic].delete_list(session, _filter)
tiernoc94c3df2018-02-09 15:38:54 +0100493
tiernobee3bad2019-12-05 12:26:01 +0000494 def del_item(self, session, topic, _id, not_send_msg=None):
tiernoc94c3df2018-02-09 15:38:54 +0100495 """
tiernob92094f2018-05-11 13:44:22 +0200496 Delete item by its internal id
tiernoc94c3df2018-02-09 15:38:54 +0100497 :param session: contains the used login username and working project
tiernob24258a2018-10-04 18:39:49 +0200498 :param topic: it can be: users, projects, vnfds, nsds, ...
tiernoc94c3df2018-02-09 15:38:54 +0100499 :param _id: server id of the item
tiernobee3bad2019-12-05 12:26:01 +0000500 :param not_send_msg: If False, message will not be sent to kafka.
501 If a list, message is not sent, but content is stored in this variable so that the caller can send this
502 message using its own loop. If None, message is sent
delacruzramo01b15d32019-07-02 14:37:47 +0200503 :return: dictionary with deleted item _id. It raises exception if not found.
tiernoc94c3df2018-02-09 15:38:54 +0100504 """
tiernob24258a2018-10-04 18:39:49 +0200505 if topic not in self.map_topic:
garciadeblas4568a372021-03-24 09:19:48 +0100506 raise EngineException(
507 "Unknown topic {}!!!".format(topic), HTTPStatus.INTERNAL_SERVER_ERROR
508 )
tierno04dbb0e2019-01-09 16:00:24 +0000509 with self.write_lock:
tiernobee3bad2019-12-05 12:26:01 +0000510 return self.map_topic[topic].delete(session, _id, not_send_msg=not_send_msg)
tiernoc94c3df2018-02-09 15:38:54 +0100511
rshri2d386cb2024-07-05 14:35:51 +0000512 def remove(self, session, topic, _id, not_send_msg=None):
513 """
514 Delete item by its internal id
515 :param session: contains the used login username and working project
516 :param topic: it can be: users, projects, vnfds, nsds, clusters,
517 :param _id: server id of the item
518 :param not_send_msg: If False, message will not be sent to kafka.
519 If a list, message is not sent, but content is stored in this variable so that the caller can send this
520 message using its own loop. If None, message is sent
521 :return: dictionary with deleted item _id. It raises exception if not found.
522 """
523 if topic not in self.map_topic:
524 raise EngineException(
525 "Unknown topic {}!!!".format(topic), HTTPStatus.INTERNAL_SERVER_ERROR
526 )
527 with self.write_lock:
528 return self.map_topic[topic].remove(session, _id, not_send_msg=not_send_msg)
529
tierno65ca36d2019-02-12 19:27:52 +0100530 def edit_item(self, session, topic, _id, indata=None, kwargs=None):
tiernob24258a2018-10-04 18:39:49 +0200531 """
532 Update an existing entry at database
533 :param session: contains the used login username and working project
534 :param topic: it can be: users, projects, vnfds, nsds, ...
535 :param _id: identifier to be updated
536 :param indata: data to be inserted
537 :param kwargs: used to override the indata descriptor
delacruzramo01b15d32019-07-02 14:37:47 +0200538 :return: dictionary with edited item _id, raise exception if not found.
tiernob24258a2018-10-04 18:39:49 +0200539 """
540 if topic not in self.map_topic:
garciadeblas4568a372021-03-24 09:19:48 +0100541 raise EngineException(
542 "Unknown topic {}!!!".format(topic), HTTPStatus.INTERNAL_SERVER_ERROR
543 )
tierno04dbb0e2019-01-09 16:00:24 +0000544 with self.write_lock:
tierno65ca36d2019-02-12 19:27:52 +0100545 return self.map_topic[topic].edit(session, _id, indata, kwargs)
tiernoc94c3df2018-02-09 15:38:54 +0100546
rshri2d386cb2024-07-05 14:35:51 +0000547 def edit(self, session, topic, _id, item, indata=None, kwargs=None):
548 """
549 Update an existing entry at database
550 :param session: contains the used login username and working project
551 :param topic: it can be: users, projects, vnfds, nsds, ...
552 :param _id: identifier to be updated
553 :param item: it shows the type of profiles
554 :param indata: data to be inserted
555 :param kwargs: used to override the indata descriptor
556 :return: dictionary with edited item _id, raise exception if not found.
557 """
558 if topic not in self.map_topic:
559 raise EngineException(
560 "Unknown topic {}!!!".format(topic), HTTPStatus.INTERNAL_SERVER_ERROR
561 )
562 with self.write_lock:
563 return self.map_topic[topic].edit(session, _id, item, indata, kwargs)
564
Gabriel Cuba84a60df2023-10-30 14:01:54 -0500565 def cancel_item(
566 self, rollback, session, topic, indata=None, kwargs=None, headers=None
567 ):
568 """
569 Cancels an item
570 :param rollback: list to append created items at database in case a rollback must to be done
571 :param session: contains the used login username and working project, force to avoid checkins, public
572 :param topic: it can be: users, projects, vim_accounts, sdns, nsrs, nsds, vnfds
573 :param indata: data to be inserted
574 :param kwargs: used to override the indata descriptor
575 :param headers: http request headers
576 :return: _id: identity of the inserted data.
577 """
578 if topic not in self.map_topic:
579 raise EngineException(
580 "Unknown topic {}!!!".format(topic), HTTPStatus.INTERNAL_SERVER_ERROR
581 )
582 with self.write_lock:
583 self.map_topic[topic].cancel(rollback, session, indata, kwargs, headers)
584
tiernod985a8d2018-10-19 14:12:28 +0200585 def upgrade_db(self, current_version, target_version):
Eduardo Sousa044f4312019-05-20 15:17:35 +0100586 if target_version not in self.map_target_version_to_int.keys():
garciadeblas4568a372021-03-24 09:19:48 +0100587 raise EngineException(
588 "Cannot upgrade to version '{}' with this version of code".format(
589 target_version
590 ),
591 http_code=HTTPStatus.INTERNAL_SERVER_ERROR,
592 )
tiernod985a8d2018-10-19 14:12:28 +0200593
Eduardo Sousa044f4312019-05-20 15:17:35 +0100594 if current_version == target_version:
595 return
garciadeblas4568a372021-03-24 09:19:48 +0100596
Eduardo Sousa044f4312019-05-20 15:17:35 +0100597 target_version_int = self.map_target_version_to_int[target_version]
598
599 if not current_version:
600 # create database version
601 serial = urandom(32)
602 version_data = {
garciadeblas4568a372021-03-24 09:19:48 +0100603 "_id": "version", # Always "version"
604 "version_int": 1000, # version number
605 "version": "1.0", # version text
606 "date": "2018-10-25", # version date
Eduardo Sousa044f4312019-05-20 15:17:35 +0100607 "description": "added serial", # changes in this version
garciadeblas4568a372021-03-24 09:19:48 +0100608 "status": "ENABLED", # ENABLED, DISABLED (migration in process), ERROR,
609 "serial": b64encode(serial),
Eduardo Sousa044f4312019-05-20 15:17:35 +0100610 }
611 self.db.create("admin", version_data)
612 self.db.set_secret_key(serial)
613 current_version = "1.0"
garciadeblas4568a372021-03-24 09:19:48 +0100614
615 if (
616 current_version in ("1.0", "1.1")
617 and target_version_int >= self.map_target_version_to_int["1.2"]
618 ):
619 if self.config["authentication"]["backend"] == "internal":
delacruzramo01b15d32019-07-02 14:37:47 +0200620 self.db.del_list("roles")
621
Eduardo Sousa044f4312019-05-20 15:17:35 +0100622 version_data = {
623 "_id": "version",
tierno1f029d82019-06-13 22:37:04 +0000624 "version_int": 1002,
625 "version": "1.2",
626 "date": "2019-06-11",
garciadeblas4568a372021-03-24 09:19:48 +0100627 "description": "set new format for roles_operations",
Eduardo Sousa044f4312019-05-20 15:17:35 +0100628 }
629
630 self.db.set_one("admin", {"_id": "version"}, version_data)
tierno1f029d82019-06-13 22:37:04 +0000631 current_version = "1.2"
Eduardo Sousa044f4312019-05-20 15:17:35 +0100632 # TODO add future migrations here
tiernod985a8d2018-10-19 14:12:28 +0200633
garciadeblas4568a372021-03-24 09:19:48 +0100634 def init_db(self, target_version="1.0"):
tierno4a946e42018-04-12 17:48:49 +0200635 """
tiernod985a8d2018-10-19 14:12:28 +0200636 Init database if empty. If not empty it checks that database version and migrates if needed
tierno4a946e42018-04-12 17:48:49 +0200637 If empty, it creates a new user admin/admin at 'users' and a new entry at 'version'
tiernod985a8d2018-10-19 14:12:28 +0200638 :param target_version: check desired database version. Migrate to it if possible or raises exception
tierno4a946e42018-04-12 17:48:49 +0200639 :return: None if ok, exception if error or if the version is different.
640 """
tiernod985a8d2018-10-19 14:12:28 +0200641
garciadeblas4568a372021-03-24 09:19:48 +0100642 version_data = self.db.get_one(
643 "admin", {"_id": "version"}, fail_on_empty=False, fail_on_more=True
644 )
tiernod985a8d2018-10-19 14:12:28 +0200645 # check database status is ok
garciadeblas4568a372021-03-24 09:19:48 +0100646 if version_data and version_data.get("status") != "ENABLED":
647 raise EngineException(
648 "Wrong database status '{}'".format(version_data["status"]),
649 HTTPStatus.INTERNAL_SERVER_ERROR,
650 )
tiernod985a8d2018-10-19 14:12:28 +0200651
652 # check version
653 db_version = None if not version_data else version_data.get("version")
654 if db_version != target_version:
655 self.upgrade_db(db_version, target_version)
656
tierno4a946e42018-04-12 17:48:49 +0200657 return