##
import asyncio
-import base64
-import binascii
import logging
-import os
-import re
-import time
-
-from juju.action import Action
-from juju.application import Application
-from juju.client import client
-from juju.controller import Controller
-from juju.errors import JujuAPIError
-from juju.machine import Machine
-from juju.model import Model
+
+from n2vc.config import EnvironConfig
+from n2vc.definitions import RelationEndpoint
from n2vc.exceptions import (
N2VCBadArgumentsException,
N2VCException,
N2VCConnectionException,
N2VCExecutionException,
- N2VCInvalidCertificate,
- N2VCNotFound,
+ N2VCApplicationExists,
+ JujuApplicationExists,
+ # N2VCNotFound,
MethodNotImplemented,
)
-from n2vc.juju_observer import JujuModelObserver
from n2vc.n2vc_conn import N2VCConnector
from n2vc.n2vc_conn import obj_to_dict, obj_to_yaml
-from n2vc.provisioner import AsyncSSHProvisioner
+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):
"""
BUILT_IN_CLOUDS = ["localhost", "microk8s"]
+ libjuju = None
def __init__(
self,
db: object,
fs: object,
log: object = None,
- loop: object = None,
- url: str = "127.0.0.1:17070",
- username: str = "admin",
- vca_config: dict = None,
on_update_db=None,
):
- """Initialize juju N2VC connector
+ """
+ Constructor
+
+ :param: db: Database object from osm_common
+ :param: fs: Filesystem object from osm_common
+ :param: log: Logger
+ :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,
- url=url,
- username=username,
- vca_config=vca_config,
- 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)
self.log.info("Initializing N2VC juju connector...")
- """
- ##############################################################
- # check arguments
- ##############################################################
- """
-
- # juju URL
- if url is None:
- raise N2VCBadArgumentsException("Argument url is mandatory", ["url"])
- url_parts = url.split(":")
- if len(url_parts) != 2:
- raise N2VCBadArgumentsException(
- "Argument url: bad format (localhost:port) -> {}".format(url), ["url"]
- )
- self.hostname = url_parts[0]
- try:
- self.port = int(url_parts[1])
- except ValueError:
- raise N2VCBadArgumentsException(
- "url port must be a number -> {}".format(url), ["url"]
- )
-
- # juju USERNAME
- if username is None:
- raise N2VCBadArgumentsException(
- "Argument username is mandatory", ["username"]
- )
-
- # juju CONFIGURATION
- if vca_config is None:
- raise N2VCBadArgumentsException(
- "Argument vca_config is mandatory", ["vca_config"]
- )
-
- if "secret" in vca_config:
- self.secret = vca_config["secret"]
- else:
- raise N2VCBadArgumentsException(
- "Argument vca_config.secret is mandatory", ["vca_config.secret"]
- )
-
- # pubkey of juju client in osm machine: ~/.local/share/juju/ssh/juju_id_rsa.pub
- # if exists, it will be written in lcm container: _create_juju_public_key()
- if "public_key" in vca_config:
- self.public_key = vca_config["public_key"]
- else:
- self.public_key = None
-
- # TODO: Verify ca_cert is valid before using. VCA will crash
- # if the ca_cert isn't formatted correctly.
- def base64_to_cacert(b64string):
- """Convert the base64-encoded string containing the VCA CACERT.
-
- The input string....
-
- """
- try:
- cacert = base64.b64decode(b64string).decode("utf-8")
-
- cacert = re.sub(r"\\n", r"\n", cacert,)
- except binascii.Error as e:
- self.log.debug("Caught binascii.Error: {}".format(e))
- raise N2VCInvalidCertificate(message="Invalid CA Certificate")
-
- return cacert
-
- self.ca_cert = vca_config.get("ca_cert")
- if self.ca_cert:
- self.ca_cert = base64_to_cacert(vca_config["ca_cert"])
-
- if "api_proxy" in vca_config:
- self.api_proxy = vca_config["api_proxy"]
- self.log.debug(
- "api_proxy for native charms configured: {}".format(self.api_proxy)
- )
- else:
- self.warning(
- "api_proxy is not configured. Support for native charms is disabled"
- )
-
- if "enable_os_upgrade" in vca_config:
- self.enable_os_upgrade = vca_config["enable_os_upgrade"]
- else:
- self.enable_os_upgrade = True
-
- if "apt_mirror" in vca_config:
- self.apt_mirror = vca_config["apt_mirror"]
- else:
- self.apt_mirror = None
-
- self.cloud = vca_config.get("cloud")
- # self.log.debug('Arguments have been checked')
-
- # juju data
- self.controller = None # it will be filled when connect to juju
- self.juju_models = {} # model objects for every model_name
- self.juju_observers = {} # model observers for every model_name
- self._connecting = (
- False # while connecting to juju (to avoid duplicate connections)
- )
- self._authenticated = (
- False # it will be True when juju connection be stablished
- )
- self._creating_model = False # True during model creation
-
- # create juju pub key file in lcm container at
- # ./local/share/juju/ssh/juju_id_rsa.pub
- self._create_juju_public_key()
-
+ db_uri = EnvironConfig(prefixes=["OSMLCM_", "OSMMON_"]).get("database_uri")
+ self._store = MotorStore(db_uri)
+ self.loading_libjuju = asyncio.Lock()
+ self.delete_namespace_locks = {}
self.log.info("N2VC juju connector initialized")
- async def get_status(self, namespace: str, yaml_format: bool = True):
+ async def get_status(
+ self, namespace: str, yaml_format: bool = True, vca_id: str = None
+ ):
+ """
+ Get status from all juju models from a VCA
+
+ :param namespace: we obtain ns from namespace
+ :param yaml_format: returns a yaml string
+ :param: vca_id: VCA ID from which the status will be retrieved.
+ """
+ # TODO: Review where is this function used. It is not optimal at all to get the status
+ # from all the juju models of a particular VCA. Additionally, these models might
+ # not have been deployed by OSM, in that case we are getting information from
+ # deployments outside of OSM's scope.
# self.log.info('Getting NS status. namespace: {}'.format(namespace))
-
- if not self._authenticated:
- await self._juju_login()
+ libjuju = await self._get_libjuju(vca_id)
_nsi_id, ns_id, _vnf_id, _vdu_id, _vdu_count = self._get_namespace_components(
namespace=namespace
self.log.error(msg)
raise N2VCBadArgumentsException(msg, ["namespace"])
- # get juju model (create model if needed)
- model = await self._juju_get_model(model_name=model_name)
+ status = {}
+ models = await libjuju.list_models(contains=ns_id)
- status = await model.get_status()
+ for m in models:
+ status[m] = await libjuju.get_model_status(m)
if yaml_format:
return obj_to_yaml(status)
else:
return obj_to_dict(status)
+ async def update_vca_status(self, vcastatus: dict, vca_id: str = None):
+ """
+ Add all configs, actions, executed actions of all applications in a model to vcastatus dict.
+
+ :param vcastatus: dict containing vcaStatus
+ :param: vca_id: VCA ID
+
+ :return: None
+ """
+ try:
+ libjuju = await self._get_libjuju(vca_id)
+ for model_name in vcastatus:
+ # Adding executed actions
+ vcastatus[model_name][
+ "executedActions"
+ ] = await libjuju.get_executed_actions(model_name)
+ for application in vcastatus[model_name]["applications"]:
+ # Adding application actions
+ vcastatus[model_name]["applications"][application][
+ "actions"
+ ] = await libjuju.get_actions(application, model_name)
+ # Adding application configs
+ vcastatus[model_name]["applications"][application][
+ "configs"
+ ] = await libjuju.get_application_configs(model_name, application)
+ except Exception as e:
+ self.log.debug("Error in updating vca status: {}".format(str(e)))
+
async def create_execution_environment(
self,
namespace: str,
reuse_ee_id: str = None,
progress_timeout: float = None,
total_timeout: float = None,
+ vca_id: str = None,
) -> (str, dict):
+ """
+ Create an Execution Environment. Returns when it is created or raises an
+ exception on failing
+
+ :param: namespace: Contains a dot separate string.
+ LCM will use: [<nsi-id>].<ns-id>.<vnf-id>.<vdu-id>[-<count>]
+ :param: db_dict: where to write to database when the status changes.
+ It contains a dictionary with {collection: str, filter: {}, path: str},
+ e.g. {collection: "nsrs", filter: {_id: <nsd-id>, path:
+ "_admin.deployed.VCA.3"}
+ :param: reuse_ee_id: ee id from an older execution. It allows us to reuse an
+ older environment
+ :param: progress_timeout: Progress timeout
+ :param: total_timeout: Total timeout
+ :param: vca_id: VCA ID
+
+ :returns: id of the new execution environment and credentials for it
+ (credentials can contains hostname, username, etc depending on underlying cloud)
+ """
self.log.info(
"Creating execution environment. namespace: {}, reuse_ee_id: {}".format(
namespace, reuse_ee_id
)
)
-
- if not self._authenticated:
- await self._juju_login()
+ libjuju = await self._get_libjuju(vca_id)
machine_id = None
if reuse_ee_id:
# create or reuse a new juju machine
try:
- machine = await self._juju_create_machine(
+ if not await libjuju.model_exists(model_name):
+ await libjuju.add_model(model_name, libjuju.vca_connection.lxd_cloud)
+ machine, new = await libjuju.create_machine(
model_name=model_name,
- application_name=application_name,
machine_id=machine_id,
db_dict=db_dict,
progress_timeout=progress_timeout,
total_timeout=total_timeout,
)
+ # id for the execution environment
+ ee_id = N2VCJujuConnector._build_ee_id(
+ model_name=model_name,
+ application_name=application_name,
+ machine_id=str(machine.entity_id),
+ )
+ self.log.debug("ee_id: {}".format(ee_id))
+
+ if new:
+ # write ee_id in database
+ self._write_ee_id_db(db_dict=db_dict, ee_id=ee_id)
+
except Exception as e:
message = "Error creating machine on juju: {}".format(e)
self.log.error(message)
raise N2VCException(message=message)
- # id for the execution environment
- ee_id = N2VCJujuConnector._build_ee_id(
- model_name=model_name,
- application_name=application_name,
- machine_id=str(machine.entity_id),
- )
- self.log.debug("ee_id: {}".format(ee_id))
-
# new machine credentials
- credentials = dict()
- credentials["hostname"] = machine.dns_name
+ credentials = {"hostname": machine.dns_name}
self.log.info(
"Execution environment created. ee_id: {}, credentials: {}".format(
db_dict: dict,
progress_timeout: float = None,
total_timeout: float = None,
+ vca_id: str = None,
) -> str:
-
- if not self._authenticated:
- await self._juju_login()
-
+ """
+ Register an existing execution environment at the VCA
+
+ :param: namespace: Contains a dot separate string.
+ LCM will use: [<nsi-id>].<ns-id>.<vnf-id>.<vdu-id>[-<count>]
+ :param: credentials: credentials to access the existing execution environment
+ (it can contains hostname, username, path to private key,
+ etc depending on underlying cloud)
+ :param: db_dict: where to write to database when the status changes.
+ It contains a dictionary with {collection: str, filter: {}, path: str},
+ e.g. {collection: "nsrs", filter: {_id: <nsd-id>, path:
+ "_admin.deployed.VCA.3"}
+ :param: reuse_ee_id: ee id from an older execution. It allows us to reuse an
+ older environment
+ :param: progress_timeout: Progress timeout
+ :param: total_timeout: Total timeout
+ :param: vca_id: VCA ID
+
+ :returns: id of the execution environment
+ """
self.log.info(
"Registering execution environment. namespace={}, credentials={}".format(
namespace, credentials
)
)
+ libjuju = await self._get_libjuju(vca_id)
if credentials is None:
raise N2VCBadArgumentsException(
# register machine on juju
try:
- machine_id = await self._juju_provision_machine(
+ if not await libjuju.model_exists(model_name):
+ await libjuju.add_model(model_name, libjuju.vca_connection.lxd_cloud)
+ machine_id = await libjuju.provision_machine(
model_name=model_name,
hostname=hostname,
username=username,
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,
progress_timeout: float = None,
total_timeout: float = None,
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
+
+ :param: ee_id: the id of the execution environment returned by
+ create_execution_environment or register_execution_environment
+ :param: artifact_path: where to locate the artifacts (parent folder) using
+ the self.fs
+ the final artifact path will be a combination of this
+ artifact_path and additional string from the config_dict
+ (e.g. charm name)
+ :param: db_dict: where to write into database when the status changes.
+ It contains a dict with
+ {collection: <str>, filter: {}, path: <str>},
+ e.g. {collection: "nsrs", filter:
+ {_id: <nsd-id>, path: "_admin.deployed.VCA.3"}
+ :param: progress_timeout: Progress timeout
+ :param: total_timeout: Total timeout
+ :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(
(
"artifact path: {}, db_dict: {}"
).format(ee_id, artifact_path, db_dict)
)
-
- if not self._authenticated:
- await self._juju_login()
+ libjuju = await self._get_libjuju(vca_id)
# check arguments
if ee_id is None or len(ee_id) == 0:
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"])
+
+ if artifact_path.startswith("/"):
+ full_path = self.fs.path + artifact_path
+ else:
+ full_path = self.fs.path + "/" + artifact_path
+
+ try:
+ 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 deploying charm into ee={} : {}".format(ee_id, e)
+ )
+
+ self.log.info("Configuration sw installed")
+
+ async def install_k8s_proxy_charm(
+ self,
+ charm_name: str,
+ namespace: str,
+ artifact_path: str,
+ db_dict: dict,
+ progress_timeout: float = None,
+ total_timeout: float = None,
+ config: dict = None,
+ vca_id: str = None,
+ ) -> str:
+ """
+ Install a k8s proxy charm
+
+ :param charm_name: Name of the charm being deployed
+ :param namespace: collection of all the uuids related to the charm.
+ :param str artifact_path: where to locate the artifacts (parent folder) using
+ the self.fs
+ the final artifact path will be a combination of this artifact_path and
+ additional string from the config_dict (e.g. charm name)
+ :param dict db_dict: where to write into database when the status changes.
+ It contains a dict with
+ {collection: <str>, filter: {}, path: <str>},
+ e.g. {collection: "nsrs", filter:
+ {_id: <nsd-id>, path: "_admin.deployed.VCA.3"}
+ :param: progress_timeout: Progress timeout
+ :param: total_timeout: Total timeout
+ :param config: Dictionary with additional configuration
+ :param vca_id: VCA ID
+
+ :returns ee_id: execution environment id.
+ """
+ self.log.info(
+ "Installing k8s proxy charm: {}, artifact path: {}, db_dict: {}".format(
+ charm_name, artifact_path, db_dict
+ )
+ )
+ libjuju = await self._get_libjuju(vca_id)
+
+ if artifact_path is None or len(artifact_path) == 0:
+ raise N2VCBadArgumentsException(
+ message="artifact_path is mandatory", bad_args=["artifact_path"]
+ )
+ if db_dict is None:
+ raise N2VCBadArgumentsException(
+ message="db_dict is mandatory", bad_args=["db_dict"]
+ )
+
+ # remove // in charm path
+ while artifact_path.find("//") >= 0:
+ artifact_path = artifact_path.replace("//", "/")
+
+ # check charm path
+ 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"])
else:
full_path = self.fs.path + "/" + artifact_path
+ _, 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)
+ application_name = self._get_application_name(namespace)
+
try:
- await self._juju_deploy_charm(
+ await libjuju.deploy_charm(
model_name=model_name,
application_name=application_name,
- charm_path=full_path,
- machine_id=machine_id,
+ path=full_path,
+ machine_id=None,
db_dict=db_dict,
progress_timeout=progress_timeout,
total_timeout=total_timeout,
config=config,
)
except Exception as e:
- raise N2VCException(
- message="Error desploying charm into ee={} : {}".format(ee_id, e)
- )
+ raise N2VCException(message="Error deploying charm: {}".format(e))
- self.log.info("Configuration sw installed")
+ self.log.info("K8s proxy charm installed")
+ ee_id = N2VCJujuConnector._build_ee_id(
+ model_name=model_name, application_name=application_name, machine_id="k8s"
+ )
+
+ self._write_ee_id_db(db_dict=db_dict, ee_id=ee_id)
+
+ return ee_id
async def get_ee_ssh_public__key(
self,
db_dict: dict,
progress_timeout: float = None,
total_timeout: float = None,
+ vca_id: str = None,
) -> str:
+ """
+ Get Execution environment ssh public key
+
+ :param: ee_id: the id of the execution environment returned by
+ create_execution_environment or register_execution_environment
+ :param: db_dict: where to write into database when the status changes.
+ It contains a dict with
+ {collection: <str>, filter: {}, path: <str>},
+ e.g. {collection: "nsrs", filter:
+ {_id: <nsd-id>, path: "_admin.deployed.VCA.3"}
+ :param: progress_timeout: Progress timeout
+ :param: total_timeout: Total timeout
+ :param vca_id: VCA ID
+ :returns: public key of the execution environment
+ For the case of juju proxy charm ssh-layered, it is the one
+ returned by 'get-ssh-public-key' primitive.
+ It raises a N2VC exception if fails
+ """
self.log.info(
(
"Generating priv/pub key pair and get pub key on ee_id: {}, db_dict: {}"
).format(ee_id, db_dict)
)
-
- if not self._authenticated:
- await self._juju_login()
+ libjuju = await self._get_libjuju(vca_id)
# check arguments
if ee_id is None or len(ee_id) == 0:
output = None
+ application_name = N2VCJujuConnector._format_app_name(application_name)
+
# execute action: generate-ssh-key
try:
- output, _status = await self._juju_execute_action(
+ output, _status = await libjuju.execute_action(
model_name=model_name,
application_name=application_name,
action_name="generate-ssh-key",
# execute action: get-ssh-public-key
try:
- output, _status = await self._juju_execute_action(
+ output, _status = await libjuju.execute_action(
model_name=model_name,
application_name=application_name,
action_name="get-ssh-public-key",
except Exception as e:
msg = "Cannot execute action get-ssh-public-key: {}\n".format(e)
self.log.info(msg)
- raise N2VCException(msg)
+ raise N2VCExecutionException(e, primitive_name="get-ssh-public-key")
# return public key if exists
return output["pubkey"] if "pubkey" in output else output
- async def add_relation(
- self, ee_id_1: str, ee_id_2: str, endpoint_1: str, endpoint_2: str
- ):
-
- self.log.debug(
- "adding new relation between {} and {}, endpoints: {}, {}".format(
- ee_id_1, ee_id_2, endpoint_1, endpoint_2
- )
- )
-
- # 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"])
+ async def get_metrics(
+ self, model_name: str, application_name: str, vca_id: str = None
+ ) -> dict:
+ """
+ Get metrics from application
- if not self._authenticated:
- await self._juju_login()
+ :param: model_name: Model name
+ :param: application_name: Application name
+ :param: vca_id: VCA ID
- # 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)
+ :return: Dictionary with obtained metrics
+ """
+ libjuju = await self._get_libjuju(vca_id)
+ return await libjuju.get_metrics(model_name, application_name)
- # 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"]
- )
+ async def add_relation(
+ self, provider: RelationEndpoint, requirer: RelationEndpoint
+ ):
+ """
+ Add relation between two charmed endpoints
- # add juju relations between two applications
+ :param: provider: Provider relation endpoint
+ :param: requirer: Requirer relation endpoint
+ """
+ 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
+ )
try:
- await self._juju_add_relation(
- model_name=model_1,
- application_name_1=app_1,
- application_name_2=app_2,
- relation_1=endpoint_1,
- relation_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)
async def remove_relation(self):
- if not self._authenticated:
- await self._juju_login()
# TODO
self.log.info("Method not implemented yet")
raise MethodNotImplemented()
async def deregister_execution_environments(self):
- if not self._authenticated:
- await self._juju_login()
- # TODO
self.log.info("Method not implemented yet")
raise MethodNotImplemented()
async def delete_namespace(
- self, namespace: str, db_dict: dict = None, total_timeout: float = None
+ self,
+ namespace: str,
+ db_dict: dict = None,
+ total_timeout: float = None,
+ vca_id: str = None,
):
+ """
+ Remove a network scenario and its execution environments
+ :param: namespace: [<nsi-id>].<ns-id>
+ :param: db_dict: where to write into database when the status changes.
+ It contains a dict with
+ {collection: <str>, filter: {}, path: <str>},
+ e.g. {collection: "nsrs", filter:
+ {_id: <nsd-id>, path: "_admin.deployed.VCA.3"}
+ :param: total_timeout: Total timeout
+ :param: vca_id: VCA ID
+ """
self.log.info("Deleting namespace={}".format(namespace))
+ 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]
+
+ while delete_lock.locked():
+ will_not_delete = True
+ await asyncio.sleep(0.1)
- if not self._authenticated:
- await self._juju_login()
+ if will_not_delete:
+ self.log.info("Namespace {} deleted by another worker.".format(namespace))
+ return
- # check arguments
- if namespace is None:
- raise N2VCBadArgumentsException(
- message="namespace is mandatory", bad_args=["namespace"]
- )
+ try:
+ async with delete_lock:
+ libjuju = await self._get_libjuju(vca_id)
- _nsi_id, ns_id, _vnf_id, _vdu_id, _vdu_count = self._get_namespace_components(
- namespace=namespace
- )
- if ns_id is not None:
- try:
- await self._juju_destroy_model(
- model_name=ns_id, total_timeout=total_timeout
- )
- except N2VCNotFound:
- raise
- 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"]
- )
+ # check arguments
+ if namespace is None:
+ raise N2VCBadArgumentsException(
+ message="namespace is mandatory", 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(
- self, ee_id: str, db_dict: dict = None, total_timeout: float = None
+ self,
+ ee_id: str,
+ 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
+ :param str ee_id: id of the execution environment to delete
+ :param dict db_dict: where to write into database when the status changes.
+ It contains a dict with
+ {collection: <str>, filter: {}, path: <str>},
+ e.g. {collection: "nsrs", filter:
+ {_id: <nsd-id>, path: "_admin.deployed.VCA.3"}
+ :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))
-
- if not self._authenticated:
- await self._juju_login()
+ libjuju = await self._get_libjuju(vca_id)
# check arguments
if ee_id is None:
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
)
-
- # destroy the application
try:
- await self._juju_destroy_application(
- model_name=model_name, application_name=application_name
- )
+ 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
+ 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:
+ # destroy the application
+ await libjuju.destroy_application(
+ model_name=model_name,
+ application_name=application_name,
+ total_timeout=total_timeout,
+ )
except Exception as e:
raise N2VCException(
message=(
).format(ee_id, application_name, e)
)
- # destroy the machine
- # try:
- # await self._juju_destroy_machine(
- # model_name=model_name,
- # machine_id=machine_id,
- # total_timeout=total_timeout
- # )
- # except Exception as e:
- # raise N2VCException(
- # message='Error deleting execution environment {} (machine {}) : {}'
- # .format(ee_id, machine_id, e))
-
self.log.info("Execution environment {} deleted".format(ee_id))
async def exec_primitive(
db_dict: dict = None,
progress_timeout: float = None,
total_timeout: float = None,
+ vca_id: str = None,
+ vca_type: str = None,
) -> str:
+ """
+ Execute a primitive in the execution environment
+
+ :param: ee_id: the one returned by create_execution_environment or
+ register_execution_environment
+ :param: primitive_name: must be one defined in the software. There is one
+ called 'config', where, for the proxy case, the 'credentials' of VM are
+ provided
+ :param: params_dict: parameters of the action
+ :param: db_dict: where to write into database when the status changes.
+ It contains a dict with
+ {collection: <str>, filter: {}, path: <str>},
+ e.g. {collection: "nsrs", filter:
+ {_id: <nsd-id>, path: "_admin.deployed.VCA.3"}
+ :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
+ """
self.log.info(
"Executing primitive: {} on ee: {}, params: {}".format(
primitive_name, ee_id, params_dict
)
)
-
- if not self._authenticated:
- await self._juju_login()
+ libjuju = await self._get_libjuju(vca_id)
# check arguments
if ee_id is None or len(ee_id) == 0:
(
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(
if primitive_name == "config":
# Special case: config primitive
try:
- await self._juju_configure_application(
+ await libjuju.configure_application(
model_name=model_name,
application_name=application_name,
config=params_dict,
- db_dict=db_dict,
- progress_timeout=progress_timeout,
- total_timeout=total_timeout,
)
+ actions = await libjuju.get_actions(
+ application_name=application_name, model_name=model_name
+ )
+ self.log.debug(
+ "Application {} has these actions: {}".format(
+ application_name, actions
+ )
+ )
+ if "verify-ssh-credentials" in actions:
+ # execute verify-credentials
+ num_retries = 20
+ retry_timeout = 15.0
+ for _ in range(num_retries):
+ try:
+ self.log.debug("Executing action verify-ssh-credentials...")
+ output, ok = await libjuju.execute_action(
+ model_name=model_name,
+ application_name=application_name,
+ action_name="verify-ssh-credentials",
+ db_dict=db_dict,
+ progress_timeout=progress_timeout,
+ total_timeout=total_timeout,
+ )
+
+ if ok == "failed":
+ self.log.debug(
+ "Error executing verify-ssh-credentials: {}. Retrying..."
+ )
+ await asyncio.sleep(retry_timeout)
+
+ continue
+ self.log.debug("Result: {}, output: {}".format(ok, output))
+ break
+ except asyncio.CancelledError:
+ raise
+ else:
+ self.log.error(
+ "Error executing verify-ssh-credentials after {} retries. ".format(
+ num_retries
+ )
+ )
+ else:
+ msg = "Action verify-ssh-credentials does not exist in application {}".format(
+ application_name
+ )
+ self.log.debug(msg=msg)
except Exception as e:
self.log.error("Error configuring juju application: {}".format(e))
raise N2VCExecutionException(
return "CONFIG OK"
else:
try:
- output, status = await self._juju_execute_action(
+ output, status = await libjuju.execute_action(
model_name=model_name,
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 disconnect(self):
+ 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
+
+ :param: vca_id: VCA ID
+ """
self.log.info("closing juju N2VC...")
- await self._juju_logout()
+ libjuju = await self._get_libjuju(vca_id)
+ try:
+ await libjuju.disconnect()
+ except Exception as e:
+ raise N2VCConnectionException(
+ message="Error disconnecting controller: {}".format(e),
+ url=libjuju.vca_connection.data.endpoints,
+ )
"""
- ####################################################################################
- ################################### P R I V A T E ##################################
- ####################################################################################
+####################################################################################
+################################### P R I V A T E ##################################
+####################################################################################
"""
- def _write_ee_id_db(self, db_dict: dict, ee_id: str):
+ async def _get_libjuju(self, vca_id: str = None) -> Libjuju:
+ """
+ Get libjuju object
+
+ :param: vca_id: VCA ID
+ If None, get a libjuju object with a Connection to the default VCA
+ Else, geta libjuju object with a Connection to the specified VCA
+ """
+ if not vca_id:
+ while self.loading_libjuju.locked():
+ await asyncio.sleep(0.1)
+ if not self.libjuju:
+ async with self.loading_libjuju:
+ vca_connection = await get_connection(self._store)
+ 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, 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"]
: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-<vnf id>-vdu-<vdu-id>-cnt-<vdu-count>
+ @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:
else:
vdu_count = "-cnt-" + vdu_count
- application_name = "app-{}{}{}".format(vnf_id, vdu_id, vdu_count)
-
- return N2VCJujuConnector._format_app_name(application_name)
-
- async def _juju_create_machine(
- self,
- model_name: str,
- application_name: str,
- machine_id: str = None,
- db_dict: dict = None,
- progress_timeout: float = None,
- total_timeout: float = None,
- ) -> Machine:
-
- self.log.debug(
- "creating machine in model: {}, existing machine id: {}".format(
- model_name, machine_id
- )
- )
-
- # get juju model and observer (create model if needed)
- model = await self._juju_get_model(model_name=model_name)
- observer = self.juju_observers[model_name]
-
- # find machine id in model
- machine = None
- if machine_id is not None:
- self.log.debug("Finding existing machine id {} in model".format(machine_id))
- # get juju existing machines in the model
- existing_machines = await model.get_machines()
- if machine_id in existing_machines:
- self.log.debug(
- "Machine id {} found in model (reusing it)".format(machine_id)
- )
- machine = model.machines[machine_id]
-
- if machine is None:
- self.log.debug("Creating a new machine in juju...")
- # machine does not exist, create it and wait for it
- machine = await model.add_machine(
- spec=None, constraints=None, disks=None, series="xenial"
- )
-
- # register machine with observer
- observer.register_machine(machine=machine, db_dict=db_dict)
-
- # id for the execution environment
- ee_id = N2VCJujuConnector._build_ee_id(
- model_name=model_name,
- application_name=application_name,
- machine_id=str(machine.entity_id),
- )
-
- # write ee_id in database
- self._write_ee_id_db(db_dict=db_dict, ee_id=ee_id)
-
- # wait for machine creation
- await observer.wait_for_machine(
- machine_id=str(machine.entity_id),
- progress_timeout=progress_timeout,
- total_timeout=total_timeout,
- )
-
- else:
-
- self.log.debug("Reusing old machine pending")
-
- # register machine with observer
- observer.register_machine(machine=machine, db_dict=db_dict)
-
- # machine does exist, but it is in creation process (pending), wait for
- # create finalisation
- await observer.wait_for_machine(
- machine_id=machine.entity_id,
- progress_timeout=progress_timeout,
- total_timeout=total_timeout,
- )
-
- self.log.debug("Machine ready at " + str(machine.dns_name))
- return machine
-
- async def _juju_provision_machine(
- self,
- model_name: str,
- hostname: str,
- username: str,
- private_key_path: str,
- db_dict: dict = None,
- progress_timeout: float = None,
- total_timeout: float = None,
- ) -> str:
-
- if not self.api_proxy:
- msg = "Cannot provision machine: api_proxy is not defined"
- self.log.error(msg=msg)
- raise N2VCException(message=msg)
-
- self.log.debug(
- "provisioning machine. model: {}, hostname: {}, username: {}".format(
- model_name, hostname, username
- )
- )
-
- if not self._authenticated:
- await self._juju_login()
-
- # get juju model and observer
- model = await self._juju_get_model(model_name=model_name)
- observer = self.juju_observers[model_name]
-
- # TODO check if machine is already provisioned
- machine_list = await model.get_machines()
-
- provisioner = AsyncSSHProvisioner(
- host=hostname,
- user=username,
- private_key_path=private_key_path,
- log=self.log,
- )
-
- params = None
- try:
- params = await provisioner.provision_machine()
- except Exception as ex:
- msg = "Exception provisioning machine: {}".format(ex)
- self.log.error(msg)
- raise N2VCException(message=msg)
-
- params.jobs = ["JobHostUnits"]
-
- connection = model.connection()
-
- # Submit the request.
- self.log.debug("Adding machine to model")
- client_facade = client.ClientFacade.from_connection(connection)
- results = await client_facade.AddMachines(params=[params])
- error = results.machines[0].error
- if error:
- msg = "Error adding machine: {}".format(error.message)
- self.log.error(msg=msg)
- raise ValueError(msg)
-
- machine_id = results.machines[0].machine
-
- # Need to run this after AddMachines has been called,
- # as we need the machine_id
- self.log.debug("Installing Juju agent into machine {}".format(machine_id))
- asyncio.ensure_future(
- provisioner.install_agent(
- connection=connection,
- nonce=params.nonce,
- machine_id=machine_id,
- api=self.api_proxy,
- )
- )
-
- # wait for machine in model (now, machine is not yet in model, so we must
- # wait for it)
- machine = None
- for _ in range(10):
- machine_list = await model.get_machines()
- if machine_id in machine_list:
- self.log.debug("Machine {} found in model!".format(machine_id))
- machine = model.machines.get(machine_id)
- break
- await asyncio.sleep(2)
-
- if machine is None:
- msg = "Machine {} not found in model".format(machine_id)
- self.log.error(msg=msg)
- raise Exception(msg)
-
- # register machine with observer
- observer.register_machine(machine=machine, db_dict=db_dict)
-
- # wait for machine creation
- self.log.debug("waiting for provision finishes... {}".format(machine_id))
- await observer.wait_for_machine(
- machine_id=machine_id,
- progress_timeout=progress_timeout,
- total_timeout=total_timeout,
- )
-
- self.log.debug("Machine provisioned {}".format(machine_id))
-
- return machine_id
-
- async def _juju_deploy_charm(
- self,
- model_name: str,
- application_name: str,
- charm_path: str,
- machine_id: str,
- db_dict: dict,
- progress_timeout: float = None,
- total_timeout: float = None,
- config: dict = None,
- ) -> (Application, int):
-
- # get juju model and observer
- model = await self._juju_get_model(model_name=model_name)
- observer = self.juju_observers[model_name]
-
- # check if application already exists
- application = None
- if application_name in model.applications:
- application = model.applications[application_name]
-
- if application is None:
-
- # application does not exist, create it and wait for it
- self.log.debug(
- "deploying application {} to machine {}, model {}".format(
- application_name, machine_id, model_name
- )
- )
- self.log.debug("charm: {}".format(charm_path))
- series = "xenial"
- # series = None
- application = await model.deploy(
- entity_url=charm_path,
- application_name=application_name,
- channel="stable",
- num_units=1,
- series=series,
- to=machine_id,
- config=config,
- )
-
- # register application with observer
- observer.register_application(application=application, db_dict=db_dict)
-
- self.log.debug(
- "waiting for application deployed... {}".format(application.entity_id)
- )
- retries = await observer.wait_for_application(
- application_id=application.entity_id,
- progress_timeout=progress_timeout,
- total_timeout=total_timeout,
- )
- self.log.debug("application deployed")
-
- else:
-
- # register application with observer
- observer.register_application(application=application, db_dict=db_dict)
-
- # application already exists, but not finalised
- self.log.debug("application already exists, waiting for deployed...")
- retries = await observer.wait_for_application(
- application_id=application.entity_id,
- progress_timeout=progress_timeout,
- total_timeout=total_timeout,
- )
- self.log.debug("application deployed")
-
- return application, retries
+ # Generate a random suffix with 5 characters (the default size used by K8s)
+ random_suffix = generate_random_alfanum_string(size=5)
- async def _juju_execute_action(
- self,
- model_name: str,
- application_name: str,
- action_name: str,
- db_dict: dict,
- progress_timeout: float = None,
- total_timeout: float = None,
- **kwargs
- ) -> Action:
-
- # get juju model and observer
- model = await self._juju_get_model(model_name=model_name)
- observer = self.juju_observers[model_name]
-
- application = await self._juju_get_application(
- model_name=model_name, application_name=application_name
+ application_name = "app-{}{}{}-{}".format(
+ vnf_id, vdu_id, vdu_count, random_suffix
)
+ return application_name
- unit = None
- for u in application.units:
- if await u.is_leader_from_status():
- unit = u
- if unit is not None:
- actions = await application.get_actions()
- if action_name in actions:
- self.log.debug(
- 'executing action "{}" using params: {}'.format(action_name, kwargs)
- )
- action = await unit.run_action(action_name, **kwargs)
+ @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
- # register action with observer
- observer.register_action(action=action, db_dict=db_dict)
+ Args:
+ search_key (str): keyword to find the correct VCA record
+ vca_records (list): All VCA records as list
+ vdu_id (str): VDU ID
- await observer.wait_for_action(
- action_id=action.entity_id,
- progress_timeout=progress_timeout,
- total_timeout=total_timeout,
- )
- self.log.debug("action completed with status: {}".format(action.status))
- output = await model.get_action_output(action_uuid=action.entity_id)
- status = await model.get_action_status(uuid_or_prefix=action.entity_id)
- if action.entity_id in status:
- status = status[action.entity_id]
- else:
- status = "failed"
- return output, status
+ Returns:
+ vca_record (dict): Dictionary which includes the correct VCA record
- raise N2VCExecutionException(
- message="Cannot execute action on charm", primitive_name=action_name
+ """
+ return next(
+ filter(lambda record: record[search_key] == vdu_id, vca_records), {}
)
- async def _juju_configure_application(
- self,
- model_name: str,
- application_name: str,
- config: dict,
- db_dict: dict,
- progress_timeout: float = None,
- total_timeout: float = None,
- ):
+ @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.
- # get the application
- application = await self._juju_get_application(
- model_name=model_name, application_name=application_name
- )
+ 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
- self.log.debug(
- "configuring the application {} -> {}".format(application_name, config)
- )
- res = await application.set_config(config)
- self.log.debug(
- "application {} configured. res={}".format(application_name, res)
- )
+ Returns:
+ application_name (str): generated application name
- # Verify the config is set
- new_conf = await application.get_config()
- for key in config:
- value = new_conf[key]["value"]
- self.log.debug(" {} = {}".format(key, value))
- if config[key] != value:
- raise N2VCException(
- message="key {} is not configured correctly {} != {}".format(
- key, config[key], new_conf[key]
- )
+ """
+ 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
)
- # check if 'verify-ssh-credentials' action exists
- # unit = application.units[0]
- actions = await application.get_actions()
- if "verify-ssh-credentials" not in actions:
- msg = (
- "Action verify-ssh-credentials does not exist in application {}"
- ).format(application_name)
- self.log.debug(msg=msg)
- return False
-
- # execute verify-credentials
- num_retries = 20
- retry_timeout = 15.0
- for _ in range(num_retries):
- try:
- self.log.debug("Executing action verify-ssh-credentials...")
- output, ok = await self._juju_execute_action(
- model_name=model_name,
- application_name=application_name,
- action_name="verify-ssh-credentials",
- db_dict=db_dict,
- progress_timeout=progress_timeout,
- total_timeout=total_timeout,
- )
- self.log.debug("Result: {}, output: {}".format(ok, output))
- return True
- except asyncio.CancelledError:
- raise
- except Exception as e:
- self.log.debug(
- "Error executing verify-ssh-credentials: {}. Retrying...".format(e)
- )
- await asyncio.sleep(retry_timeout)
- else:
- self.log.error(
- "Error executing verify-ssh-credentials after {} retries. ".format(
- num_retries
- )
+ application_name = (
+ vca_record["ee_descriptor_id"][:12]
+ + "-"
+ + vnf_count
+ + "-"
+ + vnfrs["member-vnf-index-ref"][:12]
+ + "-"
+ + vdu_id[:12]
+ + "-"
+ + vdu_count
+ + "-vdu"
)
- return False
- async def _juju_get_application(self, model_name: str, application_name: str):
- """Get the deployed application."""
+ return application_name
- model = await self._juju_get_model(model_name=model_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
- application_name = N2VCJujuConnector._format_app_name(application_name)
+ Args:
+ charm_level (str)
+ vnf_id_and_count (str)
- if model.applications and application_name in model.applications:
- return model.applications[application_name]
- else:
- raise N2VCException(
- message="Cannot get application {} from model {}".format(
- application_name, model_name
- )
- )
-
- async def _juju_get_model(self, model_name: str) -> Model:
- """ Get a model object from juju controller
- If the model does not exits, it creates it.
+ Returns:
+ (vnf_count (str), db_vnfr(dict)) as Tuple
- :param str model_name: name of the model
- :returns Model: model obtained from juju controller or Exception
"""
+ vnf_count = ""
+ db_vnfr = {}
- # format model name
- model_name = N2VCJujuConnector._format_model_name(model_name)
-
- if model_name in self.juju_models:
- return self.juju_models[model_name]
-
- if self._creating_model:
- self.log.debug("Another coroutine is creating a model. Wait...")
- while self._creating_model:
- # another coroutine is creating a model, wait
- await asyncio.sleep(0.1)
- # retry (perhaps another coroutine has created the model meanwhile)
- if model_name in self.juju_models:
- return self.juju_models[model_name]
-
- try:
- self._creating_model = True
+ 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})
- # get juju model names from juju
- model_list = await self.controller.list_models()
+ # If the charm is ns level, it returns empty vnf_count and db_vnfr
+ return vnf_count, db_vnfr
- if model_name not in model_list:
- self.log.info(
- "Model {} does not exist. Creating new model...".format(model_name)
- )
- config_dict = {"authorized-keys": self.public_key}
- if self.apt_mirror:
- config_dict["apt-mirror"] = self.apt_mirror
- if not self.enable_os_upgrade:
- config_dict["enable-os-refresh-update"] = False
- config_dict["enable-os-upgrade"] = False
- if self.cloud in self.BUILT_IN_CLOUDS:
- model = await self.controller.add_model(
- model_name=model_name,
- config=config_dict,
- cloud_name=self.cloud,
- )
- else:
- model = await self.controller.add_model(
- model_name=model_name,
- config=config_dict,
- cloud_name=self.cloud,
- credential_name=self.cloud,
- )
- self.log.info("New model created, name={}".format(model_name))
- else:
- self.log.debug(
- "Model already exists in juju. Getting model {}".format(model_name)
- )
- model = await self.controller.get_model(model_name)
- self.log.debug("Existing model in juju, name={}".format(model_name))
-
- self.juju_models[model_name] = model
- self.juju_observers[model_name] = JujuModelObserver(n2vc=self, model=model)
- return model
-
- except Exception as e:
- msg = "Cannot get model {}. Exception: {}".format(model_name, e)
- self.log.error(msg)
- raise N2VCException(msg)
- finally:
- self._creating_model = False
-
- async def _juju_add_relation(
- self,
- model_name: str,
- application_name_1: str,
- application_name_2: str,
- relation_1: str,
- relation_2: str,
- ):
-
- # get juju model and observer
- model = await self._juju_get_model(model_name=model_name)
-
- r1 = "{}:{}".format(application_name_1, relation_1)
- r2 = "{}:{}".format(application_name_2, relation_2)
-
- self.log.debug("adding relation: {} -> {}".format(r1, r2))
- try:
- await model.add_relation(relation1=r1, relation2=r2)
- except JujuAPIError as e:
- # If one of the applications in the relationship doesn't exist, or the
- # relation has already been added,
- # let the operation fail silently.
- if "not found" in e.message:
- return
- if "already exists" in e.message:
- return
- # another execption, raise it
- raise e
-
- async def _juju_destroy_application(self, model_name: str, application_name: str):
-
- self.log.debug(
- "Destroying application {} in model {}".format(application_name, model_name)
- )
-
- # get juju model and observer
- model = await self._juju_get_model(model_name=model_name)
- observer = self.juju_observers[model_name]
-
- application = model.applications.get(application_name)
- if application:
- observer.unregister_application(application_name)
- await application.destroy()
- else:
- self.log.debug("Application not found: {}".format(application_name))
-
- async def _juju_destroy_machine(
- self, model_name: str, machine_id: str, total_timeout: float = None
- ):
-
- self.log.debug(
- "Destroying machine {} in model {}".format(machine_id, model_name)
- )
-
- if total_timeout is None:
- total_timeout = 3600
-
- # get juju model and observer
- model = await self._juju_get_model(model_name=model_name)
- observer = self.juju_observers[model_name]
-
- machines = await model.get_machines()
- if machine_id in machines:
- machine = model.machines[machine_id]
- observer.unregister_machine(machine_id)
- # TODO: change this by machine.is_manual when this is upstreamed:
- # https://github.com/juju/python-libjuju/pull/396
- if "instance-id" in machine.safe_data and machine.safe_data[
- "instance-id"
- ].startswith("manual:"):
- self.log.debug("machine.destroy(force=True) started.")
- await machine.destroy(force=True)
- self.log.debug("machine.destroy(force=True) passed.")
- # max timeout
- end = time.time() + total_timeout
- # wait for machine removal
- machines = await model.get_machines()
- while machine_id in machines and time.time() < end:
- self.log.debug(
- "Waiting for machine {} is destroyed".format(machine_id)
- )
- await asyncio.sleep(0.5)
- machines = await model.get_machines()
- self.log.debug("Machine destroyed: {}".format(machine_id))
- else:
- self.log.debug("Machine not found: {}".format(machine_id))
-
- async def _juju_destroy_model(self, model_name: str, total_timeout: float = None):
-
- self.log.debug("Destroying model {}".format(model_name))
-
- if total_timeout is None:
- total_timeout = 3600
- end = time.time() + total_timeout
-
- model = await self._juju_get_model(model_name=model_name)
+ @staticmethod
+ def _get_vca_records(charm_level: str, db_nsr: dict, db_vnfr: dict) -> list:
+ """Get the VCA records from db_nsr dict
- if not model:
- raise N2VCNotFound(message="Model {} does not exist".format(model_name))
+ Args:
+ charm_level (str): level of charm
+ db_nsr (dict): NS record from database
+ db_vnfr (dict): VNF record from database
- uuid = model.info.uuid
+ Returns:
+ vca_records (list): List of VCA record dictionaries
- # destroy applications
- for application_name in model.applications:
- try:
- await self._juju_destroy_application(
- model_name=model_name, application_name=application_name
- )
- except Exception as e:
- self.log.error(
- "Error destroying application {} in model {}: {}".format(
- application_name, model_name, e
- )
- )
-
- # destroy machines
- machines = await model.get_machines()
- for machine_id in machines:
- try:
- await self._juju_destroy_machine(
- model_name=model_name, machine_id=machine_id
+ """
+ vca_records = {}
+ if charm_level == "ns-level":
+ vca_records = list(
+ filter(
+ lambda vca_record: vca_record["target_element"] == "ns",
+ db_nsr["_admin"]["deployed"]["VCA"],
)
- except asyncio.CancelledError:
- raise
- except Exception:
- # ignore exceptions destroying machine
- pass
-
- await self._juju_disconnect_model(model_name=model_name)
-
- self.log.debug("destroying model {}...".format(model_name))
- await self.controller.destroy_model(uuid)
- # self.log.debug('model destroy requested {}'.format(model_name))
-
- # wait for model is completely destroyed
- self.log.debug("Waiting for model {} to be destroyed...".format(model_name))
- last_exception = ""
- while time.time() < end:
- try:
- # await self.controller.get_model(uuid)
- models = await self.controller.list_models()
- if model_name not in models:
- self.log.debug(
- "The model {} ({}) was destroyed".format(model_name, uuid)
- )
- return
- except asyncio.CancelledError:
- raise
- except Exception as e:
- last_exception = e
- await asyncio.sleep(5)
- raise N2VCException(
- "Timeout waiting for model {} to be destroyed {}".format(
- model_name, last_exception
)
- )
-
- async def _juju_login(self):
- """Connect to juju controller
-
- """
-
- # if already authenticated, exit function
- if self._authenticated:
- return
-
- # if connecting, wait for finish
- # another task could be trying to connect in parallel
- while self._connecting:
- await asyncio.sleep(0.1)
-
- # double check after other task has finished
- if self._authenticated:
- return
-
- try:
- self._connecting = True
- self.log.info(
- "connecting to juju controller: {} {}:{}{}".format(
- self.url,
- self.username,
- self.secret[:8] + "...",
- " with ca_cert" if self.ca_cert else "",
+ 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"],
)
)
- # Create controller object
- self.controller = Controller(loop=self.loop)
- # Connect to controller
- await self.controller.connect(
- endpoint=self.url,
- username=self.username,
- password=self.secret,
- cacert=self.ca_cert,
- )
- self._authenticated = True
- self.log.info("juju controller connected")
- except Exception as e:
- message = "Exception connecting to juju: {}".format(e)
- self.log.error(message)
- raise N2VCConnectionException(message=message, url=self.url)
- finally:
- self._connecting = False
+ return vca_records
- async def _juju_logout(self):
- """Logout of the Juju controller."""
- if not self._authenticated:
- return False
+ def _get_application_name(self, namespace: str) -> str:
+ """Build application name from namespace
- # disconnect all models
- for model_name in self.juju_models:
- try:
- await self._juju_disconnect_model(model_name)
- except Exception as e:
- self.log.error(
- "Error disconnecting model {} : {}".format(model_name, e)
- )
- # continue with next model...
+ Application name structure:
+ NS level: <charm-name>-ns
+ VNF level: <ee-name>-z<vnf-ordinal-scale-number>-<vnf-profile-id>-vnf
+ VDU level: <ee-name>-z<vnf-ordinal-scale-number>-<vnf-profile-id>-
+ <vdu-profile-id>-z<vdu-ordinal-scale-number>-vdu
- self.log.info("Disconnecting controller")
- try:
- await self.controller.disconnect()
- except Exception as e:
- raise N2VCConnectionException(
- message="Error disconnecting controller: {}".format(e), url=self.url
- )
+ Application naming for backward compatibility (old structure):
+ NS level: app-<random_value>
+ VNF level: app-vnf-<vnf-id>-z<ordinal-scale-number>-<random_value>
+ VDU level: app-vnf-<vnf-id>-z<vnf-ordinal-scale-number>-vdu-
+ <vdu-id>-cnt-<vdu-count>-z<vdu-ordinal-scale-number>-<random_value>
- self.controller = None
- self._authenticated = False
- self.log.info("disconnected")
+ Args:
+ namespace (str)
- async def _juju_disconnect_model(self, model_name: str):
- self.log.debug("Disconnecting model {}".format(model_name))
- if model_name in self.juju_models:
- await self.juju_models[model_name].disconnect()
- self.juju_models[model_name] = None
- self.juju_observers[model_name] = None
- else:
- self.warning("Cannot disconnect model: {}".format(model_name))
+ Returns:
+ application_name (str)
- def _create_juju_public_key(self):
- """Recreate the Juju public key on lcm container, if needed
- Certain libjuju commands expect to be run from the same machine as Juju
- is bootstrapped to. This method will write the public key to disk in
- that location: ~/.local/share/juju/ssh/juju_id_rsa.pub
"""
+ # 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)
- # Make sure that we have a public key before writing to disk
- if self.public_key is None or len(self.public_key) == 0:
- if "OSMLCM_VCA_PUBKEY" in os.environ:
- self.public_key = os.getenv("OSMLCM_VCA_PUBKEY", "")
- if len(self.public_key) == 0:
- return
- else:
- return
-
- pk_path = "{}/.local/share/juju/ssh".format(os.path.expanduser("~"))
- file_path = "{}/juju_id_rsa.pub".format(pk_path)
- self.log.debug(
- "writing juju public key to file:\n{}\npublic key: {}".format(
- file_path, self.public_key
+ 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,
)
- )
- if not os.path.exists(pk_path):
- # create path and write file
- os.makedirs(pk_path)
- with open(file_path, "w") as f:
- self.log.debug("Creating juju public key file: {}".format(file_path))
- f.write(self.public_key)
else:
- self.log.debug("juju public key file already exists: {}".format(file_path))
+ application_name = self._generate_backward_compatible_application_name(
+ vnf_id_and_count, vdu_id, vdu_count
+ )
+
+ return N2VCJujuConnector._format_app_name(application_name)
@staticmethod
def _format_model_name(name: str) -> str:
app_name = "z" + app_name
return app_name
+
+ async def validate_vca(self, vca_id: str):
+ """
+ Validate a VCA by connecting/disconnecting to/from it
+
+ :param: vca_id: VCA ID
+ """
+ vca_connection = await get_connection(self._store, vca_id=vca_id)
+ libjuju = Libjuju(vca_connection, log=self.log, n2vc=self)
+ controller = await libjuju.get_controller()
+ await libjuju.disconnect_controller(controller)