blob: fe7d8db47a57b91e9dc4f31a712be4c0ff618a5c [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)
almagiae47b9132022-05-17 14:12:22 +020056from osm_nbi.vnf_instance_topics import VnfInstances, VnfLcmOpTopic
tierno23acf402019-08-28 13:36:34 +000057from osm_nbi.pmjobs_topics import PmJobsTopic
preethika.p329b8182020-04-22 12:25:39 +053058from osm_nbi.subscription_topics import NslcmSubscriptionsTopic
selvi.jf1004592022-04-29 05:42:35 +000059from osm_nbi.osm_vnfm.vnf_subscription import VnflcmSubscriptionsTopic
tiernod985a8d2018-10-19 14:12:28 +020060from base64 import b64encode
garciadeblas4568a372021-03-24 09:19:48 +010061from os import urandom # , path
tierno04dbb0e2019-01-09 16:00:24 +000062from threading import Lock
tiernoc94c3df2018-02-09 15:38:54 +010063
64__author__ = "Alfonso Tierno <alfonso.tiernosepulveda@telefonica.com>"
tierno932499c2019-01-28 17:28:10 +000065min_common_version = "0.1.16"
tierno441dbbf2018-07-10 12:52:48 +020066
67
tiernoc94c3df2018-02-09 15:38:54 +010068class Engine(object):
tiernob24258a2018-10-04 18:39:49 +020069 map_from_topic_to_class = {
70 "vnfds": VnfdTopic,
71 "nsds": NsdTopic,
Felipe Vicensb57758d2018-10-16 16:00:20 +020072 "nsts": NstTopic,
tiernob24258a2018-10-04 18:39:49 +020073 "pdus": PduTopic,
74 "nsrs": NsrTopic,
75 "vnfrs": VnfrTopic,
76 "nslcmops": NsLcmOpTopic,
77 "vim_accounts": VimAccountTopic,
tierno55ba2e62018-12-11 17:22:22 +000078 "wim_accounts": WimAccountTopic,
tiernob24258a2018-10-04 18:39:49 +020079 "sdns": SdnTopic,
delacruzramofe598fe2019-10-23 18:25:11 +020080 "k8sclusters": K8sClusterTopic,
David Garciaecb41322021-03-31 19:10:46 +020081 "vca": VcaTopic,
delacruzramofe598fe2019-10-23 18:25:11 +020082 "k8srepos": K8sRepoTopic,
Felipe Vicensb66b0412020-05-06 10:11:00 +020083 "osmrepos": OsmRepoTopic,
garciadeblas4568a372021-03-24 09:19:48 +010084 "users": UserTopicAuth, # Valid for both internal and keystone authentication backends
85 "projects": ProjectTopicAuth, # Valid for both internal and keystone authentication backends
86 "roles": RoleTopicAuth, # Valid for both internal and keystone authentication backends
Felipe Vicensb57758d2018-10-16 16:00:20 +020087 "nsis": NsiTopic,
delacruzramo271d2002019-12-02 21:00:37 +010088 "nsilcmops": NsiLcmOpTopic,
89 "vnfpkgops": VnfPkgOpTopic,
preethika.p329b8182020-04-22 12:25:39 +053090 "nslcm_subscriptions": NslcmSubscriptionsTopic,
almagiae47b9132022-05-17 14:12:22 +020091 "vnf_instances": VnfInstances,
92 "vnflcmops": VnfLcmOpTopic,
selvi.jf1004592022-04-29 05:42:35 +000093 "vnflcm_subscriptions": VnflcmSubscriptionsTopic,
kayal2001f71c2e82024-06-25 15:26:24 +053094 "nsconfigtemps": NsConfigTemplateTopic,
tiernob24258a2018-10-04 18:39:49 +020095 # [NEW_TOPIC]: add an entry here
vijay.r35ef2f72019-04-30 17:55:49 +053096 # "pm_jobs": PmJobsTopic will be added manually because it needs other parameters
tiernob24258a2018-10-04 18:39:49 +020097 }
tiernoc94c3df2018-02-09 15:38:54 +010098
Eduardo Sousa044f4312019-05-20 15:17:35 +010099 map_target_version_to_int = {
100 "1.0": 1000,
tierno1f029d82019-06-13 22:37:04 +0000101 "1.1": 1001,
102 "1.2": 1002,
Eduardo Sousa044f4312019-05-20 15:17:35 +0100103 # Add new versions here
104 }
105
delacruzramoad682a52019-12-10 16:26:34 +0100106 def __init__(self, authenticator):
tiernoc94c3df2018-02-09 15:38:54 +0100107 self.db = None
108 self.fs = None
109 self.msg = None
delacruzramoad682a52019-12-10 16:26:34 +0100110 self.authconn = None
tiernoc94c3df2018-02-09 15:38:54 +0100111 self.config = None
tierno9e87a7f2020-03-23 09:24:10 +0000112 # self.operations = None
tiernoc94c3df2018-02-09 15:38:54 +0100113 self.logger = logging.getLogger("nbi.engine")
tiernob24258a2018-10-04 18:39:49 +0200114 self.map_topic = {}
tierno04dbb0e2019-01-09 16:00:24 +0000115 self.write_lock = None
delacruzramoad682a52019-12-10 16:26:34 +0100116 # self.token_cache = token_cache
117 self.authenticator = authenticator
tiernoc94c3df2018-02-09 15:38:54 +0100118
119 def start(self, config):
120 """
121 Connect to database, filesystem storage, and messaging
122 :param config: two level dictionary with configuration. Top level should contain 'database', 'storage',
123 :return: None
124 """
125 self.config = config
tiernob24258a2018-10-04 18:39:49 +0200126 # check right version of common
127 if versiontuple(common_version) < versiontuple(min_common_version):
garciadeblas4568a372021-03-24 09:19:48 +0100128 raise EngineException(
129 "Not compatible osm/common version '{}'. Needed '{}' or higher".format(
130 common_version, min_common_version
131 )
132 )
tiernob24258a2018-10-04 18:39:49 +0200133
tiernoc94c3df2018-02-09 15:38:54 +0100134 try:
135 if not self.db:
136 if config["database"]["driver"] == "mongo":
137 self.db = dbmongo.DbMongo()
138 self.db.db_connect(config["database"])
139 elif config["database"]["driver"] == "memory":
140 self.db = dbmemory.DbMemory()
141 self.db.db_connect(config["database"])
142 else:
garciadeblas4568a372021-03-24 09:19:48 +0100143 raise EngineException(
144 "Invalid configuration param '{}' at '[database]':'driver'".format(
145 config["database"]["driver"]
146 )
147 )
tiernoc94c3df2018-02-09 15:38:54 +0100148 if not self.fs:
149 if config["storage"]["driver"] == "local":
150 self.fs = fslocal.FsLocal()
151 self.fs.fs_connect(config["storage"])
Eduardo Sousa7e0eb132019-06-21 11:50:21 +0100152 elif config["storage"]["driver"] == "mongo":
153 self.fs = fsmongo.FsMongo()
154 self.fs.fs_connect(config["storage"])
tiernoc94c3df2018-02-09 15:38:54 +0100155 else:
garciadeblas4568a372021-03-24 09:19:48 +0100156 raise EngineException(
157 "Invalid configuration param '{}' at '[storage]':'driver'".format(
158 config["storage"]["driver"]
159 )
160 )
tiernoc94c3df2018-02-09 15:38:54 +0100161 if not self.msg:
162 if config["message"]["driver"] == "local":
163 self.msg = msglocal.MsgLocal()
164 self.msg.connect(config["message"])
165 elif config["message"]["driver"] == "kafka":
166 self.msg = msgkafka.MsgKafka()
167 self.msg.connect(config["message"])
168 else:
garciadeblas4568a372021-03-24 09:19:48 +0100169 raise EngineException(
170 "Invalid configuration param '{}' at '[message]':'driver'".format(
171 config["message"]["driver"]
172 )
173 )
delacruzramoad682a52019-12-10 16:26:34 +0100174 if not self.authconn:
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100175 if config["authentication"]["backend"] == "keystone":
garciadeblas4568a372021-03-24 09:19:48 +0100176 self.authconn = AuthconnKeystone(
177 config["authentication"],
178 self.db,
179 self.authenticator.role_permissions,
180 )
K Sai Kiran7ddb0732020-10-30 11:14:44 +0530181 elif config["authentication"]["backend"] == "tacacs":
garciadeblas4568a372021-03-24 09:19:48 +0100182 self.authconn = AuthconnTacacs(
183 config["authentication"],
184 self.db,
185 self.authenticator.role_permissions,
186 )
delacruzramoceb8baf2019-06-21 14:25:38 +0200187 else:
garciadeblas4568a372021-03-24 09:19:48 +0100188 self.authconn = AuthconnInternal(
189 config["authentication"],
190 self.db,
191 self.authenticator.role_permissions,
192 )
tierno9e87a7f2020-03-23 09:24:10 +0000193 # if not self.operations:
194 # if "resources_to_operations" in config["rbac"]:
195 # resources_to_operations_file = config["rbac"]["resources_to_operations"]
196 # else:
197 # possible_paths = (
198 # __file__[:__file__.rfind("engine.py")] + "resources_to_operations.yml",
199 # "./resources_to_operations.yml"
200 # )
201 # for config_file in possible_paths:
202 # if path.isfile(config_file):
203 # resources_to_operations_file = config_file
204 # break
205 # if not resources_to_operations_file:
206 # raise EngineException("Invalid permission configuration:"
207 # "resources_to_operations file missing")
208 #
209 # with open(resources_to_operations_file, 'r') as f:
garciadeblas4cd875d2023-02-14 19:05:34 +0100210 # resources_to_operations = yaml.safeload(f)
tierno9e87a7f2020-03-23 09:24:10 +0000211 #
212 # self.operations = []
213 #
214 # for _, value in resources_to_operations["resources_to_operations"].items():
215 # if value not in self.operations:
216 # self.operations += [value]
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100217
tierno04dbb0e2019-01-09 16:00:24 +0000218 self.write_lock = Lock()
tiernob24258a2018-10-04 18:39:49 +0200219 # create one class per topic
220 for topic, topic_class in self.map_from_topic_to_class.items():
delacruzramo32bab472019-09-13 12:24:22 +0200221 # if self.auth and topic_class in (UserTopicAuth, ProjectTopicAuth):
222 # self.map_topic[topic] = topic_class(self.db, self.fs, self.msg, self.auth)
garciadeblas4568a372021-03-24 09:19:48 +0100223 self.map_topic[topic] = topic_class(
224 self.db, self.fs, self.msg, self.authconn
225 )
226
227 self.map_topic["pm_jobs"] = PmJobsTopic(
228 self.db,
229 config["prometheus"].get("host"),
230 config["prometheus"].get("port"),
231 )
tiernoc94c3df2018-02-09 15:38:54 +0100232 except (DbException, FsException, MsgException) as e:
233 raise EngineException(str(e), http_code=e.http_code)
234
235 def stop(self):
236 try:
237 if self.db:
238 self.db.db_disconnect()
239 if self.fs:
240 self.fs.fs_disconnect()
tierno932499c2019-01-28 17:28:10 +0000241 if self.msg:
242 self.msg.disconnect()
tierno04dbb0e2019-01-09 16:00:24 +0000243 self.write_lock = None
tiernoc94c3df2018-02-09 15:38:54 +0100244 except (DbException, FsException, MsgException) as e:
245 raise EngineException(str(e), http_code=e.http_code)
246
garciadeblas4568a372021-03-24 09:19:48 +0100247 def new_item(
248 self, rollback, session, topic, indata=None, kwargs=None, headers=None
249 ):
tiernoc94c3df2018-02-09 15:38:54 +0100250 """
tiernof27c79b2018-03-12 17:08:42 +0100251 Creates a new entry into database. For nsds and vnfds it creates an almost empty DISABLED entry,
252 that must be completed with a call to method upload_content
tiernob24258a2018-10-04 18:39:49 +0200253 :param rollback: list to append created items at database in case a rollback must to be done
tierno65ca36d2019-02-12 19:27:52 +0100254 :param session: contains the used login username and working project, force to avoid checkins, public
tiernob24258a2018-10-04 18:39:49 +0200255 :param topic: it can be: users, projects, vim_accounts, sdns, nsrs, nsds, vnfds
tiernoc94c3df2018-02-09 15:38:54 +0100256 :param indata: data to be inserted
257 :param kwargs: used to override the indata descriptor
258 :param headers: http request headers
tierno0ffaa992018-05-09 13:21:56 +0200259 :return: _id: identity of the inserted data.
tiernoc94c3df2018-02-09 15:38:54 +0100260 """
tiernob24258a2018-10-04 18:39:49 +0200261 if topic not in self.map_topic:
garciadeblas4568a372021-03-24 09:19:48 +0100262 raise EngineException(
263 "Unknown topic {}!!!".format(topic), HTTPStatus.INTERNAL_SERVER_ERROR
264 )
tierno04dbb0e2019-01-09 16:00:24 +0000265 with self.write_lock:
tierno65ca36d2019-02-12 19:27:52 +0100266 return self.map_topic[topic].new(rollback, session, indata, kwargs, headers)
tiernoc94c3df2018-02-09 15:38:54 +0100267
tierno65ca36d2019-02-12 19:27:52 +0100268 def upload_content(self, session, topic, _id, indata, kwargs, headers):
tierno65acb4d2018-04-06 16:42:40 +0200269 """
tiernob24258a2018-10-04 18:39:49 +0200270 Upload content for an already created entry (_id)
tierno65acb4d2018-04-06 16:42:40 +0200271 :param session: contains the used login username and working project
tiernob24258a2018-10-04 18:39:49 +0200272 :param topic: it can be: users, projects, vnfds, nsds,
273 :param _id: server id of the item
274 :param indata: data to be inserted
tierno65acb4d2018-04-06 16:42:40 +0200275 :param kwargs: used to override the indata descriptor
tiernob24258a2018-10-04 18:39:49 +0200276 :param headers: http request headers
tiernob24258a2018-10-04 18:39:49 +0200277 :return: _id: identity of the inserted data.
tierno65acb4d2018-04-06 16:42:40 +0200278 """
tiernob24258a2018-10-04 18:39:49 +0200279 if topic not in self.map_topic:
garciadeblas4568a372021-03-24 09:19:48 +0100280 raise EngineException(
281 "Unknown topic {}!!!".format(topic), HTTPStatus.INTERNAL_SERVER_ERROR
282 )
tierno04dbb0e2019-01-09 16:00:24 +0000283 with self.write_lock:
garciadeblas4568a372021-03-24 09:19:48 +0100284 return self.map_topic[topic].upload_content(
285 session, _id, indata, kwargs, headers
286 )
tiernoc94c3df2018-02-09 15:38:54 +0100287
Frank Bryden19b97522020-07-10 12:32:02 +0000288 def get_item_list(self, session, topic, filter_q=None, api_req=False):
tiernoc94c3df2018-02-09 15:38:54 +0100289 """
290 Get a list of items
291 :param session: contains the used login username and working project
tiernob24258a2018-10-04 18:39:49 +0200292 :param topic: it can be: users, projects, vnfds, nsds, ...
293 :param filter_q: filter of data to be applied
Frank Bryden19b97522020-07-10 12:32:02 +0000294 :param api_req: True if this call is serving an external API request. False if serving internal request.
tiernob24258a2018-10-04 18:39:49 +0200295 :return: The list, it can be empty if no one match the filter_q.
tiernoc94c3df2018-02-09 15:38:54 +0100296 """
tiernob24258a2018-10-04 18:39:49 +0200297 if topic not in self.map_topic:
garciadeblasf2af4a12023-01-24 16:56:54 +0100298 raise EngineException(
299 "Unknown topic {}!!!".format(topic), HTTPStatus.INTERNAL_SERVER_ERROR
300 )
Frank Bryden19b97522020-07-10 12:32:02 +0000301 return self.map_topic[topic].list(session, filter_q, api_req)
tiernof27c79b2018-03-12 17:08:42 +0100302
K Sai Kiran57589552021-01-27 21:38:34 +0530303 def get_item(self, session, topic, _id, filter_q=None, api_req=False):
tiernoc94c3df2018-02-09 15:38:54 +0100304 """
tiernob24258a2018-10-04 18:39:49 +0200305 Get complete information on an item
tiernoc94c3df2018-02-09 15:38:54 +0100306 :param session: contains the used login username and working project
tiernob24258a2018-10-04 18:39:49 +0200307 :param topic: it can be: users, projects, vnfds, nsds,
tiernoc94c3df2018-02-09 15:38:54 +0100308 :param _id: server id of the item
K Sai Kiran57589552021-01-27 21:38:34 +0530309 :param filter_q: other arguments
Frank Bryden19b97522020-07-10 12:32:02 +0000310 :param api_req: True if this call is serving an external API request. False if serving internal request.
tiernoc94c3df2018-02-09 15:38:54 +0100311 :return: dictionary, raise exception if not found.
312 """
tiernob24258a2018-10-04 18:39:49 +0200313 if topic not in self.map_topic:
garciadeblasf2af4a12023-01-24 16:56:54 +0100314 raise EngineException(
315 "Unknown topic {}!!!".format(topic), HTTPStatus.INTERNAL_SERVER_ERROR
316 )
K Sai Kiran57589552021-01-27 21:38:34 +0530317 return self.map_topic[topic].show(session, _id, filter_q, api_req)
tiernoc94c3df2018-02-09 15:38:54 +0100318
tierno87006042018-10-24 12:50:20 +0200319 def get_file(self, session, topic, _id, path=None, accept_header=None):
320 """
321 Get descriptor package or artifact file content
322 :param session: contains the used login username and working project
323 :param topic: it can be: users, projects, vnfds, nsds,
324 :param _id: server id of the item
325 :param path: artifact path or "$DESCRIPTOR" or None
326 :param accept_header: Content of Accept header. Must contain applition/zip or/and text/plain
327 :return: opened file plus Accept format or raises an exception
328 """
329 if topic not in self.map_topic:
garciadeblas4568a372021-03-24 09:19:48 +0100330 raise EngineException(
331 "Unknown topic {}!!!".format(topic), HTTPStatus.INTERNAL_SERVER_ERROR
332 )
tierno87006042018-10-24 12:50:20 +0200333 return self.map_topic[topic].get_file(session, _id, path, accept_header)
334
tiernob24258a2018-10-04 18:39:49 +0200335 def del_item_list(self, session, topic, _filter=None):
tiernoc94c3df2018-02-09 15:38:54 +0100336 """
337 Delete a list of items
338 :param session: contains the used login username and working project
tiernob24258a2018-10-04 18:39:49 +0200339 :param topic: it can be: users, projects, vnfds, nsds, ...
340 :param _filter: filter of data to be applied
341 :return: The deleted list, it can be empty if no one match the _filter.
tiernoc94c3df2018-02-09 15:38:54 +0100342 """
tiernob24258a2018-10-04 18:39:49 +0200343 if topic not in self.map_topic:
garciadeblas4568a372021-03-24 09:19:48 +0100344 raise EngineException(
345 "Unknown topic {}!!!".format(topic), HTTPStatus.INTERNAL_SERVER_ERROR
346 )
tierno04dbb0e2019-01-09 16:00:24 +0000347 with self.write_lock:
348 return self.map_topic[topic].delete_list(session, _filter)
tiernoc94c3df2018-02-09 15:38:54 +0100349
tiernobee3bad2019-12-05 12:26:01 +0000350 def del_item(self, session, topic, _id, not_send_msg=None):
tiernoc94c3df2018-02-09 15:38:54 +0100351 """
tiernob92094f2018-05-11 13:44:22 +0200352 Delete item by its internal id
tiernoc94c3df2018-02-09 15:38:54 +0100353 :param session: contains the used login username and working project
tiernob24258a2018-10-04 18:39:49 +0200354 :param topic: it can be: users, projects, vnfds, nsds, ...
tiernoc94c3df2018-02-09 15:38:54 +0100355 :param _id: server id of the item
tiernobee3bad2019-12-05 12:26:01 +0000356 :param not_send_msg: If False, message will not be sent to kafka.
357 If a list, message is not sent, but content is stored in this variable so that the caller can send this
358 message using its own loop. If None, message is sent
delacruzramo01b15d32019-07-02 14:37:47 +0200359 :return: dictionary with deleted item _id. It raises exception if not found.
tiernoc94c3df2018-02-09 15:38:54 +0100360 """
tiernob24258a2018-10-04 18:39:49 +0200361 if topic not in self.map_topic:
garciadeblas4568a372021-03-24 09:19:48 +0100362 raise EngineException(
363 "Unknown topic {}!!!".format(topic), HTTPStatus.INTERNAL_SERVER_ERROR
364 )
tierno04dbb0e2019-01-09 16:00:24 +0000365 with self.write_lock:
tiernobee3bad2019-12-05 12:26:01 +0000366 return self.map_topic[topic].delete(session, _id, not_send_msg=not_send_msg)
tiernoc94c3df2018-02-09 15:38:54 +0100367
tierno65ca36d2019-02-12 19:27:52 +0100368 def edit_item(self, session, topic, _id, indata=None, kwargs=None):
tiernob24258a2018-10-04 18:39:49 +0200369 """
370 Update an existing entry at database
371 :param session: contains the used login username and working project
372 :param topic: it can be: users, projects, vnfds, nsds, ...
373 :param _id: identifier to be updated
374 :param indata: data to be inserted
375 :param kwargs: used to override the indata descriptor
delacruzramo01b15d32019-07-02 14:37:47 +0200376 :return: dictionary with edited item _id, raise exception if not found.
tiernob24258a2018-10-04 18:39:49 +0200377 """
378 if topic not in self.map_topic:
garciadeblas4568a372021-03-24 09:19:48 +0100379 raise EngineException(
380 "Unknown topic {}!!!".format(topic), HTTPStatus.INTERNAL_SERVER_ERROR
381 )
tierno04dbb0e2019-01-09 16:00:24 +0000382 with self.write_lock:
tierno65ca36d2019-02-12 19:27:52 +0100383 return self.map_topic[topic].edit(session, _id, indata, kwargs)
tiernoc94c3df2018-02-09 15:38:54 +0100384
Gabriel Cuba84a60df2023-10-30 14:01:54 -0500385 def cancel_item(
386 self, rollback, session, topic, indata=None, kwargs=None, headers=None
387 ):
388 """
389 Cancels an item
390 :param rollback: list to append created items at database in case a rollback must to be done
391 :param session: contains the used login username and working project, force to avoid checkins, public
392 :param topic: it can be: users, projects, vim_accounts, sdns, nsrs, nsds, vnfds
393 :param indata: data to be inserted
394 :param kwargs: used to override the indata descriptor
395 :param headers: http request headers
396 :return: _id: identity of the inserted data.
397 """
398 if topic not in self.map_topic:
399 raise EngineException(
400 "Unknown topic {}!!!".format(topic), HTTPStatus.INTERNAL_SERVER_ERROR
401 )
402 with self.write_lock:
403 self.map_topic[topic].cancel(rollback, session, indata, kwargs, headers)
404
tiernod985a8d2018-10-19 14:12:28 +0200405 def upgrade_db(self, current_version, target_version):
Eduardo Sousa044f4312019-05-20 15:17:35 +0100406 if target_version not in self.map_target_version_to_int.keys():
garciadeblas4568a372021-03-24 09:19:48 +0100407 raise EngineException(
408 "Cannot upgrade to version '{}' with this version of code".format(
409 target_version
410 ),
411 http_code=HTTPStatus.INTERNAL_SERVER_ERROR,
412 )
tiernod985a8d2018-10-19 14:12:28 +0200413
Eduardo Sousa044f4312019-05-20 15:17:35 +0100414 if current_version == target_version:
415 return
garciadeblas4568a372021-03-24 09:19:48 +0100416
Eduardo Sousa044f4312019-05-20 15:17:35 +0100417 target_version_int = self.map_target_version_to_int[target_version]
418
419 if not current_version:
420 # create database version
421 serial = urandom(32)
422 version_data = {
garciadeblas4568a372021-03-24 09:19:48 +0100423 "_id": "version", # Always "version"
424 "version_int": 1000, # version number
425 "version": "1.0", # version text
426 "date": "2018-10-25", # version date
Eduardo Sousa044f4312019-05-20 15:17:35 +0100427 "description": "added serial", # changes in this version
garciadeblas4568a372021-03-24 09:19:48 +0100428 "status": "ENABLED", # ENABLED, DISABLED (migration in process), ERROR,
429 "serial": b64encode(serial),
Eduardo Sousa044f4312019-05-20 15:17:35 +0100430 }
431 self.db.create("admin", version_data)
432 self.db.set_secret_key(serial)
433 current_version = "1.0"
garciadeblas4568a372021-03-24 09:19:48 +0100434
435 if (
436 current_version in ("1.0", "1.1")
437 and target_version_int >= self.map_target_version_to_int["1.2"]
438 ):
439 if self.config["authentication"]["backend"] == "internal":
delacruzramo01b15d32019-07-02 14:37:47 +0200440 self.db.del_list("roles")
441
Eduardo Sousa044f4312019-05-20 15:17:35 +0100442 version_data = {
443 "_id": "version",
tierno1f029d82019-06-13 22:37:04 +0000444 "version_int": 1002,
445 "version": "1.2",
446 "date": "2019-06-11",
garciadeblas4568a372021-03-24 09:19:48 +0100447 "description": "set new format for roles_operations",
Eduardo Sousa044f4312019-05-20 15:17:35 +0100448 }
449
450 self.db.set_one("admin", {"_id": "version"}, version_data)
tierno1f029d82019-06-13 22:37:04 +0000451 current_version = "1.2"
Eduardo Sousa044f4312019-05-20 15:17:35 +0100452 # TODO add future migrations here
tiernod985a8d2018-10-19 14:12:28 +0200453
garciadeblas4568a372021-03-24 09:19:48 +0100454 def init_db(self, target_version="1.0"):
tierno4a946e42018-04-12 17:48:49 +0200455 """
tiernod985a8d2018-10-19 14:12:28 +0200456 Init database if empty. If not empty it checks that database version and migrates if needed
tierno4a946e42018-04-12 17:48:49 +0200457 If empty, it creates a new user admin/admin at 'users' and a new entry at 'version'
tiernod985a8d2018-10-19 14:12:28 +0200458 :param target_version: check desired database version. Migrate to it if possible or raises exception
tierno4a946e42018-04-12 17:48:49 +0200459 :return: None if ok, exception if error or if the version is different.
460 """
tiernod985a8d2018-10-19 14:12:28 +0200461
garciadeblas4568a372021-03-24 09:19:48 +0100462 version_data = self.db.get_one(
463 "admin", {"_id": "version"}, fail_on_empty=False, fail_on_more=True
464 )
tiernod985a8d2018-10-19 14:12:28 +0200465 # check database status is ok
garciadeblas4568a372021-03-24 09:19:48 +0100466 if version_data and version_data.get("status") != "ENABLED":
467 raise EngineException(
468 "Wrong database status '{}'".format(version_data["status"]),
469 HTTPStatus.INTERNAL_SERVER_ERROR,
470 )
tiernod985a8d2018-10-19 14:12:28 +0200471
472 # check version
473 db_version = None if not version_data else version_data.get("version")
474 if db_version != target_version:
475 self.upgrade_db(db_version, target_version)
476
tierno4a946e42018-04-12 17:48:49 +0200477 return