X-Git-Url: https://osm.etsi.org/gitweb/?a=blobdiff_plain;f=n2vc%2Fn2vc_juju_conn.py;h=55220d64ab389f178fd4ac13dea63a5809f88b49;hb=HEAD;hp=eed2f30eafcc794dfb1dba11533576258a151b3e;hpb=82b591ceed704c798ead2d9104085a08e75b511b;p=osm%2FN2VC.git diff --git a/n2vc/n2vc_juju_conn.py b/n2vc/n2vc_juju_conn.py index eed2f30..f28a9bd 100644 --- a/n2vc/n2vc_juju_conn.py +++ b/n2vc/n2vc_juju_conn.py @@ -24,19 +24,25 @@ import asyncio import logging from n2vc.config import EnvironConfig +from n2vc.definitions import RelationEndpoint from n2vc.exceptions import ( N2VCBadArgumentsException, N2VCException, N2VCConnectionException, N2VCExecutionException, + N2VCApplicationExists, + JujuApplicationExists, # N2VCNotFound, MethodNotImplemented, ) from n2vc.n2vc_conn import N2VCConnector from n2vc.n2vc_conn import obj_to_dict, obj_to_yaml -from n2vc.libjuju import Libjuju +from n2vc.libjuju import Libjuju, retry_callback from n2vc.store import MotorStore +from n2vc.utils import get_ee_id_components, generate_random_alfanum_string from n2vc.vca.connection import get_connection +from retrying_async import retry +from typing import Tuple class N2VCJujuConnector(N2VCConnector): @@ -55,7 +61,6 @@ class N2VCJujuConnector(N2VCConnector): db: object, fs: object, log: object = None, - loop: object = None, on_update_db=None, ): """ @@ -64,19 +69,11 @@ class N2VCJujuConnector(N2VCConnector): :param: db: Database object from osm_common :param: fs: Filesystem object from osm_common :param: log: Logger - :param: loop: Asyncio loop :param: on_update_db: Callback function to be called for updating the database. """ # parent class constructor - N2VCConnector.__init__( - self, - db=db, - fs=fs, - log=log, - loop=loop, - on_update_db=on_update_db, - ) + N2VCConnector.__init__(self, db=db, fs=fs, log=log, on_update_db=on_update_db) # silence websocket traffic log logging.getLogger("websockets.protocol").setLevel(logging.INFO) @@ -87,8 +84,8 @@ class N2VCJujuConnector(N2VCConnector): db_uri = EnvironConfig(prefixes=["OSMLCM_", "OSMMON_"]).get("database_uri") self._store = MotorStore(db_uri) - self.loading_libjuju = asyncio.Lock(loop=self.loop) - + self.loading_libjuju = asyncio.Lock() + self.delete_namespace_locks = {} self.log.info("N2VC juju connector initialized") async def get_status( @@ -221,10 +218,7 @@ class N2VCJujuConnector(N2VCConnector): # create or reuse a new juju machine try: if not await libjuju.model_exists(model_name): - await libjuju.add_model( - model_name, - libjuju.vca_connection.lxd_cloud, - ) + await libjuju.add_model(model_name, libjuju.vca_connection.lxd_cloud) machine, new = await libjuju.create_machine( model_name=model_name, machine_id=machine_id, @@ -250,9 +244,7 @@ class N2VCJujuConnector(N2VCConnector): raise N2VCException(message=message) # new machine credentials - credentials = { - "hostname": machine.dns_name, - } + credentials = {"hostname": machine.dns_name} self.log.info( "Execution environment created. ee_id: {}, credentials: {}".format( @@ -332,10 +324,7 @@ class N2VCJujuConnector(N2VCConnector): # register machine on juju try: if not await libjuju.model_exists(model_name): - await libjuju.add_model( - model_name, - libjuju.vca_connection.lxd_cloud, - ) + await libjuju.add_model(model_name, libjuju.vca_connection.lxd_cloud) machine_id = await libjuju.provision_machine( model_name=model_name, hostname=hostname, @@ -364,6 +353,15 @@ class N2VCJujuConnector(N2VCConnector): return ee_id + # In case of native_charm is being deployed, if JujuApplicationExists error happens + # it will try to add_unit + @retry( + attempts=3, + delay=5, + retry_exceptions=(N2VCApplicationExists,), + timeout=None, + callback=retry_callback, + ) async def install_configuration_sw( self, ee_id: str, @@ -374,6 +372,8 @@ class N2VCJujuConnector(N2VCConnector): config: dict = None, num_units: int = 1, vca_id: str = None, + scaling_out: bool = False, + vca_type: str = None, ): """ Install the software inside the execution environment identified by ee_id @@ -395,6 +395,8 @@ class N2VCJujuConnector(N2VCConnector): :param: config: Dictionary with deployment config information. :param: num_units: Number of units to deploy of a particular charm. :param: vca_id: VCA ID + :param: scaling_out: Boolean to indicate if it is a scaling out operation + :param: vca_type: VCA type """ self.log.info( @@ -443,7 +445,7 @@ class N2VCJujuConnector(N2VCConnector): artifact_path = artifact_path.replace("//", "/") # check charm path - if not self.fs.file_exists(artifact_path, mode="dir"): + if not self.fs.file_exists(artifact_path): msg = "artifact path does not exist: {}".format(artifact_path) raise N2VCBadArgumentsException(message=msg, bad_args=["artifact_path"]) @@ -453,20 +455,36 @@ class N2VCJujuConnector(N2VCConnector): full_path = self.fs.path + "/" + artifact_path try: - await libjuju.deploy_charm( - model_name=model_name, - application_name=application_name, - path=full_path, - machine_id=machine_id, - db_dict=db_dict, - progress_timeout=progress_timeout, - total_timeout=total_timeout, - config=config, - num_units=num_units, + if vca_type == "native_charm" and await libjuju.check_application_exists( + model_name, application_name + ): + await libjuju.add_unit( + application_name=application_name, + model_name=model_name, + machine_id=machine_id, + db_dict=db_dict, + progress_timeout=progress_timeout, + total_timeout=total_timeout, + ) + else: + await libjuju.deploy_charm( + model_name=model_name, + application_name=application_name, + path=full_path, + machine_id=machine_id, + db_dict=db_dict, + progress_timeout=progress_timeout, + total_timeout=total_timeout, + config=config, + num_units=num_units, + ) + except JujuApplicationExists as e: + raise N2VCApplicationExists( + message="Error deploying charm into ee={} : {}".format(ee_id, e.message) ) except Exception as e: raise N2VCException( - message="Error desploying charm into ee={} : {}".format(ee_id, e) + message="Error deploying charm into ee={} : {}".format(ee_id, e) ) self.log.info("Configuration sw installed") @@ -524,7 +542,7 @@ class N2VCJujuConnector(N2VCConnector): artifact_path = artifact_path.replace("//", "/") # check charm path - if not self.fs.file_exists(artifact_path, mode="dir"): + if not self.fs.file_exists(artifact_path): msg = "artifact path does not exist: {}".format(artifact_path) raise N2VCBadArgumentsException(message=msg, bad_args=["artifact_path"]) @@ -536,10 +554,7 @@ class N2VCJujuConnector(N2VCConnector): _, ns_id, _, _, _ = self._get_namespace_components(namespace=namespace) model_name = "{}-k8s".format(ns_id) if not await libjuju.model_exists(model_name): - await libjuju.add_model( - model_name, - libjuju.vca_connection.k8s_cloud, - ) + await libjuju.add_model(model_name, libjuju.vca_connection.k8s_cloud) application_name = self._get_application_name(namespace) try: @@ -558,9 +573,7 @@ class N2VCJujuConnector(N2VCConnector): self.log.info("K8s proxy charm installed") ee_id = N2VCJujuConnector._build_ee_id( - model_name=model_name, - application_name=application_name, - machine_id="k8s", + model_name=model_name, application_name=application_name, machine_id="k8s" ) self._write_ee_id_db(db_dict=db_dict, ee_id=ee_id) @@ -689,70 +702,45 @@ class N2VCJujuConnector(N2VCConnector): return await libjuju.get_metrics(model_name, application_name) async def add_relation( - self, - ee_id_1: str, - ee_id_2: str, - endpoint_1: str, - endpoint_2: str, - vca_id: str = None, + self, provider: RelationEndpoint, requirer: RelationEndpoint ): """ Add relation between two charmed endpoints - :param: ee_id_1: The id of the first execution environment - :param: ee_id_2: The id of the second execution environment - :param: endpoint_1: The endpoint in the first execution environment - :param: endpoint_2: The endpoint in the second execution environment - :param: vca_id: VCA ID + :param: provider: Provider relation endpoint + :param: requirer: Requirer relation endpoint """ - self.log.debug( - "adding new relation between {} and {}, endpoints: {}, {}".format( - ee_id_1, ee_id_2, endpoint_1, endpoint_2 - ) + self.log.debug(f"adding new relation between {provider} and {requirer}") + cross_model_relation = ( + provider.model_name != requirer.model_name + or provider.vca_id != requirer.vca_id ) - libjuju = await self._get_libjuju(vca_id) - - # check arguments - if not ee_id_1: - message = "EE 1 is mandatory" - self.log.error(message) - raise N2VCBadArgumentsException(message=message, bad_args=["ee_id_1"]) - if not ee_id_2: - message = "EE 2 is mandatory" - self.log.error(message) - raise N2VCBadArgumentsException(message=message, bad_args=["ee_id_2"]) - if not endpoint_1: - message = "endpoint 1 is mandatory" - self.log.error(message) - raise N2VCBadArgumentsException(message=message, bad_args=["endpoint_1"]) - if not endpoint_2: - message = "endpoint 2 is mandatory" - self.log.error(message) - raise N2VCBadArgumentsException(message=message, bad_args=["endpoint_2"]) - - # get the model, the applications and the machines from the ee_id's - model_1, app_1, _machine_1 = self._get_ee_id_components(ee_id_1) - model_2, app_2, _machine_2 = self._get_ee_id_components(ee_id_2) - - # model must be the same - if model_1 != model_2: - message = "EE models are not the same: {} vs {}".format(ee_id_1, ee_id_2) - self.log.error(message) - raise N2VCBadArgumentsException( - message=message, bad_args=["ee_id_1", "ee_id_2"] - ) - - # add juju relations between two applications try: - await libjuju.add_relation( - model_name=model_1, - endpoint_1="{}:{}".format(app_1, endpoint_1), - endpoint_2="{}:{}".format(app_2, endpoint_2), - ) + if cross_model_relation: + # Cross-model relation + provider_libjuju = await self._get_libjuju(provider.vca_id) + requirer_libjuju = await self._get_libjuju(requirer.vca_id) + offer = await provider_libjuju.offer(provider) + if offer: + saas_name = await requirer_libjuju.consume( + requirer.model_name, offer, provider_libjuju + ) + await requirer_libjuju.add_relation( + requirer.model_name, requirer.endpoint, saas_name + ) + else: + # Standard relation + vca_id = provider.vca_id + model = provider.model_name + libjuju = await self._get_libjuju(vca_id) + # add juju relations between two applications + await libjuju.add_relation( + model_name=model, + endpoint_1=provider.endpoint, + endpoint_2=requirer.endpoint, + ) except Exception as e: - message = "Error adding relation between {} and {}: {}".format( - ee_id_1, ee_id_2, e - ) + message = f"Error adding relation between {provider} and {requirer}: {e}" self.log.error(message) raise N2VCException(message=message) @@ -784,33 +772,60 @@ class N2VCJujuConnector(N2VCConnector): :param: vca_id: VCA ID """ self.log.info("Deleting namespace={}".format(namespace)) - libjuju = await self._get_libjuju(vca_id) + will_not_delete = False + if namespace not in self.delete_namespace_locks: + self.delete_namespace_locks[namespace] = asyncio.Lock() + delete_lock = self.delete_namespace_locks[namespace] - # check arguments - if namespace is None: - raise N2VCBadArgumentsException( - message="namespace is mandatory", bad_args=["namespace"] - ) + while delete_lock.locked(): + will_not_delete = True + await asyncio.sleep(0.1) - _nsi_id, ns_id, _vnf_id, _vdu_id, _vdu_count = self._get_namespace_components( - namespace=namespace - ) - if ns_id is not None: - try: - models = await libjuju.list_models(contains=ns_id) - for model in models: - await libjuju.destroy_model( - model_name=model, total_timeout=total_timeout + if will_not_delete: + self.log.info("Namespace {} deleted by another worker.".format(namespace)) + return + + try: + async with delete_lock: + libjuju = await self._get_libjuju(vca_id) + + # check arguments + if namespace is None: + raise N2VCBadArgumentsException( + message="namespace is mandatory", bad_args=["namespace"] ) - except Exception as e: - raise N2VCException( - message="Error deleting namespace {} : {}".format(namespace, e) - ) - else: - raise N2VCBadArgumentsException( - message="only ns_id is permitted to delete yet", bad_args=["namespace"] - ) + ( + _nsi_id, + ns_id, + _vnf_id, + _vdu_id, + _vdu_count, + ) = self._get_namespace_components(namespace=namespace) + if ns_id is not None: + try: + models = await libjuju.list_models(contains=ns_id) + for model in models: + await libjuju.destroy_model( + model_name=model, total_timeout=total_timeout + ) + except Exception as e: + self.log.error(f"Error deleting namespace {namespace} : {e}") + raise N2VCException( + message="Error deleting namespace {} : {}".format( + namespace, e + ) + ) + else: + raise N2VCBadArgumentsException( + message="only ns_id is permitted to delete yet", + bad_args=["namespace"], + ) + except Exception as e: + self.log.error(f"Error deleting namespace {namespace} : {e}") + raise e + finally: + self.delete_namespace_locks.pop(namespace) self.log.info("Namespace {} deleted".format(namespace)) async def delete_execution_environment( @@ -819,7 +834,9 @@ class N2VCJujuConnector(N2VCConnector): db_dict: dict = None, total_timeout: float = None, scaling_in: bool = False, + vca_type: str = None, vca_id: str = None, + application_to_delete: str = None, ): """ Delete an execution environment @@ -829,9 +846,11 @@ class N2VCJujuConnector(N2VCConnector): {collection: , filter: {}, path: }, e.g. {collection: "nsrs", filter: {_id: , path: "_admin.deployed.VCA.3"} - :param: total_timeout: Total timeout - :param: scaling_in: Boolean to indicate if is it a scaling in operation - :param: vca_id: VCA ID + :param total_timeout: Total timeout + :param scaling_in: Boolean to indicate if it is a scaling in operation + :param vca_type: VCA type + :param vca_id: VCA ID + :param application_to_delete: name of the single application to be deleted """ self.log.info("Deleting execution environment ee_id={}".format(ee_id)) libjuju = await self._get_libjuju(vca_id) @@ -842,15 +861,40 @@ class N2VCJujuConnector(N2VCConnector): message="ee_id is mandatory", bad_args=["ee_id"] ) - model_name, application_name, _machine_id = self._get_ee_id_components( + model_name, application_name, machine_id = self._get_ee_id_components( ee_id=ee_id ) try: - if not scaling_in: + if application_to_delete == application_name: + # destroy the application + await libjuju.destroy_application( + model_name=model_name, + application_name=application_name, + total_timeout=total_timeout, + ) + # if model is empty delete it + controller = await libjuju.get_controller() + model = await libjuju.get_model( + controller=controller, + model_name=model_name, + ) + if not model.applications: + self.log.info("Model {} is empty, deleting it".format(model_name)) + await libjuju.destroy_model( + model_name=model_name, + total_timeout=total_timeout, + ) + elif not scaling_in: # destroy the model - # TODO: should this be removed? await libjuju.destroy_model( + model_name=model_name, total_timeout=total_timeout + ) + elif vca_type == "native_charm" and scaling_in: + # destroy the unit in the application + await libjuju.destroy_unit( + application_name=application_name, model_name=model_name, + machine_id=machine_id, total_timeout=total_timeout, ) else: @@ -878,6 +922,7 @@ class N2VCJujuConnector(N2VCConnector): progress_timeout: float = None, total_timeout: float = None, vca_id: str = None, + vca_type: str = None, ) -> str: """ Execute a primitive in the execution environment @@ -896,6 +941,7 @@ class N2VCJujuConnector(N2VCConnector): :param: progress_timeout: Progress timeout :param: total_timeout: Total timeout :param: vca_id: VCA ID + :param: vca_type: VCA type :returns str: primitive result, if ok. It raises exceptions in case of fail """ @@ -922,8 +968,12 @@ class N2VCJujuConnector(N2VCConnector): ( model_name, application_name, - _machine_id, + machine_id, ) = N2VCJujuConnector._get_ee_id_components(ee_id=ee_id) + # To run action on the leader unit in libjuju.execute_action function, + # machine_id must be set to None if vca_type is not native_charm + if vca_type != "native_charm": + machine_id = None except Exception: raise N2VCBadArgumentsException( message="ee_id={} is not a valid execution environment id".format( @@ -941,8 +991,7 @@ class N2VCJujuConnector(N2VCConnector): config=params_dict, ) actions = await libjuju.get_actions( - application_name=application_name, - model_name=model_name, + application_name=application_name, model_name=model_name ) self.log.debug( "Application {} has these actions: {}".format( @@ -1003,25 +1052,89 @@ class N2VCJujuConnector(N2VCConnector): application_name=application_name, action_name=primitive_name, db_dict=db_dict, + machine_id=machine_id, progress_timeout=progress_timeout, total_timeout=total_timeout, - **params_dict + **params_dict, ) if status == "completed": return output else: - raise Exception("status is not completed: {}".format(status)) + if "output" in output: + raise Exception(f'{status}: {output["output"]}') + else: + raise Exception( + f"{status}: No further information received from action" + ) + except Exception as e: - self.log.error( - "Error executing primitive {}: {}".format(primitive_name, e) - ) + self.log.error(f"Error executing primitive {primitive_name}: {e}") raise N2VCExecutionException( - message="Error executing primitive {} into ee={} : {}".format( - primitive_name, ee_id, e - ), + message=f"Error executing primitive {primitive_name} in ee={ee_id}: {e}", primitive_name=primitive_name, ) + async def upgrade_charm( + self, + ee_id: str = None, + path: str = None, + charm_id: str = None, + charm_type: str = None, + timeout: float = None, + ) -> str: + """This method upgrade charms in VNFs + + Args: + ee_id: Execution environment id + path: Local path to the charm + charm_id: charm-id + charm_type: Charm type can be lxc-proxy-charm, native-charm or k8s-proxy-charm + timeout: (Float) Timeout for the ns update operation + + Returns: + The output of the update operation if status equals to "completed" + + """ + self.log.info("Upgrading charm: {} on ee: {}".format(path, ee_id)) + libjuju = await self._get_libjuju(charm_id) + + # check arguments + if ee_id is None or len(ee_id) == 0: + raise N2VCBadArgumentsException( + message="ee_id is mandatory", bad_args=["ee_id"] + ) + try: + ( + model_name, + application_name, + machine_id, + ) = N2VCJujuConnector._get_ee_id_components(ee_id=ee_id) + + except Exception: + raise N2VCBadArgumentsException( + message="ee_id={} is not a valid execution environment id".format( + ee_id + ), + bad_args=["ee_id"], + ) + + try: + await libjuju.upgrade_charm( + application_name=application_name, + path=path, + model_name=model_name, + total_timeout=timeout, + ) + + return f"Charm upgraded with application name {application_name}" + + except Exception as e: + self.log.error("Error upgrading charm {}: {}".format(path, e)) + + raise N2VCException( + message="Error upgrading charm {} in ee={} : {}".format(path, ee_id, e) + ) + async def disconnect(self, vca_id: str = None): """ Disconnect from VCA @@ -1058,19 +1171,13 @@ class N2VCJujuConnector(N2VCConnector): if not self.libjuju: async with self.loading_libjuju: vca_connection = await get_connection(self._store) - self.libjuju = Libjuju(vca_connection, loop=self.loop, log=self.log) + self.libjuju = Libjuju(vca_connection, log=self.log) return self.libjuju else: vca_connection = await get_connection(self._store, vca_id) - return Libjuju( - vca_connection, - loop=self.loop, - log=self.log, - n2vc=self, - ) + return Libjuju(vca_connection, log=self.log, n2vc=self) def _write_ee_id_db(self, db_dict: dict, ee_id: str): - # write ee_id to database: _admin.deployed.VCA.x try: the_table = db_dict["collection"] @@ -1111,30 +1218,43 @@ class N2VCJujuConnector(N2VCConnector): :return: model_name, application_name, machine_id """ - if ee_id is None: - return None, None, None - - # split components of id - parts = ee_id.split(".") - model_name = parts[0] - application_name = parts[1] - machine_id = parts[2] - return model_name, application_name, machine_id + return get_ee_id_components(ee_id) - def _get_application_name(self, namespace: str) -> str: - """ - Build application name from namespace - :param namespace: - :return: app-vnf--vdu--cnt- + @staticmethod + def _find_charm_level(vnf_id: str, vdu_id: str) -> str: + """Decides the charm level. + Args: + vnf_id (str): VNF id + vdu_id (str): VDU id + + Returns: + charm_level (str): ns-level or vnf-level or vdu-level """ + if vdu_id and not vnf_id: + raise N2VCException(message="If vdu-id exists, vnf-id should be provided.") + if vnf_id and vdu_id: + return "vdu-level" + if vnf_id and not vdu_id: + return "vnf-level" + if not vnf_id and not vdu_id: + return "ns-level" - # TODO: Enforce the Juju 50-character application limit + @staticmethod + def _generate_backward_compatible_application_name( + vnf_id: str, vdu_id: str, vdu_count: str + ) -> str: + """Generate backward compatible application name + by limiting the app name to 50 characters. - # split namespace components - _, _, vnf_id, vdu_id, vdu_count = self._get_namespace_components( - namespace=namespace - ) + Args: + vnf_id (str): VNF ID + vdu_id (str): VDU ID + vdu_count (str): vdu-count-index + + Returns: + application_name (str): generated application name + """ if vnf_id is None or len(vnf_id) == 0: vnf_id = "" else: @@ -1152,7 +1272,233 @@ class N2VCJujuConnector(N2VCConnector): else: vdu_count = "-cnt-" + vdu_count - application_name = "app-{}{}{}".format(vnf_id, vdu_id, vdu_count) + # Generate a random suffix with 5 characters (the default size used by K8s) + random_suffix = generate_random_alfanum_string(size=5) + + application_name = "app-{}{}{}-{}".format( + vnf_id, vdu_id, vdu_count, random_suffix + ) + return application_name + + @staticmethod + def _get_vca_record(search_key: str, vca_records: list, vdu_id: str) -> dict: + """Get the correct VCA record dict depending on the search key + + Args: + search_key (str): keyword to find the correct VCA record + vca_records (list): All VCA records as list + vdu_id (str): VDU ID + + Returns: + vca_record (dict): Dictionary which includes the correct VCA record + + """ + return next( + filter(lambda record: record[search_key] == vdu_id, vca_records), {} + ) + + @staticmethod + def _generate_application_name( + charm_level: str, + vnfrs: dict, + vca_records: list, + vnf_count: str = None, + vdu_id: str = None, + vdu_count: str = None, + ) -> str: + """Generate application name to make the relevant charm of VDU/KDU + in the VNFD descriptor become clearly visible. + Limiting the app name to 50 characters. + + Args: + charm_level (str): level of charm + vnfrs (dict): vnf record dict + vca_records (list): db_nsr["_admin"]["deployed"]["VCA"] as list + vnf_count (str): vnf count index + vdu_id (str): VDU ID + vdu_count (str): vdu count index + + Returns: + application_name (str): generated application name + + """ + application_name = "" + if charm_level == "ns-level": + if len(vca_records) != 1: + raise N2VCException(message="One VCA record is expected.") + # Only one VCA record is expected if it's ns-level charm. + # Shorten the charm name to its first 40 characters. + charm_name = vca_records[0]["charm_name"][:40] + if not charm_name: + raise N2VCException(message="Charm name should be provided.") + application_name = charm_name + "-ns" + + elif charm_level == "vnf-level": + if len(vca_records) < 1: + raise N2VCException(message="One or more VCA record is expected.") + # If VNF is scaled, more than one VCA record may be included in vca_records + # but ee_descriptor_id is same. + # Shorten the ee_descriptor_id and member-vnf-index-ref + # to first 12 characters. + application_name = ( + vca_records[0]["ee_descriptor_id"][:12] + + "-" + + vnf_count + + "-" + + vnfrs["member-vnf-index-ref"][:12] + + "-vnf" + ) + elif charm_level == "vdu-level": + if len(vca_records) < 1: + raise N2VCException(message="One or more VCA record is expected.") + + # Charms are also used for deployments with Helm charts. + # If deployment unit is a Helm chart/KDU, + # vdu_profile_id and vdu_count will be empty string. + if vdu_count is None: + vdu_count = "" + + # If vnf/vdu is scaled, more than one VCA record may be included in vca_records + # but ee_descriptor_id is same. + # Shorten the ee_descriptor_id, member-vnf-index-ref and vdu_profile_id + # to first 12 characters. + if not vdu_id: + raise N2VCException(message="vdu-id should be provided.") + + vca_record = N2VCJujuConnector._get_vca_record( + "vdu_id", vca_records, vdu_id + ) + + if not vca_record: + vca_record = N2VCJujuConnector._get_vca_record( + "kdu_name", vca_records, vdu_id + ) + + application_name = ( + vca_record["ee_descriptor_id"][:12] + + "-" + + vnf_count + + "-" + + vnfrs["member-vnf-index-ref"][:12] + + "-" + + vdu_id[:12] + + "-" + + vdu_count + + "-vdu" + ) + + return application_name + + def _get_vnf_count_and_record( + self, charm_level: str, vnf_id_and_count: str + ) -> Tuple[str, dict]: + """Get the vnf count and VNF record depend on charm level + + Args: + charm_level (str) + vnf_id_and_count (str) + + Returns: + (vnf_count (str), db_vnfr(dict)) as Tuple + + """ + vnf_count = "" + db_vnfr = {} + + if charm_level in ("vnf-level", "vdu-level"): + vnf_id = "-".join(vnf_id_and_count.split("-")[:-1]) + vnf_count = vnf_id_and_count.split("-")[-1] + db_vnfr = self.db.get_one("vnfrs", {"_id": vnf_id}) + + # If the charm is ns level, it returns empty vnf_count and db_vnfr + return vnf_count, db_vnfr + + @staticmethod + def _get_vca_records(charm_level: str, db_nsr: dict, db_vnfr: dict) -> list: + """Get the VCA records from db_nsr dict + + Args: + charm_level (str): level of charm + db_nsr (dict): NS record from database + db_vnfr (dict): VNF record from database + + Returns: + vca_records (list): List of VCA record dictionaries + + """ + vca_records = {} + if charm_level == "ns-level": + vca_records = list( + filter( + lambda vca_record: vca_record["target_element"] == "ns", + db_nsr["_admin"]["deployed"]["VCA"], + ) + ) + elif charm_level in ["vnf-level", "vdu-level"]: + vca_records = list( + filter( + lambda vca_record: vca_record["member-vnf-index"] + == db_vnfr["member-vnf-index-ref"], + db_nsr["_admin"]["deployed"]["VCA"], + ) + ) + + return vca_records + + def _get_application_name(self, namespace: str) -> str: + """Build application name from namespace + + Application name structure: + NS level: -ns + VNF level: -z--vnf + VDU level: -z-- + -z-vdu + + Application naming for backward compatibility (old structure): + NS level: app- + VNF level: app-vnf--z- + VDU level: app-vnf--z-vdu- + -cnt--z- + + Args: + namespace (str) + + Returns: + application_name (str) + + """ + # split namespace components + ( + nsi_id, + ns_id, + vnf_id_and_count, + vdu_id, + vdu_count, + ) = self._get_namespace_components(namespace=namespace) + + if not ns_id: + raise N2VCException(message="ns-id should be provided.") + + charm_level = self._find_charm_level(vnf_id_and_count, vdu_id) + db_nsr = self.db.get_one("nsrs", {"_id": ns_id}) + vnf_count, db_vnfr = self._get_vnf_count_and_record( + charm_level, vnf_id_and_count + ) + vca_records = self._get_vca_records(charm_level, db_nsr, db_vnfr) + + if all("charm_name" in vca_record.keys() for vca_record in vca_records): + application_name = self._generate_application_name( + charm_level, + db_vnfr, + vca_records, + vnf_count=vnf_count, + vdu_id=vdu_id, + vdu_count=vdu_count, + ) + else: + application_name = self._generate_backward_compatible_application_name( + vnf_id_and_count, vdu_id, vdu_count + ) return N2VCJujuConnector._format_app_name(application_name) @@ -1213,6 +1559,6 @@ class N2VCJujuConnector(N2VCConnector): :param: vca_id: VCA ID """ vca_connection = await get_connection(self._store, vca_id=vca_id) - libjuju = Libjuju(vca_connection, loop=self.loop, log=self.log, n2vc=self) + libjuju = Libjuju(vca_connection, log=self.log, n2vc=self) controller = await libjuju.get_controller() await libjuju.disconnect_controller(controller)