blob: 37f1fb27503281a06db3117c95c91b8bcc3fc9c1 [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,
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,
delacruzramofe598fe2019-10-23 18:25:11 +020081 "k8srepos": K8sRepoTopic,
Felipe Vicensb66b0412020-05-06 10:11:00 +020082 "osmrepos": OsmRepoTopic,
garciadeblas4568a372021-03-24 09:19:48 +010083 "users": UserTopicAuth, # Valid for both internal and keystone authentication backends
84 "projects": ProjectTopicAuth, # Valid for both internal and keystone authentication backends
85 "roles": RoleTopicAuth, # Valid for both internal and keystone authentication backends
Felipe Vicensb57758d2018-10-16 16:00:20 +020086 "nsis": NsiTopic,
delacruzramo271d2002019-12-02 21:00:37 +010087 "nsilcmops": NsiLcmOpTopic,
88 "vnfpkgops": VnfPkgOpTopic,
preethika.p329b8182020-04-22 12:25:39 +053089 "nslcm_subscriptions": NslcmSubscriptionsTopic,
almagiae47b9132022-05-17 14:12:22 +020090 "vnf_instances": VnfInstances,
91 "vnflcmops": VnfLcmOpTopic,
selvi.jf1004592022-04-29 05:42:35 +000092 "vnflcm_subscriptions": VnflcmSubscriptionsTopic,
tiernob24258a2018-10-04 18:39:49 +020093 # [NEW_TOPIC]: add an entry here
vijay.r35ef2f72019-04-30 17:55:49 +053094 # "pm_jobs": PmJobsTopic will be added manually because it needs other parameters
tiernob24258a2018-10-04 18:39:49 +020095 }
tiernoc94c3df2018-02-09 15:38:54 +010096
Eduardo Sousa044f4312019-05-20 15:17:35 +010097 map_target_version_to_int = {
98 "1.0": 1000,
tierno1f029d82019-06-13 22:37:04 +000099 "1.1": 1001,
100 "1.2": 1002,
Eduardo Sousa044f4312019-05-20 15:17:35 +0100101 # Add new versions here
102 }
103
delacruzramoad682a52019-12-10 16:26:34 +0100104 def __init__(self, authenticator):
tiernoc94c3df2018-02-09 15:38:54 +0100105 self.db = None
106 self.fs = None
107 self.msg = None
delacruzramoad682a52019-12-10 16:26:34 +0100108 self.authconn = None
tiernoc94c3df2018-02-09 15:38:54 +0100109 self.config = None
tierno9e87a7f2020-03-23 09:24:10 +0000110 # self.operations = None
tiernoc94c3df2018-02-09 15:38:54 +0100111 self.logger = logging.getLogger("nbi.engine")
tiernob24258a2018-10-04 18:39:49 +0200112 self.map_topic = {}
tierno04dbb0e2019-01-09 16:00:24 +0000113 self.write_lock = None
delacruzramoad682a52019-12-10 16:26:34 +0100114 # self.token_cache = token_cache
115 self.authenticator = authenticator
tiernoc94c3df2018-02-09 15:38:54 +0100116
117 def start(self, config):
118 """
119 Connect to database, filesystem storage, and messaging
120 :param config: two level dictionary with configuration. Top level should contain 'database', 'storage',
121 :return: None
122 """
123 self.config = config
tiernob24258a2018-10-04 18:39:49 +0200124 # check right version of common
125 if versiontuple(common_version) < versiontuple(min_common_version):
garciadeblas4568a372021-03-24 09:19:48 +0100126 raise EngineException(
127 "Not compatible osm/common version '{}'. Needed '{}' or higher".format(
128 common_version, min_common_version
129 )
130 )
tiernob24258a2018-10-04 18:39:49 +0200131
tiernoc94c3df2018-02-09 15:38:54 +0100132 try:
133 if not self.db:
134 if config["database"]["driver"] == "mongo":
135 self.db = dbmongo.DbMongo()
136 self.db.db_connect(config["database"])
137 elif config["database"]["driver"] == "memory":
138 self.db = dbmemory.DbMemory()
139 self.db.db_connect(config["database"])
140 else:
garciadeblas4568a372021-03-24 09:19:48 +0100141 raise EngineException(
142 "Invalid configuration param '{}' at '[database]':'driver'".format(
143 config["database"]["driver"]
144 )
145 )
tiernoc94c3df2018-02-09 15:38:54 +0100146 if not self.fs:
147 if config["storage"]["driver"] == "local":
148 self.fs = fslocal.FsLocal()
149 self.fs.fs_connect(config["storage"])
Eduardo Sousa7e0eb132019-06-21 11:50:21 +0100150 elif config["storage"]["driver"] == "mongo":
151 self.fs = fsmongo.FsMongo()
152 self.fs.fs_connect(config["storage"])
tiernoc94c3df2018-02-09 15:38:54 +0100153 else:
garciadeblas4568a372021-03-24 09:19:48 +0100154 raise EngineException(
155 "Invalid configuration param '{}' at '[storage]':'driver'".format(
156 config["storage"]["driver"]
157 )
158 )
tiernoc94c3df2018-02-09 15:38:54 +0100159 if not self.msg:
160 if config["message"]["driver"] == "local":
161 self.msg = msglocal.MsgLocal()
162 self.msg.connect(config["message"])
163 elif config["message"]["driver"] == "kafka":
164 self.msg = msgkafka.MsgKafka()
165 self.msg.connect(config["message"])
166 else:
garciadeblas4568a372021-03-24 09:19:48 +0100167 raise EngineException(
168 "Invalid configuration param '{}' at '[message]':'driver'".format(
169 config["message"]["driver"]
170 )
171 )
delacruzramoad682a52019-12-10 16:26:34 +0100172 if not self.authconn:
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100173 if config["authentication"]["backend"] == "keystone":
garciadeblas4568a372021-03-24 09:19:48 +0100174 self.authconn = AuthconnKeystone(
175 config["authentication"],
176 self.db,
177 self.authenticator.role_permissions,
178 )
K Sai Kiran7ddb0732020-10-30 11:14:44 +0530179 elif config["authentication"]["backend"] == "tacacs":
garciadeblas4568a372021-03-24 09:19:48 +0100180 self.authconn = AuthconnTacacs(
181 config["authentication"],
182 self.db,
183 self.authenticator.role_permissions,
184 )
delacruzramoceb8baf2019-06-21 14:25:38 +0200185 else:
garciadeblas4568a372021-03-24 09:19:48 +0100186 self.authconn = AuthconnInternal(
187 config["authentication"],
188 self.db,
189 self.authenticator.role_permissions,
190 )
tierno9e87a7f2020-03-23 09:24:10 +0000191 # if not self.operations:
192 # if "resources_to_operations" in config["rbac"]:
193 # resources_to_operations_file = config["rbac"]["resources_to_operations"]
194 # else:
195 # possible_paths = (
196 # __file__[:__file__.rfind("engine.py")] + "resources_to_operations.yml",
197 # "./resources_to_operations.yml"
198 # )
199 # for config_file in possible_paths:
200 # if path.isfile(config_file):
201 # resources_to_operations_file = config_file
202 # break
203 # if not resources_to_operations_file:
204 # raise EngineException("Invalid permission configuration:"
205 # "resources_to_operations file missing")
206 #
207 # with open(resources_to_operations_file, 'r') as f:
208 # resources_to_operations = yaml.load(f, Loader=yaml.Loader)
209 #
210 # self.operations = []
211 #
212 # for _, value in resources_to_operations["resources_to_operations"].items():
213 # if value not in self.operations:
214 # self.operations += [value]
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100215
tierno04dbb0e2019-01-09 16:00:24 +0000216 self.write_lock = Lock()
tiernob24258a2018-10-04 18:39:49 +0200217 # create one class per topic
218 for topic, topic_class in self.map_from_topic_to_class.items():
delacruzramo32bab472019-09-13 12:24:22 +0200219 # if self.auth and topic_class in (UserTopicAuth, ProjectTopicAuth):
220 # self.map_topic[topic] = topic_class(self.db, self.fs, self.msg, self.auth)
garciadeblas4568a372021-03-24 09:19:48 +0100221 self.map_topic[topic] = topic_class(
222 self.db, self.fs, self.msg, self.authconn
223 )
224
225 self.map_topic["pm_jobs"] = PmJobsTopic(
226 self.db,
227 config["prometheus"].get("host"),
228 config["prometheus"].get("port"),
229 )
tiernoc94c3df2018-02-09 15:38:54 +0100230 except (DbException, FsException, MsgException) as e:
231 raise EngineException(str(e), http_code=e.http_code)
232
233 def stop(self):
234 try:
235 if self.db:
236 self.db.db_disconnect()
237 if self.fs:
238 self.fs.fs_disconnect()
tierno932499c2019-01-28 17:28:10 +0000239 if self.msg:
240 self.msg.disconnect()
tierno04dbb0e2019-01-09 16:00:24 +0000241 self.write_lock = None
tiernoc94c3df2018-02-09 15:38:54 +0100242 except (DbException, FsException, MsgException) as e:
243 raise EngineException(str(e), http_code=e.http_code)
244
garciadeblas4568a372021-03-24 09:19:48 +0100245 def new_item(
246 self, rollback, session, topic, indata=None, kwargs=None, headers=None
247 ):
tiernoc94c3df2018-02-09 15:38:54 +0100248 """
tiernof27c79b2018-03-12 17:08:42 +0100249 Creates a new entry into database. For nsds and vnfds it creates an almost empty DISABLED entry,
250 that must be completed with a call to method upload_content
tiernob24258a2018-10-04 18:39:49 +0200251 :param rollback: list to append created items at database in case a rollback must to be done
tierno65ca36d2019-02-12 19:27:52 +0100252 :param session: contains the used login username and working project, force to avoid checkins, public
tiernob24258a2018-10-04 18:39:49 +0200253 :param topic: it can be: users, projects, vim_accounts, sdns, nsrs, nsds, vnfds
tiernoc94c3df2018-02-09 15:38:54 +0100254 :param indata: data to be inserted
255 :param kwargs: used to override the indata descriptor
256 :param headers: http request headers
tierno0ffaa992018-05-09 13:21:56 +0200257 :return: _id: identity of the inserted data.
tiernoc94c3df2018-02-09 15:38:54 +0100258 """
tiernob24258a2018-10-04 18:39:49 +0200259 if topic not in self.map_topic:
garciadeblas4568a372021-03-24 09:19:48 +0100260 raise EngineException(
261 "Unknown topic {}!!!".format(topic), HTTPStatus.INTERNAL_SERVER_ERROR
262 )
tierno04dbb0e2019-01-09 16:00:24 +0000263 with self.write_lock:
tierno65ca36d2019-02-12 19:27:52 +0100264 return self.map_topic[topic].new(rollback, session, indata, kwargs, headers)
tiernoc94c3df2018-02-09 15:38:54 +0100265
tierno65ca36d2019-02-12 19:27:52 +0100266 def upload_content(self, session, topic, _id, indata, kwargs, headers):
tierno65acb4d2018-04-06 16:42:40 +0200267 """
tiernob24258a2018-10-04 18:39:49 +0200268 Upload content for an already created entry (_id)
tierno65acb4d2018-04-06 16:42:40 +0200269 :param session: contains the used login username and working project
tiernob24258a2018-10-04 18:39:49 +0200270 :param topic: it can be: users, projects, vnfds, nsds,
271 :param _id: server id of the item
272 :param indata: data to be inserted
tierno65acb4d2018-04-06 16:42:40 +0200273 :param kwargs: used to override the indata descriptor
tiernob24258a2018-10-04 18:39:49 +0200274 :param headers: http request headers
tiernob24258a2018-10-04 18:39:49 +0200275 :return: _id: identity of the inserted data.
tierno65acb4d2018-04-06 16:42:40 +0200276 """
tiernob24258a2018-10-04 18:39:49 +0200277 if topic not in self.map_topic:
garciadeblas4568a372021-03-24 09:19:48 +0100278 raise EngineException(
279 "Unknown topic {}!!!".format(topic), HTTPStatus.INTERNAL_SERVER_ERROR
280 )
tierno04dbb0e2019-01-09 16:00:24 +0000281 with self.write_lock:
garciadeblas4568a372021-03-24 09:19:48 +0100282 return self.map_topic[topic].upload_content(
283 session, _id, indata, kwargs, headers
284 )
tiernoc94c3df2018-02-09 15:38:54 +0100285
Frank Bryden19b97522020-07-10 12:32:02 +0000286 def get_item_list(self, session, topic, filter_q=None, api_req=False):
tiernoc94c3df2018-02-09 15:38:54 +0100287 """
288 Get a list of items
289 :param session: contains the used login username and working project
tiernob24258a2018-10-04 18:39:49 +0200290 :param topic: it can be: users, projects, vnfds, nsds, ...
291 :param filter_q: filter of data to be applied
Frank Bryden19b97522020-07-10 12:32:02 +0000292 :param api_req: True if this call is serving an external API request. False if serving internal request.
tiernob24258a2018-10-04 18:39:49 +0200293 :return: The list, it can be empty if no one match the filter_q.
tiernoc94c3df2018-02-09 15:38:54 +0100294 """
tiernob24258a2018-10-04 18:39:49 +0200295 if topic not in self.map_topic:
K Sai Kiran57589552021-01-27 21:38:34 +0530296 raise EngineException("Unknown topic {}!!!".format(topic), HTTPStatus.INTERNAL_SERVER_ERROR)
Frank Bryden19b97522020-07-10 12:32:02 +0000297 return self.map_topic[topic].list(session, filter_q, api_req)
tiernof27c79b2018-03-12 17:08:42 +0100298
K Sai Kiran57589552021-01-27 21:38:34 +0530299 def get_item(self, session, topic, _id, filter_q=None, api_req=False):
tiernoc94c3df2018-02-09 15:38:54 +0100300 """
tiernob24258a2018-10-04 18:39:49 +0200301 Get complete information on an item
tiernoc94c3df2018-02-09 15:38:54 +0100302 :param session: contains the used login username and working project
tiernob24258a2018-10-04 18:39:49 +0200303 :param topic: it can be: users, projects, vnfds, nsds,
tiernoc94c3df2018-02-09 15:38:54 +0100304 :param _id: server id of the item
K Sai Kiran57589552021-01-27 21:38:34 +0530305 :param filter_q: other arguments
Frank Bryden19b97522020-07-10 12:32:02 +0000306 :param api_req: True if this call is serving an external API request. False if serving internal request.
tiernoc94c3df2018-02-09 15:38:54 +0100307 :return: dictionary, raise exception if not found.
308 """
tiernob24258a2018-10-04 18:39:49 +0200309 if topic not in self.map_topic:
K Sai Kiran57589552021-01-27 21:38:34 +0530310 raise EngineException("Unknown topic {}!!!".format(topic), HTTPStatus.INTERNAL_SERVER_ERROR)
311 return self.map_topic[topic].show(session, _id, filter_q, api_req)
tiernoc94c3df2018-02-09 15:38:54 +0100312
tierno87006042018-10-24 12:50:20 +0200313 def get_file(self, session, topic, _id, path=None, accept_header=None):
314 """
315 Get descriptor package or artifact file content
316 :param session: contains the used login username and working project
317 :param topic: it can be: users, projects, vnfds, nsds,
318 :param _id: server id of the item
319 :param path: artifact path or "$DESCRIPTOR" or None
320 :param accept_header: Content of Accept header. Must contain applition/zip or/and text/plain
321 :return: opened file plus Accept format or raises an exception
322 """
323 if topic not in self.map_topic:
garciadeblas4568a372021-03-24 09:19:48 +0100324 raise EngineException(
325 "Unknown topic {}!!!".format(topic), HTTPStatus.INTERNAL_SERVER_ERROR
326 )
tierno87006042018-10-24 12:50:20 +0200327 return self.map_topic[topic].get_file(session, _id, path, accept_header)
328
tiernob24258a2018-10-04 18:39:49 +0200329 def del_item_list(self, session, topic, _filter=None):
tiernoc94c3df2018-02-09 15:38:54 +0100330 """
331 Delete a list of items
332 :param session: contains the used login username and working project
tiernob24258a2018-10-04 18:39:49 +0200333 :param topic: it can be: users, projects, vnfds, nsds, ...
334 :param _filter: filter of data to be applied
335 :return: The deleted list, it can be empty if no one match the _filter.
tiernoc94c3df2018-02-09 15:38:54 +0100336 """
tiernob24258a2018-10-04 18:39:49 +0200337 if topic not in self.map_topic:
garciadeblas4568a372021-03-24 09:19:48 +0100338 raise EngineException(
339 "Unknown topic {}!!!".format(topic), HTTPStatus.INTERNAL_SERVER_ERROR
340 )
tierno04dbb0e2019-01-09 16:00:24 +0000341 with self.write_lock:
342 return self.map_topic[topic].delete_list(session, _filter)
tiernoc94c3df2018-02-09 15:38:54 +0100343
tiernobee3bad2019-12-05 12:26:01 +0000344 def del_item(self, session, topic, _id, not_send_msg=None):
tiernoc94c3df2018-02-09 15:38:54 +0100345 """
tiernob92094f2018-05-11 13:44:22 +0200346 Delete item by its internal id
tiernoc94c3df2018-02-09 15:38:54 +0100347 :param session: contains the used login username and working project
tiernob24258a2018-10-04 18:39:49 +0200348 :param topic: it can be: users, projects, vnfds, nsds, ...
tiernoc94c3df2018-02-09 15:38:54 +0100349 :param _id: server id of the item
tiernobee3bad2019-12-05 12:26:01 +0000350 :param not_send_msg: If False, message will not be sent to kafka.
351 If a list, message is not sent, but content is stored in this variable so that the caller can send this
352 message using its own loop. If None, message is sent
delacruzramo01b15d32019-07-02 14:37:47 +0200353 :return: dictionary with deleted item _id. It raises exception if not found.
tiernoc94c3df2018-02-09 15:38:54 +0100354 """
tiernob24258a2018-10-04 18:39:49 +0200355 if topic not in self.map_topic:
garciadeblas4568a372021-03-24 09:19:48 +0100356 raise EngineException(
357 "Unknown topic {}!!!".format(topic), HTTPStatus.INTERNAL_SERVER_ERROR
358 )
tierno04dbb0e2019-01-09 16:00:24 +0000359 with self.write_lock:
tiernobee3bad2019-12-05 12:26:01 +0000360 return self.map_topic[topic].delete(session, _id, not_send_msg=not_send_msg)
tiernoc94c3df2018-02-09 15:38:54 +0100361
tierno65ca36d2019-02-12 19:27:52 +0100362 def edit_item(self, session, topic, _id, indata=None, kwargs=None):
tiernob24258a2018-10-04 18:39:49 +0200363 """
364 Update an existing entry at database
365 :param session: contains the used login username and working project
366 :param topic: it can be: users, projects, vnfds, nsds, ...
367 :param _id: identifier to be updated
368 :param indata: data to be inserted
369 :param kwargs: used to override the indata descriptor
delacruzramo01b15d32019-07-02 14:37:47 +0200370 :return: dictionary with edited item _id, raise exception if not found.
tiernob24258a2018-10-04 18:39:49 +0200371 """
372 if topic not in self.map_topic:
garciadeblas4568a372021-03-24 09:19:48 +0100373 raise EngineException(
374 "Unknown topic {}!!!".format(topic), HTTPStatus.INTERNAL_SERVER_ERROR
375 )
tierno04dbb0e2019-01-09 16:00:24 +0000376 with self.write_lock:
tierno65ca36d2019-02-12 19:27:52 +0100377 return self.map_topic[topic].edit(session, _id, indata, kwargs)
tiernoc94c3df2018-02-09 15:38:54 +0100378
tiernod985a8d2018-10-19 14:12:28 +0200379 def upgrade_db(self, current_version, target_version):
Eduardo Sousa044f4312019-05-20 15:17:35 +0100380 if target_version not in self.map_target_version_to_int.keys():
garciadeblas4568a372021-03-24 09:19:48 +0100381 raise EngineException(
382 "Cannot upgrade to version '{}' with this version of code".format(
383 target_version
384 ),
385 http_code=HTTPStatus.INTERNAL_SERVER_ERROR,
386 )
tiernod985a8d2018-10-19 14:12:28 +0200387
Eduardo Sousa044f4312019-05-20 15:17:35 +0100388 if current_version == target_version:
389 return
garciadeblas4568a372021-03-24 09:19:48 +0100390
Eduardo Sousa044f4312019-05-20 15:17:35 +0100391 target_version_int = self.map_target_version_to_int[target_version]
392
393 if not current_version:
394 # create database version
395 serial = urandom(32)
396 version_data = {
garciadeblas4568a372021-03-24 09:19:48 +0100397 "_id": "version", # Always "version"
398 "version_int": 1000, # version number
399 "version": "1.0", # version text
400 "date": "2018-10-25", # version date
Eduardo Sousa044f4312019-05-20 15:17:35 +0100401 "description": "added serial", # changes in this version
garciadeblas4568a372021-03-24 09:19:48 +0100402 "status": "ENABLED", # ENABLED, DISABLED (migration in process), ERROR,
403 "serial": b64encode(serial),
Eduardo Sousa044f4312019-05-20 15:17:35 +0100404 }
405 self.db.create("admin", version_data)
406 self.db.set_secret_key(serial)
407 current_version = "1.0"
garciadeblas4568a372021-03-24 09:19:48 +0100408
409 if (
410 current_version in ("1.0", "1.1")
411 and target_version_int >= self.map_target_version_to_int["1.2"]
412 ):
413 if self.config["authentication"]["backend"] == "internal":
delacruzramo01b15d32019-07-02 14:37:47 +0200414 self.db.del_list("roles")
415
Eduardo Sousa044f4312019-05-20 15:17:35 +0100416 version_data = {
417 "_id": "version",
tierno1f029d82019-06-13 22:37:04 +0000418 "version_int": 1002,
419 "version": "1.2",
420 "date": "2019-06-11",
garciadeblas4568a372021-03-24 09:19:48 +0100421 "description": "set new format for roles_operations",
Eduardo Sousa044f4312019-05-20 15:17:35 +0100422 }
423
424 self.db.set_one("admin", {"_id": "version"}, version_data)
tierno1f029d82019-06-13 22:37:04 +0000425 current_version = "1.2"
Eduardo Sousa044f4312019-05-20 15:17:35 +0100426 # TODO add future migrations here
tiernod985a8d2018-10-19 14:12:28 +0200427
garciadeblas4568a372021-03-24 09:19:48 +0100428 def init_db(self, target_version="1.0"):
tierno4a946e42018-04-12 17:48:49 +0200429 """
tiernod985a8d2018-10-19 14:12:28 +0200430 Init database if empty. If not empty it checks that database version and migrates if needed
tierno4a946e42018-04-12 17:48:49 +0200431 If empty, it creates a new user admin/admin at 'users' and a new entry at 'version'
tiernod985a8d2018-10-19 14:12:28 +0200432 :param target_version: check desired database version. Migrate to it if possible or raises exception
tierno4a946e42018-04-12 17:48:49 +0200433 :return: None if ok, exception if error or if the version is different.
434 """
tiernod985a8d2018-10-19 14:12:28 +0200435
garciadeblas4568a372021-03-24 09:19:48 +0100436 version_data = self.db.get_one(
437 "admin", {"_id": "version"}, fail_on_empty=False, fail_on_more=True
438 )
tiernod985a8d2018-10-19 14:12:28 +0200439 # check database status is ok
garciadeblas4568a372021-03-24 09:19:48 +0100440 if version_data and version_data.get("status") != "ENABLED":
441 raise EngineException(
442 "Wrong database status '{}'".format(version_data["status"]),
443 HTTPStatus.INTERNAL_SERVER_ERROR,
444 )
tiernod985a8d2018-10-19 14:12:28 +0200445
446 # check version
447 db_version = None if not version_data else version_data.get("version")
448 if db_version != target_version:
449 self.upgrade_db(db_version, target_version)
450
tierno4a946e42018-04-12 17:48:49 +0200451 return