blob: 1f0308af8a712208cdd2f4bacd2f8f93dd1dd879 [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
Patricia Reinoso43eac1e2022-10-26 08:55:54 +000039from osm_nbi.admin_topics import VcaTopic, PaasTopic
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,
47)
48from osm_nbi.instance_topics import (
49 NsrTopic,
50 VnfrTopic,
51 NsLcmOpTopic,
52 NsiTopic,
53 NsiLcmOpTopic,
54)
almagiae47b9132022-05-17 14:12:22 +020055from osm_nbi.vnf_instance_topics import VnfInstances, VnfLcmOpTopic
tierno23acf402019-08-28 13:36:34 +000056from osm_nbi.pmjobs_topics import PmJobsTopic
preethika.p329b8182020-04-22 12:25:39 +053057from osm_nbi.subscription_topics import NslcmSubscriptionsTopic
selvi.jf1004592022-04-29 05:42:35 +000058from osm_nbi.osm_vnfm.vnf_subscription import VnflcmSubscriptionsTopic
tiernod985a8d2018-10-19 14:12:28 +020059from base64 import b64encode
garciadeblas4568a372021-03-24 09:19:48 +010060from os import urandom # , path
tierno04dbb0e2019-01-09 16:00:24 +000061from threading import Lock
tiernoc94c3df2018-02-09 15:38:54 +010062
63__author__ = "Alfonso Tierno <alfonso.tiernosepulveda@telefonica.com>"
tierno932499c2019-01-28 17:28:10 +000064min_common_version = "0.1.16"
tierno441dbbf2018-07-10 12:52:48 +020065
66
tiernoc94c3df2018-02-09 15:38:54 +010067class Engine(object):
tiernob24258a2018-10-04 18:39:49 +020068 map_from_topic_to_class = {
69 "vnfds": VnfdTopic,
70 "nsds": NsdTopic,
Felipe Vicensb57758d2018-10-16 16:00:20 +020071 "nsts": NstTopic,
tiernob24258a2018-10-04 18:39:49 +020072 "pdus": PduTopic,
73 "nsrs": NsrTopic,
74 "vnfrs": VnfrTopic,
75 "nslcmops": NsLcmOpTopic,
76 "vim_accounts": VimAccountTopic,
tierno55ba2e62018-12-11 17:22:22 +000077 "wim_accounts": WimAccountTopic,
tiernob24258a2018-10-04 18:39:49 +020078 "sdns": SdnTopic,
delacruzramofe598fe2019-10-23 18:25:11 +020079 "k8sclusters": K8sClusterTopic,
David Garciaecb41322021-03-31 19:10:46 +020080 "vca": VcaTopic,
Patricia Reinoso43eac1e2022-10-26 08:55:54 +000081 "paas": PaasTopic,
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,
tiernob24258a2018-10-04 18:39:49 +020094 # [NEW_TOPIC]: add an entry here
vijay.r35ef2f72019-04-30 17:55:49 +053095 # "pm_jobs": PmJobsTopic will be added manually because it needs other parameters
tiernob24258a2018-10-04 18:39:49 +020096 }
tiernoc94c3df2018-02-09 15:38:54 +010097
Eduardo Sousa044f4312019-05-20 15:17:35 +010098 map_target_version_to_int = {
99 "1.0": 1000,
tierno1f029d82019-06-13 22:37:04 +0000100 "1.1": 1001,
101 "1.2": 1002,
Eduardo Sousa044f4312019-05-20 15:17:35 +0100102 # Add new versions here
103 }
104
delacruzramoad682a52019-12-10 16:26:34 +0100105 def __init__(self, authenticator):
tiernoc94c3df2018-02-09 15:38:54 +0100106 self.db = None
107 self.fs = None
108 self.msg = None
delacruzramoad682a52019-12-10 16:26:34 +0100109 self.authconn = None
tiernoc94c3df2018-02-09 15:38:54 +0100110 self.config = None
tierno9e87a7f2020-03-23 09:24:10 +0000111 # self.operations = None
tiernoc94c3df2018-02-09 15:38:54 +0100112 self.logger = logging.getLogger("nbi.engine")
tiernob24258a2018-10-04 18:39:49 +0200113 self.map_topic = {}
tierno04dbb0e2019-01-09 16:00:24 +0000114 self.write_lock = None
delacruzramoad682a52019-12-10 16:26:34 +0100115 # self.token_cache = token_cache
116 self.authenticator = authenticator
tiernoc94c3df2018-02-09 15:38:54 +0100117
118 def start(self, config):
119 """
120 Connect to database, filesystem storage, and messaging
121 :param config: two level dictionary with configuration. Top level should contain 'database', 'storage',
122 :return: None
123 """
124 self.config = config
tiernob24258a2018-10-04 18:39:49 +0200125 # check right version of common
126 if versiontuple(common_version) < versiontuple(min_common_version):
garciadeblas4568a372021-03-24 09:19:48 +0100127 raise EngineException(
128 "Not compatible osm/common version '{}'. Needed '{}' or higher".format(
129 common_version, min_common_version
130 )
131 )
tiernob24258a2018-10-04 18:39:49 +0200132
tiernoc94c3df2018-02-09 15:38:54 +0100133 try:
134 if not self.db:
135 if config["database"]["driver"] == "mongo":
136 self.db = dbmongo.DbMongo()
137 self.db.db_connect(config["database"])
138 elif config["database"]["driver"] == "memory":
139 self.db = dbmemory.DbMemory()
140 self.db.db_connect(config["database"])
141 else:
garciadeblas4568a372021-03-24 09:19:48 +0100142 raise EngineException(
143 "Invalid configuration param '{}' at '[database]':'driver'".format(
144 config["database"]["driver"]
145 )
146 )
tiernoc94c3df2018-02-09 15:38:54 +0100147 if not self.fs:
148 if config["storage"]["driver"] == "local":
149 self.fs = fslocal.FsLocal()
150 self.fs.fs_connect(config["storage"])
Eduardo Sousa7e0eb132019-06-21 11:50:21 +0100151 elif config["storage"]["driver"] == "mongo":
152 self.fs = fsmongo.FsMongo()
153 self.fs.fs_connect(config["storage"])
tiernoc94c3df2018-02-09 15:38:54 +0100154 else:
garciadeblas4568a372021-03-24 09:19:48 +0100155 raise EngineException(
156 "Invalid configuration param '{}' at '[storage]':'driver'".format(
157 config["storage"]["driver"]
158 )
159 )
tiernoc94c3df2018-02-09 15:38:54 +0100160 if not self.msg:
161 if config["message"]["driver"] == "local":
162 self.msg = msglocal.MsgLocal()
163 self.msg.connect(config["message"])
164 elif config["message"]["driver"] == "kafka":
165 self.msg = msgkafka.MsgKafka()
166 self.msg.connect(config["message"])
167 else:
garciadeblas4568a372021-03-24 09:19:48 +0100168 raise EngineException(
169 "Invalid configuration param '{}' at '[message]':'driver'".format(
170 config["message"]["driver"]
171 )
172 )
delacruzramoad682a52019-12-10 16:26:34 +0100173 if not self.authconn:
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100174 if config["authentication"]["backend"] == "keystone":
garciadeblas4568a372021-03-24 09:19:48 +0100175 self.authconn = AuthconnKeystone(
176 config["authentication"],
177 self.db,
178 self.authenticator.role_permissions,
179 )
K Sai Kiran7ddb0732020-10-30 11:14:44 +0530180 elif config["authentication"]["backend"] == "tacacs":
garciadeblas4568a372021-03-24 09:19:48 +0100181 self.authconn = AuthconnTacacs(
182 config["authentication"],
183 self.db,
184 self.authenticator.role_permissions,
185 )
delacruzramoceb8baf2019-06-21 14:25:38 +0200186 else:
garciadeblas4568a372021-03-24 09:19:48 +0100187 self.authconn = AuthconnInternal(
188 config["authentication"],
189 self.db,
190 self.authenticator.role_permissions,
191 )
tierno9e87a7f2020-03-23 09:24:10 +0000192 # if not self.operations:
193 # if "resources_to_operations" in config["rbac"]:
194 # resources_to_operations_file = config["rbac"]["resources_to_operations"]
195 # else:
196 # possible_paths = (
197 # __file__[:__file__.rfind("engine.py")] + "resources_to_operations.yml",
198 # "./resources_to_operations.yml"
199 # )
200 # for config_file in possible_paths:
201 # if path.isfile(config_file):
202 # resources_to_operations_file = config_file
203 # break
204 # if not resources_to_operations_file:
205 # raise EngineException("Invalid permission configuration:"
206 # "resources_to_operations file missing")
207 #
208 # with open(resources_to_operations_file, 'r') as f:
209 # resources_to_operations = yaml.load(f, Loader=yaml.Loader)
210 #
211 # self.operations = []
212 #
213 # for _, value in resources_to_operations["resources_to_operations"].items():
214 # if value not in self.operations:
215 # self.operations += [value]
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100216
tierno04dbb0e2019-01-09 16:00:24 +0000217 self.write_lock = Lock()
tiernob24258a2018-10-04 18:39:49 +0200218 # create one class per topic
219 for topic, topic_class in self.map_from_topic_to_class.items():
delacruzramo32bab472019-09-13 12:24:22 +0200220 # if self.auth and topic_class in (UserTopicAuth, ProjectTopicAuth):
221 # self.map_topic[topic] = topic_class(self.db, self.fs, self.msg, self.auth)
garciadeblas4568a372021-03-24 09:19:48 +0100222 self.map_topic[topic] = topic_class(
223 self.db, self.fs, self.msg, self.authconn
224 )
225
226 self.map_topic["pm_jobs"] = PmJobsTopic(
227 self.db,
228 config["prometheus"].get("host"),
229 config["prometheus"].get("port"),
230 )
tiernoc94c3df2018-02-09 15:38:54 +0100231 except (DbException, FsException, MsgException) as e:
232 raise EngineException(str(e), http_code=e.http_code)
233
234 def stop(self):
235 try:
236 if self.db:
237 self.db.db_disconnect()
238 if self.fs:
239 self.fs.fs_disconnect()
tierno932499c2019-01-28 17:28:10 +0000240 if self.msg:
241 self.msg.disconnect()
tierno04dbb0e2019-01-09 16:00:24 +0000242 self.write_lock = None
tiernoc94c3df2018-02-09 15:38:54 +0100243 except (DbException, FsException, MsgException) as e:
244 raise EngineException(str(e), http_code=e.http_code)
245
garciadeblas4568a372021-03-24 09:19:48 +0100246 def new_item(
247 self, rollback, session, topic, indata=None, kwargs=None, headers=None
248 ):
tiernoc94c3df2018-02-09 15:38:54 +0100249 """
tiernof27c79b2018-03-12 17:08:42 +0100250 Creates a new entry into database. For nsds and vnfds it creates an almost empty DISABLED entry,
251 that must be completed with a call to method upload_content
tiernob24258a2018-10-04 18:39:49 +0200252 :param rollback: list to append created items at database in case a rollback must to be done
tierno65ca36d2019-02-12 19:27:52 +0100253 :param session: contains the used login username and working project, force to avoid checkins, public
tiernob24258a2018-10-04 18:39:49 +0200254 :param topic: it can be: users, projects, vim_accounts, sdns, nsrs, nsds, vnfds
tiernoc94c3df2018-02-09 15:38:54 +0100255 :param indata: data to be inserted
256 :param kwargs: used to override the indata descriptor
257 :param headers: http request headers
tierno0ffaa992018-05-09 13:21:56 +0200258 :return: _id: identity of the inserted data.
tiernoc94c3df2018-02-09 15:38:54 +0100259 """
tiernob24258a2018-10-04 18:39:49 +0200260 if topic not in self.map_topic:
garciadeblas4568a372021-03-24 09:19:48 +0100261 raise EngineException(
262 "Unknown topic {}!!!".format(topic), HTTPStatus.INTERNAL_SERVER_ERROR
263 )
tierno04dbb0e2019-01-09 16:00:24 +0000264 with self.write_lock:
tierno65ca36d2019-02-12 19:27:52 +0100265 return self.map_topic[topic].new(rollback, session, indata, kwargs, headers)
tiernoc94c3df2018-02-09 15:38:54 +0100266
tierno65ca36d2019-02-12 19:27:52 +0100267 def upload_content(self, session, topic, _id, indata, kwargs, headers):
tierno65acb4d2018-04-06 16:42:40 +0200268 """
tiernob24258a2018-10-04 18:39:49 +0200269 Upload content for an already created entry (_id)
tierno65acb4d2018-04-06 16:42:40 +0200270 :param session: contains the used login username and working project
tiernob24258a2018-10-04 18:39:49 +0200271 :param topic: it can be: users, projects, vnfds, nsds,
272 :param _id: server id of the item
273 :param indata: data to be inserted
tierno65acb4d2018-04-06 16:42:40 +0200274 :param kwargs: used to override the indata descriptor
tiernob24258a2018-10-04 18:39:49 +0200275 :param headers: http request headers
tiernob24258a2018-10-04 18:39:49 +0200276 :return: _id: identity of the inserted data.
tierno65acb4d2018-04-06 16:42:40 +0200277 """
tiernob24258a2018-10-04 18:39:49 +0200278 if topic not in self.map_topic:
garciadeblas4568a372021-03-24 09:19:48 +0100279 raise EngineException(
280 "Unknown topic {}!!!".format(topic), HTTPStatus.INTERNAL_SERVER_ERROR
281 )
tierno04dbb0e2019-01-09 16:00:24 +0000282 with self.write_lock:
garciadeblas4568a372021-03-24 09:19:48 +0100283 return self.map_topic[topic].upload_content(
284 session, _id, indata, kwargs, headers
285 )
tiernoc94c3df2018-02-09 15:38:54 +0100286
Frank Bryden19b97522020-07-10 12:32:02 +0000287 def get_item_list(self, session, topic, filter_q=None, api_req=False):
tiernoc94c3df2018-02-09 15:38:54 +0100288 """
289 Get a list of items
290 :param session: contains the used login username and working project
tiernob24258a2018-10-04 18:39:49 +0200291 :param topic: it can be: users, projects, vnfds, nsds, ...
292 :param filter_q: filter of data to be applied
Frank Bryden19b97522020-07-10 12:32:02 +0000293 :param api_req: True if this call is serving an external API request. False if serving internal request.
tiernob24258a2018-10-04 18:39:49 +0200294 :return: The list, it can be empty if no one match the filter_q.
tiernoc94c3df2018-02-09 15:38:54 +0100295 """
tiernob24258a2018-10-04 18:39:49 +0200296 if topic not in self.map_topic:
Patricia Reinoso43eac1e2022-10-26 08:55:54 +0000297 raise EngineException(
298 "Unknown topic {}!!!".format(topic), HTTPStatus.INTERNAL_SERVER_ERROR
299 )
Frank Bryden19b97522020-07-10 12:32:02 +0000300 return self.map_topic[topic].list(session, filter_q, api_req)
tiernof27c79b2018-03-12 17:08:42 +0100301
K Sai Kiran57589552021-01-27 21:38:34 +0530302 def get_item(self, session, topic, _id, filter_q=None, api_req=False):
tiernoc94c3df2018-02-09 15:38:54 +0100303 """
tiernob24258a2018-10-04 18:39:49 +0200304 Get complete information on an item
tiernoc94c3df2018-02-09 15:38:54 +0100305 :param session: contains the used login username and working project
tiernob24258a2018-10-04 18:39:49 +0200306 :param topic: it can be: users, projects, vnfds, nsds,
tiernoc94c3df2018-02-09 15:38:54 +0100307 :param _id: server id of the item
K Sai Kiran57589552021-01-27 21:38:34 +0530308 :param filter_q: other arguments
Frank Bryden19b97522020-07-10 12:32:02 +0000309 :param api_req: True if this call is serving an external API request. False if serving internal request.
tiernoc94c3df2018-02-09 15:38:54 +0100310 :return: dictionary, raise exception if not found.
311 """
tiernob24258a2018-10-04 18:39:49 +0200312 if topic not in self.map_topic:
Patricia Reinoso43eac1e2022-10-26 08:55:54 +0000313 raise EngineException(
314 "Unknown topic {}!!!".format(topic), HTTPStatus.INTERNAL_SERVER_ERROR
315 )
K Sai Kiran57589552021-01-27 21:38:34 +0530316 return self.map_topic[topic].show(session, _id, filter_q, api_req)
tiernoc94c3df2018-02-09 15:38:54 +0100317
tierno87006042018-10-24 12:50:20 +0200318 def get_file(self, session, topic, _id, path=None, accept_header=None):
319 """
320 Get descriptor package or artifact file content
321 :param session: contains the used login username and working project
322 :param topic: it can be: users, projects, vnfds, nsds,
323 :param _id: server id of the item
324 :param path: artifact path or "$DESCRIPTOR" or None
325 :param accept_header: Content of Accept header. Must contain applition/zip or/and text/plain
326 :return: opened file plus Accept format or raises an exception
327 """
328 if topic not in self.map_topic:
garciadeblas4568a372021-03-24 09:19:48 +0100329 raise EngineException(
330 "Unknown topic {}!!!".format(topic), HTTPStatus.INTERNAL_SERVER_ERROR
331 )
tierno87006042018-10-24 12:50:20 +0200332 return self.map_topic[topic].get_file(session, _id, path, accept_header)
333
tiernob24258a2018-10-04 18:39:49 +0200334 def del_item_list(self, session, topic, _filter=None):
tiernoc94c3df2018-02-09 15:38:54 +0100335 """
336 Delete a list of items
337 :param session: contains the used login username and working project
tiernob24258a2018-10-04 18:39:49 +0200338 :param topic: it can be: users, projects, vnfds, nsds, ...
339 :param _filter: filter of data to be applied
340 :return: The deleted list, it can be empty if no one match the _filter.
tiernoc94c3df2018-02-09 15:38:54 +0100341 """
tiernob24258a2018-10-04 18:39:49 +0200342 if topic not in self.map_topic:
garciadeblas4568a372021-03-24 09:19:48 +0100343 raise EngineException(
344 "Unknown topic {}!!!".format(topic), HTTPStatus.INTERNAL_SERVER_ERROR
345 )
tierno04dbb0e2019-01-09 16:00:24 +0000346 with self.write_lock:
347 return self.map_topic[topic].delete_list(session, _filter)
tiernoc94c3df2018-02-09 15:38:54 +0100348
tiernobee3bad2019-12-05 12:26:01 +0000349 def del_item(self, session, topic, _id, not_send_msg=None):
tiernoc94c3df2018-02-09 15:38:54 +0100350 """
tiernob92094f2018-05-11 13:44:22 +0200351 Delete item by its internal id
tiernoc94c3df2018-02-09 15:38:54 +0100352 :param session: contains the used login username and working project
tiernob24258a2018-10-04 18:39:49 +0200353 :param topic: it can be: users, projects, vnfds, nsds, ...
tiernoc94c3df2018-02-09 15:38:54 +0100354 :param _id: server id of the item
tiernobee3bad2019-12-05 12:26:01 +0000355 :param not_send_msg: If False, message will not be sent to kafka.
356 If a list, message is not sent, but content is stored in this variable so that the caller can send this
357 message using its own loop. If None, message is sent
delacruzramo01b15d32019-07-02 14:37:47 +0200358 :return: dictionary with deleted item _id. It raises exception if not found.
tiernoc94c3df2018-02-09 15:38:54 +0100359 """
tiernob24258a2018-10-04 18:39:49 +0200360 if topic not in self.map_topic:
garciadeblas4568a372021-03-24 09:19:48 +0100361 raise EngineException(
362 "Unknown topic {}!!!".format(topic), HTTPStatus.INTERNAL_SERVER_ERROR
363 )
tierno04dbb0e2019-01-09 16:00:24 +0000364 with self.write_lock:
tiernobee3bad2019-12-05 12:26:01 +0000365 return self.map_topic[topic].delete(session, _id, not_send_msg=not_send_msg)
tiernoc94c3df2018-02-09 15:38:54 +0100366
tierno65ca36d2019-02-12 19:27:52 +0100367 def edit_item(self, session, topic, _id, indata=None, kwargs=None):
tiernob24258a2018-10-04 18:39:49 +0200368 """
369 Update an existing entry at database
370 :param session: contains the used login username and working project
371 :param topic: it can be: users, projects, vnfds, nsds, ...
372 :param _id: identifier to be updated
373 :param indata: data to be inserted
374 :param kwargs: used to override the indata descriptor
delacruzramo01b15d32019-07-02 14:37:47 +0200375 :return: dictionary with edited item _id, raise exception if not found.
tiernob24258a2018-10-04 18:39:49 +0200376 """
377 if topic not in self.map_topic:
garciadeblas4568a372021-03-24 09:19:48 +0100378 raise EngineException(
379 "Unknown topic {}!!!".format(topic), HTTPStatus.INTERNAL_SERVER_ERROR
380 )
tierno04dbb0e2019-01-09 16:00:24 +0000381 with self.write_lock:
tierno65ca36d2019-02-12 19:27:52 +0100382 return self.map_topic[topic].edit(session, _id, indata, kwargs)
tiernoc94c3df2018-02-09 15:38:54 +0100383
tiernod985a8d2018-10-19 14:12:28 +0200384 def upgrade_db(self, current_version, target_version):
Eduardo Sousa044f4312019-05-20 15:17:35 +0100385 if target_version not in self.map_target_version_to_int.keys():
garciadeblas4568a372021-03-24 09:19:48 +0100386 raise EngineException(
387 "Cannot upgrade to version '{}' with this version of code".format(
388 target_version
389 ),
390 http_code=HTTPStatus.INTERNAL_SERVER_ERROR,
391 )
tiernod985a8d2018-10-19 14:12:28 +0200392
Eduardo Sousa044f4312019-05-20 15:17:35 +0100393 if current_version == target_version:
394 return
garciadeblas4568a372021-03-24 09:19:48 +0100395
Eduardo Sousa044f4312019-05-20 15:17:35 +0100396 target_version_int = self.map_target_version_to_int[target_version]
397
398 if not current_version:
399 # create database version
400 serial = urandom(32)
401 version_data = {
garciadeblas4568a372021-03-24 09:19:48 +0100402 "_id": "version", # Always "version"
403 "version_int": 1000, # version number
404 "version": "1.0", # version text
405 "date": "2018-10-25", # version date
Eduardo Sousa044f4312019-05-20 15:17:35 +0100406 "description": "added serial", # changes in this version
garciadeblas4568a372021-03-24 09:19:48 +0100407 "status": "ENABLED", # ENABLED, DISABLED (migration in process), ERROR,
408 "serial": b64encode(serial),
Eduardo Sousa044f4312019-05-20 15:17:35 +0100409 }
410 self.db.create("admin", version_data)
411 self.db.set_secret_key(serial)
412 current_version = "1.0"
garciadeblas4568a372021-03-24 09:19:48 +0100413
414 if (
415 current_version in ("1.0", "1.1")
416 and target_version_int >= self.map_target_version_to_int["1.2"]
417 ):
418 if self.config["authentication"]["backend"] == "internal":
delacruzramo01b15d32019-07-02 14:37:47 +0200419 self.db.del_list("roles")
420
Eduardo Sousa044f4312019-05-20 15:17:35 +0100421 version_data = {
422 "_id": "version",
tierno1f029d82019-06-13 22:37:04 +0000423 "version_int": 1002,
424 "version": "1.2",
425 "date": "2019-06-11",
garciadeblas4568a372021-03-24 09:19:48 +0100426 "description": "set new format for roles_operations",
Eduardo Sousa044f4312019-05-20 15:17:35 +0100427 }
428
429 self.db.set_one("admin", {"_id": "version"}, version_data)
tierno1f029d82019-06-13 22:37:04 +0000430 current_version = "1.2"
Eduardo Sousa044f4312019-05-20 15:17:35 +0100431 # TODO add future migrations here
tiernod985a8d2018-10-19 14:12:28 +0200432
garciadeblas4568a372021-03-24 09:19:48 +0100433 def init_db(self, target_version="1.0"):
tierno4a946e42018-04-12 17:48:49 +0200434 """
tiernod985a8d2018-10-19 14:12:28 +0200435 Init database if empty. If not empty it checks that database version and migrates if needed
tierno4a946e42018-04-12 17:48:49 +0200436 If empty, it creates a new user admin/admin at 'users' and a new entry at 'version'
tiernod985a8d2018-10-19 14:12:28 +0200437 :param target_version: check desired database version. Migrate to it if possible or raises exception
tierno4a946e42018-04-12 17:48:49 +0200438 :return: None if ok, exception if error or if the version is different.
439 """
tiernod985a8d2018-10-19 14:12:28 +0200440
garciadeblas4568a372021-03-24 09:19:48 +0100441 version_data = self.db.get_one(
442 "admin", {"_id": "version"}, fail_on_empty=False, fail_on_more=True
443 )
tiernod985a8d2018-10-19 14:12:28 +0200444 # check database status is ok
garciadeblas4568a372021-03-24 09:19:48 +0100445 if version_data and version_data.get("status") != "ENABLED":
446 raise EngineException(
447 "Wrong database status '{}'".format(version_data["status"]),
448 HTTPStatus.INTERNAL_SERVER_ERROR,
449 )
tiernod985a8d2018-10-19 14:12:28 +0200450
451 # check version
452 db_version = None if not version_data else version_data.get("version")
453 if db_version != target_version:
454 self.upgrade_db(db_version, target_version)
455
tierno4a946e42018-04-12 17:48:49 +0200456 return