blob: ffbb07dc247658c01a6c452a8c5eaf9f2b31d093 [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,
60 AppTopic,
61 ResourceTopic,
shrinithi28d887f2025-01-08 05:27:19 +000062 ClusterOpsTopic,
yshah53cc9eb2024-07-05 13:06:31 +000063 KsusTopic,
64 OkaTopic,
yshahd23c6a52025-06-13 05:49:31 +000065 NodeGroupTopic,
rshri2d386cb2024-07-05 14:35:51 +000066)
almagiae47b9132022-05-17 14:12:22 +020067from osm_nbi.vnf_instance_topics import VnfInstances, VnfLcmOpTopic
tierno23acf402019-08-28 13:36:34 +000068from osm_nbi.pmjobs_topics import PmJobsTopic
preethika.p329b8182020-04-22 12:25:39 +053069from osm_nbi.subscription_topics import NslcmSubscriptionsTopic
selvi.jf1004592022-04-29 05:42:35 +000070from osm_nbi.osm_vnfm.vnf_subscription import VnflcmSubscriptionsTopic
tiernod985a8d2018-10-19 14:12:28 +020071from base64 import b64encode
garciadeblas4568a372021-03-24 09:19:48 +010072from os import urandom # , path
tierno04dbb0e2019-01-09 16:00:24 +000073from threading import Lock
tiernoc94c3df2018-02-09 15:38:54 +010074
75__author__ = "Alfonso Tierno <alfonso.tiernosepulveda@telefonica.com>"
tierno932499c2019-01-28 17:28:10 +000076min_common_version = "0.1.16"
tierno441dbbf2018-07-10 12:52:48 +020077
78
tiernoc94c3df2018-02-09 15:38:54 +010079class Engine(object):
tiernob24258a2018-10-04 18:39:49 +020080 map_from_topic_to_class = {
81 "vnfds": VnfdTopic,
82 "nsds": NsdTopic,
Felipe Vicensb57758d2018-10-16 16:00:20 +020083 "nsts": NstTopic,
tiernob24258a2018-10-04 18:39:49 +020084 "pdus": PduTopic,
85 "nsrs": NsrTopic,
86 "vnfrs": VnfrTopic,
87 "nslcmops": NsLcmOpTopic,
88 "vim_accounts": VimAccountTopic,
tierno55ba2e62018-12-11 17:22:22 +000089 "wim_accounts": WimAccountTopic,
tiernob24258a2018-10-04 18:39:49 +020090 "sdns": SdnTopic,
delacruzramofe598fe2019-10-23 18:25:11 +020091 "k8sclusters": K8sClusterTopic,
David Garciaecb41322021-03-31 19:10:46 +020092 "vca": VcaTopic,
delacruzramofe598fe2019-10-23 18:25:11 +020093 "k8srepos": K8sRepoTopic,
Felipe Vicensb66b0412020-05-06 10:11:00 +020094 "osmrepos": OsmRepoTopic,
garciadeblas4568a372021-03-24 09:19:48 +010095 "users": UserTopicAuth, # Valid for both internal and keystone authentication backends
96 "projects": ProjectTopicAuth, # Valid for both internal and keystone authentication backends
97 "roles": RoleTopicAuth, # Valid for both internal and keystone authentication backends
Felipe Vicensb57758d2018-10-16 16:00:20 +020098 "nsis": NsiTopic,
delacruzramo271d2002019-12-02 21:00:37 +010099 "nsilcmops": NsiLcmOpTopic,
100 "vnfpkgops": VnfPkgOpTopic,
preethika.p329b8182020-04-22 12:25:39 +0530101 "nslcm_subscriptions": NslcmSubscriptionsTopic,
almagiae47b9132022-05-17 14:12:22 +0200102 "vnf_instances": VnfInstances,
103 "vnflcmops": VnfLcmOpTopic,
selvi.jf1004592022-04-29 05:42:35 +0000104 "vnflcm_subscriptions": VnflcmSubscriptionsTopic,
kayal2001f71c2e82024-06-25 15:26:24 +0530105 "nsconfigtemps": NsConfigTemplateTopic,
shrinithi28d887f2025-01-08 05:27:19 +0000106 "cluster": ClusterTopic,
rshri2d386cb2024-07-05 14:35:51 +0000107 "infras_cont": InfraContTopic,
108 "infras_conf": InfraConfTopic,
109 "apps": AppTopic,
110 "resources": ResourceTopic,
shrinithi28d887f2025-01-08 05:27:19 +0000111 "clusterops": ClusterOpsTopic,
yshah53cc9eb2024-07-05 13:06:31 +0000112 "ksus": KsusTopic,
113 "oka_packages": OkaTopic,
yshahd23c6a52025-06-13 05:49:31 +0000114 "node_groups": NodeGroupTopic,
tiernob24258a2018-10-04 18:39:49 +0200115 # [NEW_TOPIC]: add an entry here
vijay.r35ef2f72019-04-30 17:55:49 +0530116 # "pm_jobs": PmJobsTopic will be added manually because it needs other parameters
tiernob24258a2018-10-04 18:39:49 +0200117 }
tiernoc94c3df2018-02-09 15:38:54 +0100118
Eduardo Sousa044f4312019-05-20 15:17:35 +0100119 map_target_version_to_int = {
120 "1.0": 1000,
tierno1f029d82019-06-13 22:37:04 +0000121 "1.1": 1001,
122 "1.2": 1002,
Eduardo Sousa044f4312019-05-20 15:17:35 +0100123 # Add new versions here
124 }
125
delacruzramoad682a52019-12-10 16:26:34 +0100126 def __init__(self, authenticator):
tiernoc94c3df2018-02-09 15:38:54 +0100127 self.db = None
128 self.fs = None
129 self.msg = None
delacruzramoad682a52019-12-10 16:26:34 +0100130 self.authconn = None
tiernoc94c3df2018-02-09 15:38:54 +0100131 self.config = None
tierno9e87a7f2020-03-23 09:24:10 +0000132 # self.operations = None
tiernoc94c3df2018-02-09 15:38:54 +0100133 self.logger = logging.getLogger("nbi.engine")
tiernob24258a2018-10-04 18:39:49 +0200134 self.map_topic = {}
tierno04dbb0e2019-01-09 16:00:24 +0000135 self.write_lock = None
delacruzramoad682a52019-12-10 16:26:34 +0100136 # self.token_cache = token_cache
137 self.authenticator = authenticator
tiernoc94c3df2018-02-09 15:38:54 +0100138
139 def start(self, config):
140 """
141 Connect to database, filesystem storage, and messaging
142 :param config: two level dictionary with configuration. Top level should contain 'database', 'storage',
143 :return: None
144 """
145 self.config = config
tiernob24258a2018-10-04 18:39:49 +0200146 # check right version of common
147 if versiontuple(common_version) < versiontuple(min_common_version):
garciadeblas4568a372021-03-24 09:19:48 +0100148 raise EngineException(
149 "Not compatible osm/common version '{}'. Needed '{}' or higher".format(
150 common_version, min_common_version
151 )
152 )
tiernob24258a2018-10-04 18:39:49 +0200153
tiernoc94c3df2018-02-09 15:38:54 +0100154 try:
155 if not self.db:
156 if config["database"]["driver"] == "mongo":
157 self.db = dbmongo.DbMongo()
158 self.db.db_connect(config["database"])
159 elif config["database"]["driver"] == "memory":
160 self.db = dbmemory.DbMemory()
161 self.db.db_connect(config["database"])
162 else:
garciadeblas4568a372021-03-24 09:19:48 +0100163 raise EngineException(
164 "Invalid configuration param '{}' at '[database]':'driver'".format(
165 config["database"]["driver"]
166 )
167 )
tiernoc94c3df2018-02-09 15:38:54 +0100168 if not self.fs:
169 if config["storage"]["driver"] == "local":
170 self.fs = fslocal.FsLocal()
171 self.fs.fs_connect(config["storage"])
Eduardo Sousa7e0eb132019-06-21 11:50:21 +0100172 elif config["storage"]["driver"] == "mongo":
173 self.fs = fsmongo.FsMongo()
174 self.fs.fs_connect(config["storage"])
tiernoc94c3df2018-02-09 15:38:54 +0100175 else:
garciadeblas4568a372021-03-24 09:19:48 +0100176 raise EngineException(
177 "Invalid configuration param '{}' at '[storage]':'driver'".format(
178 config["storage"]["driver"]
179 )
180 )
tiernoc94c3df2018-02-09 15:38:54 +0100181 if not self.msg:
182 if config["message"]["driver"] == "local":
183 self.msg = msglocal.MsgLocal()
184 self.msg.connect(config["message"])
185 elif config["message"]["driver"] == "kafka":
186 self.msg = msgkafka.MsgKafka()
187 self.msg.connect(config["message"])
188 else:
garciadeblas4568a372021-03-24 09:19:48 +0100189 raise EngineException(
190 "Invalid configuration param '{}' at '[message]':'driver'".format(
191 config["message"]["driver"]
192 )
193 )
delacruzramoad682a52019-12-10 16:26:34 +0100194 if not self.authconn:
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100195 if config["authentication"]["backend"] == "keystone":
garciadeblas4568a372021-03-24 09:19:48 +0100196 self.authconn = AuthconnKeystone(
197 config["authentication"],
198 self.db,
199 self.authenticator.role_permissions,
200 )
K Sai Kiran7ddb0732020-10-30 11:14:44 +0530201 elif config["authentication"]["backend"] == "tacacs":
garciadeblas4568a372021-03-24 09:19:48 +0100202 self.authconn = AuthconnTacacs(
203 config["authentication"],
204 self.db,
205 self.authenticator.role_permissions,
206 )
delacruzramoceb8baf2019-06-21 14:25:38 +0200207 else:
garciadeblas4568a372021-03-24 09:19:48 +0100208 self.authconn = AuthconnInternal(
209 config["authentication"],
210 self.db,
211 self.authenticator.role_permissions,
212 )
tierno9e87a7f2020-03-23 09:24:10 +0000213 # if not self.operations:
214 # if "resources_to_operations" in config["rbac"]:
215 # resources_to_operations_file = config["rbac"]["resources_to_operations"]
216 # else:
217 # possible_paths = (
218 # __file__[:__file__.rfind("engine.py")] + "resources_to_operations.yml",
219 # "./resources_to_operations.yml"
220 # )
221 # for config_file in possible_paths:
222 # if path.isfile(config_file):
223 # resources_to_operations_file = config_file
224 # break
225 # if not resources_to_operations_file:
226 # raise EngineException("Invalid permission configuration:"
227 # "resources_to_operations file missing")
228 #
229 # with open(resources_to_operations_file, 'r') as f:
garciadeblas4cd875d2023-02-14 19:05:34 +0100230 # resources_to_operations = yaml.safeload(f)
tierno9e87a7f2020-03-23 09:24:10 +0000231 #
232 # self.operations = []
233 #
234 # for _, value in resources_to_operations["resources_to_operations"].items():
235 # if value not in self.operations:
236 # self.operations += [value]
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100237
tierno04dbb0e2019-01-09 16:00:24 +0000238 self.write_lock = Lock()
tiernob24258a2018-10-04 18:39:49 +0200239 # create one class per topic
240 for topic, topic_class in self.map_from_topic_to_class.items():
delacruzramo32bab472019-09-13 12:24:22 +0200241 # if self.auth and topic_class in (UserTopicAuth, ProjectTopicAuth):
242 # self.map_topic[topic] = topic_class(self.db, self.fs, self.msg, self.auth)
garciadeblas4568a372021-03-24 09:19:48 +0100243 self.map_topic[topic] = topic_class(
244 self.db, self.fs, self.msg, self.authconn
245 )
246
247 self.map_topic["pm_jobs"] = PmJobsTopic(
248 self.db,
249 config["prometheus"].get("host"),
250 config["prometheus"].get("port"),
251 )
tiernoc94c3df2018-02-09 15:38:54 +0100252 except (DbException, FsException, MsgException) as e:
253 raise EngineException(str(e), http_code=e.http_code)
254
255 def stop(self):
256 try:
257 if self.db:
258 self.db.db_disconnect()
259 if self.fs:
260 self.fs.fs_disconnect()
tierno932499c2019-01-28 17:28:10 +0000261 if self.msg:
262 self.msg.disconnect()
tierno04dbb0e2019-01-09 16:00:24 +0000263 self.write_lock = None
tiernoc94c3df2018-02-09 15:38:54 +0100264 except (DbException, FsException, MsgException) as e:
265 raise EngineException(str(e), http_code=e.http_code)
266
garciadeblas4568a372021-03-24 09:19:48 +0100267 def new_item(
268 self, rollback, session, topic, indata=None, kwargs=None, headers=None
269 ):
tiernoc94c3df2018-02-09 15:38:54 +0100270 """
tiernof27c79b2018-03-12 17:08:42 +0100271 Creates a new entry into database. For nsds and vnfds it creates an almost empty DISABLED entry,
272 that must be completed with a call to method upload_content
tiernob24258a2018-10-04 18:39:49 +0200273 :param rollback: list to append created items at database in case a rollback must to be done
tierno65ca36d2019-02-12 19:27:52 +0100274 :param session: contains the used login username and working project, force to avoid checkins, public
tiernob24258a2018-10-04 18:39:49 +0200275 :param topic: it can be: users, projects, vim_accounts, sdns, nsrs, nsds, vnfds
tiernoc94c3df2018-02-09 15:38:54 +0100276 :param indata: data to be inserted
277 :param kwargs: used to override the indata descriptor
278 :param headers: http request headers
tierno0ffaa992018-05-09 13:21:56 +0200279 :return: _id: identity of the inserted data.
tiernoc94c3df2018-02-09 15:38:54 +0100280 """
tiernob24258a2018-10-04 18:39:49 +0200281 if topic not in self.map_topic:
garciadeblas4568a372021-03-24 09:19:48 +0100282 raise EngineException(
283 "Unknown topic {}!!!".format(topic), HTTPStatus.INTERNAL_SERVER_ERROR
284 )
tierno04dbb0e2019-01-09 16:00:24 +0000285 with self.write_lock:
tierno65ca36d2019-02-12 19:27:52 +0100286 return self.map_topic[topic].new(rollback, session, indata, kwargs, headers)
tiernoc94c3df2018-02-09 15:38:54 +0100287
rshri2d386cb2024-07-05 14:35:51 +0000288 def add_item(
289 self, rollback, session, topic, indata=None, kwargs=None, headers=None
290 ):
291 """
292 register a cluster in the database.
293 :param rollback: list to append created items at database in case a rollback must to be done
294 :param session: contains the used login username and working project, force to avoid checkins, public
295 :param topic: it can be: cluster for adding cluster into database
296 :param indata: data to be inserted
297 :param kwargs: used to override the indata descriptor
298 :param headers: http request headers
299 :return: _id: identity of the inserted data.
300 """
301 if topic not in self.map_topic:
302 raise EngineException(
303 "Unknown topic {}!!!".format(topic), HTTPStatus.INTERNAL_SERVER_ERROR
304 )
305 with self.write_lock:
306 return self.map_topic[topic].add(rollback, session, indata, kwargs, headers)
307
tierno65ca36d2019-02-12 19:27:52 +0100308 def upload_content(self, session, topic, _id, indata, kwargs, headers):
tierno65acb4d2018-04-06 16:42:40 +0200309 """
tiernob24258a2018-10-04 18:39:49 +0200310 Upload content for an already created entry (_id)
tierno65acb4d2018-04-06 16:42:40 +0200311 :param session: contains the used login username and working project
tiernob24258a2018-10-04 18:39:49 +0200312 :param topic: it can be: users, projects, vnfds, nsds,
313 :param _id: server id of the item
314 :param indata: data to be inserted
tierno65acb4d2018-04-06 16:42:40 +0200315 :param kwargs: used to override the indata descriptor
tiernob24258a2018-10-04 18:39:49 +0200316 :param headers: http request headers
tiernob24258a2018-10-04 18:39:49 +0200317 :return: _id: identity of the inserted data.
tierno65acb4d2018-04-06 16:42:40 +0200318 """
tiernob24258a2018-10-04 18:39:49 +0200319 if topic not in self.map_topic:
garciadeblas4568a372021-03-24 09:19:48 +0100320 raise EngineException(
321 "Unknown topic {}!!!".format(topic), HTTPStatus.INTERNAL_SERVER_ERROR
322 )
tierno04dbb0e2019-01-09 16:00:24 +0000323 with self.write_lock:
garciadeblas4568a372021-03-24 09:19:48 +0100324 return self.map_topic[topic].upload_content(
325 session, _id, indata, kwargs, headers
326 )
tiernoc94c3df2018-02-09 15:38:54 +0100327
yshah53cc9eb2024-07-05 13:06:31 +0000328 def clone(
329 self, rollback, session, topic, _id, indata=None, kwargs=None, headers=None
330 ):
331 if topic not in self.map_topic:
332 raise EngineException(
333 "Unknown topic {}!!!".format(topic), HTTPStatus.INTERNAL_SERVER_ERROR
334 )
335 with self.write_lock:
336 return self.map_topic[topic].clone(
337 rollback, session, _id, indata, kwargs, headers
338 )
339
340 def move_ksu(self, session, topic, _id, indata=None, kwargs=None):
341 if topic not in self.map_topic:
342 raise EngineException(
343 "Unknown topic {}!!!".format(topic), HTTPStatus.INTERNAL_SERVER_ERROR
344 )
345
346 with self.write_lock:
347 return self.map_topic[topic].move_ksu(session, _id, indata, kwargs)
348
shahithyab9eb4142024-10-17 05:51:39 +0000349 def get_cluster_creds_file(self, session, topic, _id, item, op_id):
yshah53cc9eb2024-07-05 13:06:31 +0000350 if topic not in self.map_topic:
351 raise EngineException(
352 "Unknown topic {}!!!".format(topic), HTTPStatus.INTERNAL_SERVER_ERROR
353 )
shahithyab9eb4142024-10-17 05:51:39 +0000354 return self.map_topic[topic].get_cluster_creds_file(session, _id, item, op_id)
355
356 def get_cluster_creds(self, session, topic, _id, item):
357 if topic not in self.map_topic:
358 raise EngineException(
359 "Unknown topic {}!!!".format(topic), HTTPStatus.INTERNAL_SERVER_ERROR
360 )
361 return self.map_topic[topic].get_cluster_creds(session, _id, item)
yshah53cc9eb2024-07-05 13:06:31 +0000362
yshahd23c6a52025-06-13 05:49:31 +0000363 def update_item(self, session, topic, _id, item, indata):
yshah53cc9eb2024-07-05 13:06:31 +0000364 if topic not in self.map_topic:
365 raise EngineException(
366 "Unknown topic {}!!!".format(topic), HTTPStatus.INTERNAL_SERVER_ERROR
367 )
yshahd23c6a52025-06-13 05:49:31 +0000368 return self.map_topic[topic].update_item(session, _id, item, indata)
yshah53cc9eb2024-07-05 13:06:31 +0000369
370 def delete_ksu(self, session, topic, _id, indata):
371 if topic not in self.map_topic:
372 raise EngineException(
373 "Unknown topic {}!!!".format(topic), HTTPStatus.INTERNAL_SERVER_ERROR
374 )
375 with self.write_lock:
376 return self.map_topic[topic].delete_ksu(
377 session, _id, indata, not_send_msg=None
378 )
379
Frank Bryden19b97522020-07-10 12:32:02 +0000380 def get_item_list(self, session, topic, filter_q=None, api_req=False):
tiernoc94c3df2018-02-09 15:38:54 +0100381 """
382 Get a list of items
383 :param session: contains the used login username and working project
tiernob24258a2018-10-04 18:39:49 +0200384 :param topic: it can be: users, projects, vnfds, nsds, ...
385 :param filter_q: filter of data to be applied
Frank Bryden19b97522020-07-10 12:32:02 +0000386 :param api_req: True if this call is serving an external API request. False if serving internal request.
tiernob24258a2018-10-04 18:39:49 +0200387 :return: The list, it can be empty if no one match the filter_q.
tiernoc94c3df2018-02-09 15:38:54 +0100388 """
shrinithi28d887f2025-01-08 05:27:19 +0000389 self.logger.info("it is getting into item list")
tiernob24258a2018-10-04 18:39:49 +0200390 if topic not in self.map_topic:
garciadeblasf2af4a12023-01-24 16:56:54 +0100391 raise EngineException(
392 "Unknown topic {}!!!".format(topic), HTTPStatus.INTERNAL_SERVER_ERROR
393 )
Frank Bryden19b97522020-07-10 12:32:02 +0000394 return self.map_topic[topic].list(session, filter_q, api_req)
tiernof27c79b2018-03-12 17:08:42 +0100395
shrinithi28d887f2025-01-08 05:27:19 +0000396 def get_item_list_cluster(self, session, topic, filter_q=None, api_req=False):
397 """
398 Get a list of items
399 :param session: contains the used login username and working project
400 :param topic: it can be: users, projects, vnfds, nsds, ...
401 :param filter_q: filter of data to be applied
402 :param api_req: True if this call is serving an external API request. False if serving internal request.
403 :return: The list, it can be empty if no one match the filter_q.
404 """
405 self.logger.info("it is getting into item list cluster")
406 if topic not in self.map_topic:
407 raise EngineException(
408 "Unknown topic {}!!!".format(topic), HTTPStatus.INTERNAL_SERVER_ERROR
409 )
410 return self.map_topic[topic].list_both(session, filter_q, api_req)
411
K Sai Kiran57589552021-01-27 21:38:34 +0530412 def get_item(self, session, topic, _id, filter_q=None, api_req=False):
tiernoc94c3df2018-02-09 15:38:54 +0100413 """
tiernob24258a2018-10-04 18:39:49 +0200414 Get complete information on an item
tiernoc94c3df2018-02-09 15:38:54 +0100415 :param session: contains the used login username and working project
rshri2d386cb2024-07-05 14:35:51 +0000416 :param topic: it can be: users, projects, vnfds, nsds, clusters,
tiernoc94c3df2018-02-09 15:38:54 +0100417 :param _id: server id of the item
K Sai Kiran57589552021-01-27 21:38:34 +0530418 :param filter_q: other arguments
Frank Bryden19b97522020-07-10 12:32:02 +0000419 :param api_req: True if this call is serving an external API request. False if serving internal request.
tiernoc94c3df2018-02-09 15:38:54 +0100420 :return: dictionary, raise exception if not found.
421 """
tiernob24258a2018-10-04 18:39:49 +0200422 if topic not in self.map_topic:
garciadeblasf2af4a12023-01-24 16:56:54 +0100423 raise EngineException(
424 "Unknown topic {}!!!".format(topic), HTTPStatus.INTERNAL_SERVER_ERROR
425 )
K Sai Kiran57589552021-01-27 21:38:34 +0530426 return self.map_topic[topic].show(session, _id, filter_q, api_req)
tiernoc94c3df2018-02-09 15:38:54 +0100427
rshri2d386cb2024-07-05 14:35:51 +0000428 def get_one_item(self, session, topic, _id, profile, filter_q=None, api_req=False):
429 """
430 Get complete information on an item
431 :param session: contains the used login username and working project
432 :param topic: it can be: users, projects, vnfds, nsds, clusters profile,
433 :param _id: server id of the item
434 :param profile: contains the profile type
435 :param filter_q: other arguments
436 :param api_req: True if this call is serving an external API request. False if serving internal request.
437 :return: dictionary, raise exception if not found.
438 """
439 if topic not in self.map_topic:
440 raise EngineException(
441 "Unknown topic {}!!!".format(topic), HTTPStatus.INTERNAL_SERVER_ERROR
442 )
443 return self.map_topic[topic].show_one(session, _id, profile, filter_q, api_req)
444
tierno87006042018-10-24 12:50:20 +0200445 def get_file(self, session, topic, _id, path=None, accept_header=None):
446 """
447 Get descriptor package or artifact file content
448 :param session: contains the used login username and working project
449 :param topic: it can be: users, projects, vnfds, nsds,
450 :param _id: server id of the item
451 :param path: artifact path or "$DESCRIPTOR" or None
452 :param accept_header: Content of Accept header. Must contain applition/zip or/and text/plain
453 :return: opened file plus Accept format or raises an exception
454 """
455 if topic not in self.map_topic:
garciadeblas4568a372021-03-24 09:19:48 +0100456 raise EngineException(
457 "Unknown topic {}!!!".format(topic), HTTPStatus.INTERNAL_SERVER_ERROR
458 )
tierno87006042018-10-24 12:50:20 +0200459 return self.map_topic[topic].get_file(session, _id, path, accept_header)
460
yshahd23c6a52025-06-13 05:49:31 +0000461 def get_cluster_list_ksu(self, session, topic, filter_q=None, api_req=False):
462 """
463 Get a list of items
464 :param session: contains the used login username and working project
465 :param topic: it can be: users, projects, vnfds, nsds, ...
466 :param filter_q: filter of data to be applied
467 :param api_req: True if this call is serving an external API request. False if serving internal request.
468 :return: The list, it can be empty if no one match the filter_q.
469 """
470 self.logger.info("it is getting into item list cluster")
471 if topic not in self.map_topic:
472 raise EngineException(
473 "Unknown topic {}!!!".format(topic), HTTPStatus.INTERNAL_SERVER_ERROR
474 )
475 return self.map_topic[topic].cluster_list_ksu(session, filter_q, api_req)
476
tiernob24258a2018-10-04 18:39:49 +0200477 def del_item_list(self, session, topic, _filter=None):
tiernoc94c3df2018-02-09 15:38:54 +0100478 """
479 Delete a list of items
480 :param session: contains the used login username and working project
tiernob24258a2018-10-04 18:39:49 +0200481 :param topic: it can be: users, projects, vnfds, nsds, ...
482 :param _filter: filter of data to be applied
483 :return: The deleted list, it can be empty if no one match the _filter.
tiernoc94c3df2018-02-09 15:38:54 +0100484 """
tiernob24258a2018-10-04 18:39:49 +0200485 if topic not in self.map_topic:
garciadeblas4568a372021-03-24 09:19:48 +0100486 raise EngineException(
487 "Unknown topic {}!!!".format(topic), HTTPStatus.INTERNAL_SERVER_ERROR
488 )
tierno04dbb0e2019-01-09 16:00:24 +0000489 with self.write_lock:
490 return self.map_topic[topic].delete_list(session, _filter)
tiernoc94c3df2018-02-09 15:38:54 +0100491
tiernobee3bad2019-12-05 12:26:01 +0000492 def del_item(self, session, topic, _id, not_send_msg=None):
tiernoc94c3df2018-02-09 15:38:54 +0100493 """
tiernob92094f2018-05-11 13:44:22 +0200494 Delete item by its internal id
tiernoc94c3df2018-02-09 15:38:54 +0100495 :param session: contains the used login username and working project
tiernob24258a2018-10-04 18:39:49 +0200496 :param topic: it can be: users, projects, vnfds, nsds, ...
tiernoc94c3df2018-02-09 15:38:54 +0100497 :param _id: server id of the item
tiernobee3bad2019-12-05 12:26:01 +0000498 :param not_send_msg: If False, message will not be sent to kafka.
499 If a list, message is not sent, but content is stored in this variable so that the caller can send this
500 message using its own loop. If None, message is sent
delacruzramo01b15d32019-07-02 14:37:47 +0200501 :return: dictionary with deleted item _id. It raises exception if not found.
tiernoc94c3df2018-02-09 15:38:54 +0100502 """
tiernob24258a2018-10-04 18:39:49 +0200503 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:
tiernobee3bad2019-12-05 12:26:01 +0000508 return self.map_topic[topic].delete(session, _id, not_send_msg=not_send_msg)
tiernoc94c3df2018-02-09 15:38:54 +0100509
rshri2d386cb2024-07-05 14:35:51 +0000510 def remove(self, session, topic, _id, not_send_msg=None):
511 """
512 Delete item by its internal id
513 :param session: contains the used login username and working project
514 :param topic: it can be: users, projects, vnfds, nsds, clusters,
515 :param _id: server id of the item
516 :param not_send_msg: If False, message will not be sent to kafka.
517 If a list, message is not sent, but content is stored in this variable so that the caller can send this
518 message using its own loop. If None, message is sent
519 :return: dictionary with deleted item _id. It raises 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].remove(session, _id, not_send_msg=not_send_msg)
527
tierno65ca36d2019-02-12 19:27:52 +0100528 def edit_item(self, session, topic, _id, indata=None, kwargs=None):
tiernob24258a2018-10-04 18:39:49 +0200529 """
530 Update an existing entry at database
531 :param session: contains the used login username and working project
532 :param topic: it can be: users, projects, vnfds, nsds, ...
533 :param _id: identifier to be updated
534 :param indata: data to be inserted
535 :param kwargs: used to override the indata descriptor
delacruzramo01b15d32019-07-02 14:37:47 +0200536 :return: dictionary with edited item _id, raise exception if not found.
tiernob24258a2018-10-04 18:39:49 +0200537 """
538 if topic not in self.map_topic:
garciadeblas4568a372021-03-24 09:19:48 +0100539 raise EngineException(
540 "Unknown topic {}!!!".format(topic), HTTPStatus.INTERNAL_SERVER_ERROR
541 )
tierno04dbb0e2019-01-09 16:00:24 +0000542 with self.write_lock:
tierno65ca36d2019-02-12 19:27:52 +0100543 return self.map_topic[topic].edit(session, _id, indata, kwargs)
tiernoc94c3df2018-02-09 15:38:54 +0100544
rshri2d386cb2024-07-05 14:35:51 +0000545 def edit(self, session, topic, _id, item, indata=None, kwargs=None):
546 """
547 Update an existing entry at database
548 :param session: contains the used login username and working project
549 :param topic: it can be: users, projects, vnfds, nsds, ...
550 :param _id: identifier to be updated
551 :param item: it shows the type of profiles
552 :param indata: data to be inserted
553 :param kwargs: used to override the indata descriptor
554 :return: dictionary with edited item _id, raise exception if not found.
555 """
556 if topic not in self.map_topic:
557 raise EngineException(
558 "Unknown topic {}!!!".format(topic), HTTPStatus.INTERNAL_SERVER_ERROR
559 )
560 with self.write_lock:
561 return self.map_topic[topic].edit(session, _id, item, indata, kwargs)
562
Gabriel Cuba84a60df2023-10-30 14:01:54 -0500563 def cancel_item(
564 self, rollback, session, topic, indata=None, kwargs=None, headers=None
565 ):
566 """
567 Cancels an item
568 :param rollback: list to append created items at database in case a rollback must to be done
569 :param session: contains the used login username and working project, force to avoid checkins, public
570 :param topic: it can be: users, projects, vim_accounts, sdns, nsrs, nsds, vnfds
571 :param indata: data to be inserted
572 :param kwargs: used to override the indata descriptor
573 :param headers: http request headers
574 :return: _id: identity of the inserted data.
575 """
576 if topic not in self.map_topic:
577 raise EngineException(
578 "Unknown topic {}!!!".format(topic), HTTPStatus.INTERNAL_SERVER_ERROR
579 )
580 with self.write_lock:
581 self.map_topic[topic].cancel(rollback, session, indata, kwargs, headers)
582
tiernod985a8d2018-10-19 14:12:28 +0200583 def upgrade_db(self, current_version, target_version):
Eduardo Sousa044f4312019-05-20 15:17:35 +0100584 if target_version not in self.map_target_version_to_int.keys():
garciadeblas4568a372021-03-24 09:19:48 +0100585 raise EngineException(
586 "Cannot upgrade to version '{}' with this version of code".format(
587 target_version
588 ),
589 http_code=HTTPStatus.INTERNAL_SERVER_ERROR,
590 )
tiernod985a8d2018-10-19 14:12:28 +0200591
Eduardo Sousa044f4312019-05-20 15:17:35 +0100592 if current_version == target_version:
593 return
garciadeblas4568a372021-03-24 09:19:48 +0100594
Eduardo Sousa044f4312019-05-20 15:17:35 +0100595 target_version_int = self.map_target_version_to_int[target_version]
596
597 if not current_version:
598 # create database version
599 serial = urandom(32)
600 version_data = {
garciadeblas4568a372021-03-24 09:19:48 +0100601 "_id": "version", # Always "version"
602 "version_int": 1000, # version number
603 "version": "1.0", # version text
604 "date": "2018-10-25", # version date
Eduardo Sousa044f4312019-05-20 15:17:35 +0100605 "description": "added serial", # changes in this version
garciadeblas4568a372021-03-24 09:19:48 +0100606 "status": "ENABLED", # ENABLED, DISABLED (migration in process), ERROR,
607 "serial": b64encode(serial),
Eduardo Sousa044f4312019-05-20 15:17:35 +0100608 }
609 self.db.create("admin", version_data)
610 self.db.set_secret_key(serial)
611 current_version = "1.0"
garciadeblas4568a372021-03-24 09:19:48 +0100612
613 if (
614 current_version in ("1.0", "1.1")
615 and target_version_int >= self.map_target_version_to_int["1.2"]
616 ):
617 if self.config["authentication"]["backend"] == "internal":
delacruzramo01b15d32019-07-02 14:37:47 +0200618 self.db.del_list("roles")
619
Eduardo Sousa044f4312019-05-20 15:17:35 +0100620 version_data = {
621 "_id": "version",
tierno1f029d82019-06-13 22:37:04 +0000622 "version_int": 1002,
623 "version": "1.2",
624 "date": "2019-06-11",
garciadeblas4568a372021-03-24 09:19:48 +0100625 "description": "set new format for roles_operations",
Eduardo Sousa044f4312019-05-20 15:17:35 +0100626 }
627
628 self.db.set_one("admin", {"_id": "version"}, version_data)
tierno1f029d82019-06-13 22:37:04 +0000629 current_version = "1.2"
Eduardo Sousa044f4312019-05-20 15:17:35 +0100630 # TODO add future migrations here
tiernod985a8d2018-10-19 14:12:28 +0200631
garciadeblas4568a372021-03-24 09:19:48 +0100632 def init_db(self, target_version="1.0"):
tierno4a946e42018-04-12 17:48:49 +0200633 """
tiernod985a8d2018-10-19 14:12:28 +0200634 Init database if empty. If not empty it checks that database version and migrates if needed
tierno4a946e42018-04-12 17:48:49 +0200635 If empty, it creates a new user admin/admin at 'users' and a new entry at 'version'
tiernod985a8d2018-10-19 14:12:28 +0200636 :param target_version: check desired database version. Migrate to it if possible or raises exception
tierno4a946e42018-04-12 17:48:49 +0200637 :return: None if ok, exception if error or if the version is different.
638 """
tiernod985a8d2018-10-19 14:12:28 +0200639
garciadeblas4568a372021-03-24 09:19:48 +0100640 version_data = self.db.get_one(
641 "admin", {"_id": "version"}, fail_on_empty=False, fail_on_more=True
642 )
tiernod985a8d2018-10-19 14:12:28 +0200643 # check database status is ok
garciadeblas4568a372021-03-24 09:19:48 +0100644 if version_data and version_data.get("status") != "ENABLED":
645 raise EngineException(
646 "Wrong database status '{}'".format(version_data["status"]),
647 HTTPStatus.INTERNAL_SERVER_ERROR,
648 )
tiernod985a8d2018-10-19 14:12:28 +0200649
650 # check version
651 db_version = None if not version_data else version_data.get("version")
652 if db_version != target_version:
653 self.upgrade_db(db_version, target_version)
654
tierno4a946e42018-04-12 17:48:49 +0200655 return