1 # -*- coding: utf-8 -*-
3 # 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
7 # http://www.apache.org/licenses/LICENSE-2.0
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
13 # See the License for the specific language governing permissions and
14 # limitations under the License.
19 from osm_common
import (
26 version
as common_version
,
28 from osm_common
.dbbase
import DbException
29 from osm_common
.fsbase
import FsException
30 from osm_common
.msgbase
import MsgException
31 from http
import HTTPStatus
33 from osm_nbi
.authconn_keystone
import AuthconnKeystone
34 from osm_nbi
.authconn_internal
import AuthconnInternal
35 from osm_nbi
.authconn_tacacs
import AuthconnTacacs
36 from osm_nbi
.base_topic
import EngineException
, versiontuple
37 from osm_nbi
.admin_topics
import VimAccountTopic
, WimAccountTopic
, SdnTopic
38 from osm_nbi
.admin_topics
import K8sClusterTopic
, K8sRepoTopic
, OsmRepoTopic
39 from osm_nbi
.admin_topics
import VcaTopic
, PaasTopic
40 from osm_nbi
.admin_topics
import UserTopicAuth
, ProjectTopicAuth
, RoleTopicAuth
41 from osm_nbi
.descriptor_topics
import (
48 from osm_nbi
.instance_topics
import (
55 from osm_nbi
.vnf_instance_topics
import VnfInstances
, VnfLcmOpTopic
56 from osm_nbi
.pmjobs_topics
import PmJobsTopic
57 from osm_nbi
.subscription_topics
import NslcmSubscriptionsTopic
58 from osm_nbi
.osm_vnfm
.vnf_subscription
import VnflcmSubscriptionsTopic
59 from base64
import b64encode
60 from os
import urandom
# , path
61 from threading
import Lock
63 __author__
= "Alfonso Tierno <alfonso.tiernosepulveda@telefonica.com>"
64 min_common_version
= "0.1.16"
68 map_from_topic_to_class
= {
75 "nslcmops": NsLcmOpTopic
,
76 "vim_accounts": VimAccountTopic
,
77 "wim_accounts": WimAccountTopic
,
79 "k8sclusters": K8sClusterTopic
,
82 "k8srepos": K8sRepoTopic
,
83 "osmrepos": OsmRepoTopic
,
84 "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
88 "nsilcmops": NsiLcmOpTopic
,
89 "vnfpkgops": VnfPkgOpTopic
,
90 "nslcm_subscriptions": NslcmSubscriptionsTopic
,
91 "vnf_instances": VnfInstances
,
92 "vnflcmops": VnfLcmOpTopic
,
93 "vnflcm_subscriptions": VnflcmSubscriptionsTopic
,
94 # [NEW_TOPIC]: add an entry here
95 # "pm_jobs": PmJobsTopic will be added manually because it needs other parameters
98 map_target_version_to_int
= {
102 # Add new versions here
105 def __init__(self
, authenticator
):
111 # self.operations = None
112 self
.logger
= logging
.getLogger("nbi.engine")
114 self
.write_lock
= None
115 # self.token_cache = token_cache
116 self
.authenticator
= authenticator
118 def start(self
, config
):
120 Connect to database, filesystem storage, and messaging
121 :param config: two level dictionary with configuration. Top level should contain 'database', 'storage',
125 # check right version of common
126 if versiontuple(common_version
) < versiontuple(min_common_version
):
127 raise EngineException(
128 "Not compatible osm/common version '{}'. Needed '{}' or higher".format(
129 common_version
, min_common_version
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"])
142 raise EngineException(
143 "Invalid configuration param '{}' at '[database]':'driver'".format(
144 config
["database"]["driver"]
148 if config
["storage"]["driver"] == "local":
149 self
.fs
= fslocal
.FsLocal()
150 self
.fs
.fs_connect(config
["storage"])
151 elif config
["storage"]["driver"] == "mongo":
152 self
.fs
= fsmongo
.FsMongo()
153 self
.fs
.fs_connect(config
["storage"])
155 raise EngineException(
156 "Invalid configuration param '{}' at '[storage]':'driver'".format(
157 config
["storage"]["driver"]
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"])
168 raise EngineException(
169 "Invalid configuration param '{}' at '[message]':'driver'".format(
170 config
["message"]["driver"]
173 if not self
.authconn
:
174 if config
["authentication"]["backend"] == "keystone":
175 self
.authconn
= AuthconnKeystone(
176 config
["authentication"],
178 self
.authenticator
.role_permissions
,
180 elif config
["authentication"]["backend"] == "tacacs":
181 self
.authconn
= AuthconnTacacs(
182 config
["authentication"],
184 self
.authenticator
.role_permissions
,
187 self
.authconn
= AuthconnInternal(
188 config
["authentication"],
190 self
.authenticator
.role_permissions
,
192 # if not self.operations:
193 # if "resources_to_operations" in config["rbac"]:
194 # resources_to_operations_file = config["rbac"]["resources_to_operations"]
197 # __file__[:__file__.rfind("engine.py")] + "resources_to_operations.yml",
198 # "./resources_to_operations.yml"
200 # for config_file in possible_paths:
201 # if path.isfile(config_file):
202 # resources_to_operations_file = config_file
204 # if not resources_to_operations_file:
205 # raise EngineException("Invalid permission configuration:"
206 # "resources_to_operations file missing")
208 # with open(resources_to_operations_file, 'r') as f:
209 # resources_to_operations = yaml.load(f, Loader=yaml.Loader)
211 # self.operations = []
213 # for _, value in resources_to_operations["resources_to_operations"].items():
214 # if value not in self.operations:
215 # self.operations += [value]
217 self
.write_lock
= Lock()
218 # create one class per topic
219 for topic
, topic_class
in self
.map_from_topic_to_class
.items():
220 # if self.auth and topic_class in (UserTopicAuth, ProjectTopicAuth):
221 # self.map_topic[topic] = topic_class(self.db, self.fs, self.msg, self.auth)
222 self
.map_topic
[topic
] = topic_class(
223 self
.db
, self
.fs
, self
.msg
, self
.authconn
226 self
.map_topic
["pm_jobs"] = PmJobsTopic(
228 config
["prometheus"].get("host"),
229 config
["prometheus"].get("port"),
231 except (DbException
, FsException
, MsgException
) as e
:
232 raise EngineException(str(e
), http_code
=e
.http_code
)
237 self
.db
.db_disconnect()
239 self
.fs
.fs_disconnect()
241 self
.msg
.disconnect()
242 self
.write_lock
= None
243 except (DbException
, FsException
, MsgException
) as e
:
244 raise EngineException(str(e
), http_code
=e
.http_code
)
247 self
, rollback
, session
, topic
, indata
=None, kwargs
=None, headers
=None
250 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
252 :param rollback: list to append created items at database in case a rollback must to be done
253 :param session: contains the used login username and working project, force to avoid checkins, public
254 :param topic: it can be: users, projects, vim_accounts, sdns, nsrs, nsds, vnfds
255 :param indata: data to be inserted
256 :param kwargs: used to override the indata descriptor
257 :param headers: http request headers
258 :return: _id: identity of the inserted data.
260 if topic
not in self
.map_topic
:
261 raise EngineException(
262 "Unknown topic {}!!!".format(topic
), HTTPStatus
.INTERNAL_SERVER_ERROR
264 with self
.write_lock
:
265 return self
.map_topic
[topic
].new(rollback
, session
, indata
, kwargs
, headers
)
267 def upload_content(self
, session
, topic
, _id
, indata
, kwargs
, headers
):
269 Upload content for an already created entry (_id)
270 :param session: contains the used login username and working project
271 :param topic: it can be: users, projects, vnfds, nsds,
272 :param _id: server id of the item
273 :param indata: data to be inserted
274 :param kwargs: used to override the indata descriptor
275 :param headers: http request headers
276 :return: _id: identity of the inserted data.
278 if topic
not in self
.map_topic
:
279 raise EngineException(
280 "Unknown topic {}!!!".format(topic
), HTTPStatus
.INTERNAL_SERVER_ERROR
282 with self
.write_lock
:
283 return self
.map_topic
[topic
].upload_content(
284 session
, _id
, indata
, kwargs
, headers
287 def get_item_list(self
, session
, topic
, filter_q
=None, api_req
=False):
290 :param session: contains the used login username and working project
291 :param topic: it can be: users, projects, vnfds, nsds, ...
292 :param filter_q: filter of data to be applied
293 :param api_req: True if this call is serving an external API request. False if serving internal request.
294 :return: The list, it can be empty if no one match the filter_q.
296 if topic
not in self
.map_topic
:
297 raise EngineException(
298 "Unknown topic {}!!!".format(topic
), HTTPStatus
.INTERNAL_SERVER_ERROR
300 return self
.map_topic
[topic
].list(session
, filter_q
, api_req
)
302 def get_item(self
, session
, topic
, _id
, filter_q
=None, api_req
=False):
304 Get complete information on an item
305 :param session: contains the used login username and working project
306 :param topic: it can be: users, projects, vnfds, nsds,
307 :param _id: server id of the item
308 :param filter_q: other arguments
309 :param api_req: True if this call is serving an external API request. False if serving internal request.
310 :return: dictionary, raise exception if not found.
312 if topic
not in self
.map_topic
:
313 raise EngineException(
314 "Unknown topic {}!!!".format(topic
), HTTPStatus
.INTERNAL_SERVER_ERROR
316 return self
.map_topic
[topic
].show(session
, _id
, filter_q
, api_req
)
318 def get_file(self
, session
, topic
, _id
, path
=None, accept_header
=None):
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
328 if topic
not in self
.map_topic
:
329 raise EngineException(
330 "Unknown topic {}!!!".format(topic
), HTTPStatus
.INTERNAL_SERVER_ERROR
332 return self
.map_topic
[topic
].get_file(session
, _id
, path
, accept_header
)
334 def del_item_list(self
, session
, topic
, _filter
=None):
336 Delete a list of items
337 :param session: contains the used login username and working project
338 :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.
342 if topic
not in self
.map_topic
:
343 raise EngineException(
344 "Unknown topic {}!!!".format(topic
), HTTPStatus
.INTERNAL_SERVER_ERROR
346 with self
.write_lock
:
347 return self
.map_topic
[topic
].delete_list(session
, _filter
)
349 def del_item(self
, session
, topic
, _id
, not_send_msg
=None):
351 Delete item by its internal id
352 :param session: contains the used login username and working project
353 :param topic: it can be: users, projects, vnfds, nsds, ...
354 :param _id: server id of the item
355 :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
358 :return: dictionary with deleted item _id. It raises exception if not found.
360 if topic
not in self
.map_topic
:
361 raise EngineException(
362 "Unknown topic {}!!!".format(topic
), HTTPStatus
.INTERNAL_SERVER_ERROR
364 with self
.write_lock
:
365 return self
.map_topic
[topic
].delete(session
, _id
, not_send_msg
=not_send_msg
)
367 def edit_item(self
, session
, topic
, _id
, indata
=None, kwargs
=None):
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
375 :return: dictionary with edited item _id, raise exception if not found.
377 if topic
not in self
.map_topic
:
378 raise EngineException(
379 "Unknown topic {}!!!".format(topic
), HTTPStatus
.INTERNAL_SERVER_ERROR
381 with self
.write_lock
:
382 return self
.map_topic
[topic
].edit(session
, _id
, indata
, kwargs
)
384 def upgrade_db(self
, current_version
, target_version
):
385 if target_version
not in self
.map_target_version_to_int
.keys():
386 raise EngineException(
387 "Cannot upgrade to version '{}' with this version of code".format(
390 http_code
=HTTPStatus
.INTERNAL_SERVER_ERROR
,
393 if current_version
== target_version
:
396 target_version_int
= self
.map_target_version_to_int
[target_version
]
398 if not current_version
:
399 # create database version
402 "_id": "version", # Always "version"
403 "version_int": 1000, # version number
404 "version": "1.0", # version text
405 "date": "2018-10-25", # version date
406 "description": "added serial", # changes in this version
407 "status": "ENABLED", # ENABLED, DISABLED (migration in process), ERROR,
408 "serial": b64encode(serial
),
410 self
.db
.create("admin", version_data
)
411 self
.db
.set_secret_key(serial
)
412 current_version
= "1.0"
415 current_version
in ("1.0", "1.1")
416 and target_version_int
>= self
.map_target_version_to_int
["1.2"]
418 if self
.config
["authentication"]["backend"] == "internal":
419 self
.db
.del_list("roles")
425 "date": "2019-06-11",
426 "description": "set new format for roles_operations",
429 self
.db
.set_one("admin", {"_id": "version"}, version_data
)
430 current_version
= "1.2"
431 # TODO add future migrations here
433 def init_db(self
, target_version
="1.0"):
435 Init database if empty. If not empty it checks that database version and migrates if needed
436 If empty, it creates a new user admin/admin at 'users' and a new entry at 'version'
437 :param target_version: check desired database version. Migrate to it if possible or raises exception
438 :return: None if ok, exception if error or if the version is different.
441 version_data
= self
.db
.get_one(
442 "admin", {"_id": "version"}, fail_on_empty
=False, fail_on_more
=True
444 # check database status is ok
445 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
,
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
)