Merge branch feature7928. It includes feature5837 21/8221/4
authortierno <alfonso.tiernosepulveda@telefonica.com>
Sat, 23 Nov 2019 00:36:52 +0000 (00:36 +0000)
committertierno <alfonso.tiernosepulveda@telefonica.com>
Sat, 23 Nov 2019 22:49:14 +0000 (22:49 +0000)
Change-Id: Ia86ec45a9415df90309ad35dc7c63a063f12db5d
Signed-off-by: tierno <alfonso.tiernosepulveda@telefonica.com>
1  2 
Dockerfile.local
devops-stages/stage-test.sh
osm_lcm/__init__.py
osm_lcm/lcm.py
osm_lcm/lcm_utils.py
osm_lcm/ns.py
osm_lcm/tests/test_ns.py
setup.py

diff --combined Dockerfile.local
@@@ -18,20 -18,33 +18,31 @@@ FROM ubuntu:16.0
  # Set the working directory to /app
  WORKDIR /app/LCM
  
+ RUN apt-get update && apt-get install -y curl \
+     && apt-get update && apt-get install -y apt-transport-https \
+     && curl -s https://packages.cloud.google.com/apt/doc/apt-key.gpg | apt-key add - \
+     && echo "deb https://apt.kubernetes.io/ kubernetes-xenial main" | tee -a /etc/apt/sources.list.d/kubernetes.list \
+     && apt-get update && apt-get install -y kubectl
+ RUN curl https://get.helm.sh/helm-v2.15.2-linux-amd64.tar.gz --output helm-v2.15.2.tar.gz \
+     && tar -zxvf helm-v2.15.2.tar.gz \
+     && mv linux-amd64/helm /usr/local/bin/helm \
+     && rm -r linux-amd64/
  RUN apt-get update && apt-get install -y git tox python3 \
      python3-pip python3-aiohttp python3-jinja2 \
 -    && pip3 install pip==9.0.3 \
 -    && pip3 install -U 'PyYAML==3.*' 'aiohttp==0.20.2' flake8
 +    && python3 -m pip install pip --upgrade  \
 +    && python3 -m pip install -U 'PyYAML==3.*' 'aiohttp==0.20.2' flake8
  
  RUN git -C /app clone https://osm.etsi.org/gerrit/osm/N2VC.git \
 -    && git -C /app/N2VC fetch "https://osm.etsi.org/gerrit/osm/N2VC" refs/changes/56/8156/1 \
 -    && git -C /app/N2VC checkout FETCH_HEAD \
 -    && pip3 install -e /app/N2VC \
 -    && pip3 install -e /app/N2VC/modules/libjuju \
 +    && python3 -m pip install -e /app/N2VC \
 +    && python3 -m pip install -U juju \
      && apt-get install -y libffi-dev libssl-dev openssh-client
      # cd N2VC; python3 setup.py develop
      # cd modules/libjuju; python3 setup.py develop
  
  RUN git -C /app clone https://osm.etsi.org/gerrit/osm/common.git \
 -    && pip3 install -e /app/common
 +    && python3 -m pip install -e /app/common
      #  python3-pymongo python3-yaml pycrypto aiokafka
  
  RUN mkdir -p /app/storage/kafka && mkdir -p /app/log
@@@ -76,6 -89,10 +87,10 @@@ ENV OSMLCM_MESSAGE_DRIVER  kafk
  ENV OSMLCM_MESSAGE_HOST    kafka
  ENV OSMLCM_MESSAGE_PORT    9092
  
+ # k8s
+ ENV OSMLCM_VCA_HELMPATH    /usr/local/bin/helm
+ ENV OSMLCM_VCA_KUBECTLPATH /usr/bin/kubectl
  # logs
  # ENV OSMLCM_GLOBAL_LOGFILE  /app/log/lcm.log
  ENV OSMLCM_GLOBAL_LOGLEVEL DEBUG
@@@ -15,4 -15,4 +15,4 @@@
  ##
  
  tox -e flake8
--tox -e unittest
++tox -e unittest
diff --combined osm_lcm/__init__.py
@@@ -13,5 -13,5 +13,5 @@@
  ##
  
  # version moved to lcm.py. uncomment if LCM is installed as library and installed
- version = '6.0.3.post6'
- version_date = '2018-10-16'
 -version = '6.0.2.post10'
 -version_date = '2019-10-08'
++version = '6.0.3.post12'
++version_date = '2019-11-23'
diff --combined osm_lcm/lcm.py
  # under the License.
  ##
  
+ # DEBUG WITH PDB
+ import os
+ import pdb
  import asyncio
  import yaml
  import logging
@@@ -24,7 -29,11 +29,11 @@@ import logging.handler
  import getopt
  import sys
  
- from osm_lcm import ROclient, ns, vim_sdn, netslice
+ from osm_lcm import ns
+ from osm_lcm import vim_sdn
+ from osm_lcm import netslice
+ from osm_lcm import ROclient
  from time import time, sleep
  from osm_lcm.lcm_utils import versiontuple, LcmException, TaskRegistry, LcmExceptionExit
  from osm_lcm import version as lcm_version, version_date as lcm_version_date
@@@ -38,10 -47,14 +47,14 @@@ from os import environ, pat
  from random import choice as random_choice
  from n2vc import version as n2vc_version
  
+ if os.getenv('OSMLCM_PDB_DEBUG', None) is not None:
+     pdb.set_trace()
  
  __author__ = "Alfonso Tierno"
  min_RO_version = "6.0.2"
  min_n2vc_version = "0.0.2"
  min_common_version = "0.1.19"
  # uncomment if LCM is installed as library and installed, and get them from __init__.py
  # lcm_version = '0.1.41'
@@@ -149,6 -162,7 +162,7 @@@ class Lcm
                  raise LcmException("Invalid configuration param '{}' at '[storage]':'driver'".format(
                      config["storage"]["driver"]))
  
+             # copy message configuration in order to remove 'group_id' for msg_admin
              config_message = config["message"].copy()
              config_message["loop"] = self.loop
              if config_message["driver"] == "local":
          self.vim = vim_sdn.VimLcm(self.db, self.msg, self.fs, self.lcm_tasks, self.ro_config, self.loop)
          self.wim = vim_sdn.WimLcm(self.db, self.msg, self.fs, self.lcm_tasks, self.ro_config, self.loop)
          self.sdn = vim_sdn.SdnLcm(self.db, self.msg, self.fs, self.lcm_tasks, self.ro_config, self.loop)
+         self.k8scluster = vim_sdn.K8sClusterLcm(self.db, self.msg, self.fs, self.lcm_tasks, self.vca_config, self.loop)
+         self.k8srepo = vim_sdn.K8sRepoLcm(self.db, self.msg, self.fs, self.lcm_tasks, self.vca_config, self.loop)
  
      async def check_RO_version(self):
          tries = 14
                  except Exception as e:
                      self.logger.error("Cannot write into '{}' for healthcheck: {}".format(health_check_file, e))
              return
+         elif topic == "k8scluster":
+             if command == "create" or command == "created":
+                 k8scluster_id = params.get("_id")
+                 task = asyncio.ensure_future(self.k8scluster.create(params, order_id))
+                 self.lcm_tasks.register("k8scluster", k8scluster_id, order_id, "k8scluster_create", task)
+                 return
+             elif command == "delete" or command == "deleted":
+                 k8scluster_id = params.get("_id")
+                 task = asyncio.ensure_future(self.k8scluster.delete(params, order_id))
+                 self.lcm_tasks.register("k8scluster", k8scluster_id, order_id, "k8scluster_delete", task)
+                 return
+         elif topic == "k8srepo":
+             if command == "create" or command == "created":
+                 k8srepo_id = params.get("_id")
+                 self.logger.debug("k8srepo_id = {}".format(k8srepo_id))
+                 task = asyncio.ensure_future(self.k8srepo.create(params, order_id))
+                 self.lcm_tasks.register("k8srepo", k8srepo_id, order_id, "k8srepo_create", task)
+                 return
+             elif command == "delete" or command == "deleted":
+                 k8srepo_id = params.get("_id")
+                 task = asyncio.ensure_future(self.k8srepo.delete(params, order_id))
+                 self.lcm_tasks.register("k8srepo", k8srepo_id, order_id, "k8srepo_delete", task)
+                 return
          elif topic == "ns":
-             if command == "instantiate":
+             if command == "instantiate" or command == "instantiated":
                  # self.logger.debug("Deploying NS {}".format(nsr_id))
                  nslcmop = params
                  nslcmop_id = nslcmop["_id"]
                  task = asyncio.ensure_future(self.ns.instantiate(nsr_id, nslcmop_id))
                  self.lcm_tasks.register("ns", nsr_id, nslcmop_id, "ns_instantiate", task)
                  return
-             elif command == "terminate":
+             elif command == "terminate" or command == "terminated":
                  # self.logger.debug("Deleting NS {}".format(nsr_id))
                  nslcmop = params
                  nslcmop_id = nslcmop["_id"]
              elif command in ("terminated", "instantiated", "scaled", "actioned"):  # "scaled-cooldown-time"
                  return
          elif topic == "nsi":  # netslice LCM processes (instantiate, terminate, etc)
-             if command == "instantiate":
+             if command == "instantiate" or command == "instantiated":
                  # self.logger.debug("Instantiating Network Slice {}".format(nsilcmop["netsliceInstanceId"]))
                  nsilcmop = params
                  nsilcmop_id = nsilcmop["_id"]  # slice operation id
                  task = asyncio.ensure_future(self.netslice.instantiate(nsir_id, nsilcmop_id))
                  self.lcm_tasks.register("nsi", nsir_id, nsilcmop_id, "nsi_instantiate", task)
                  return
-             elif command == "terminate":
+             elif command == "terminate" or command == "terminated":
                  # self.logger.debug("Terminating Network Slice NS {}".format(nsilcmop["netsliceInstanceId"]))
                  nsilcmop = params
                  nsilcmop_id = nsilcmop["_id"]  # slice operation id
                  return
          elif topic == "vim_account":
              vim_id = params["_id"]
 -            if command == "create" or command == "created":
 +            if command in ("create", "created"):
                  task = asyncio.ensure_future(self.vim.create(params, order_id))
                  self.lcm_tasks.register("vim_account", vim_id, order_id, "vim_create", task)
                  return
-             elif command == "delete":
+             elif command == "delete" or command == "deleted":
                  self.lcm_tasks.cancel(topic, vim_id)
                  task = asyncio.ensure_future(self.vim.delete(params, order_id))
                  self.lcm_tasks.register("vim_account", vim_id, order_id, "vim_delete", task)
                  print("not implemented show with vim_account")
                  sys.stdout.flush()
                  return
 -            elif command == "edit" or command == "edited":
 +            elif command in ("edit", "edited"):
                  task = asyncio.ensure_future(self.vim.edit(params, order_id))
                  self.lcm_tasks.register("vim_account", vim_id, order_id, "vim_edit", task)
                  return
 +            elif command == "deleted":
 +                return  # TODO cleaning of task just in case should be done
          elif topic == "wim_account":
              wim_id = params["_id"]
 -            if command == "create" or command == "created":
 +            if command in ("create", "created"):
                  task = asyncio.ensure_future(self.wim.create(params, order_id))
                  self.lcm_tasks.register("wim_account", wim_id, order_id, "wim_create", task)
                  return
-             elif command == "delete":
+             elif command == "delete" or command == "deleted":
                  self.lcm_tasks.cancel(topic, wim_id)
                  task = asyncio.ensure_future(self.wim.delete(params, order_id))
                  self.lcm_tasks.register("wim_account", wim_id, order_id, "wim_delete", task)
                  print("not implemented show with wim_account")
                  sys.stdout.flush()
                  return
 -            elif command == "edit" or command == "edited":
 +            elif command in ("edit", "edited"):
                  task = asyncio.ensure_future(self.wim.edit(params, order_id))
                  self.lcm_tasks.register("wim_account", wim_id, order_id, "wim_edit", task)
                  return
 +            elif command == "deleted":
 +                return  # TODO cleaning of task just in case should be done
          elif topic == "sdn":
              _sdn_id = params["_id"]
 -            if command == "create" or command == "created":
 +            if command in ("create", "created"):
                  task = asyncio.ensure_future(self.sdn.create(params, order_id))
                  self.lcm_tasks.register("sdn", _sdn_id, order_id, "sdn_create", task)
                  return
-             elif command == "delete":
+             elif command == "delete" or command == "deleted":
                  self.lcm_tasks.cancel(topic, _sdn_id)
                  task = asyncio.ensure_future(self.sdn.delete(params, order_id))
                  self.lcm_tasks.register("sdn", _sdn_id, order_id, "sdn_delete", task)
                  return
 -            elif command == "edit" or command == "edited":
 +            elif command in ("edit", "edited"):
                  task = asyncio.ensure_future(self.sdn.edit(params, order_id))
                  self.lcm_tasks.register("sdn", _sdn_id, order_id, "sdn_edit", task)
                  return
 +            elif command == "deleted":
 +                return  # TODO cleaning of task just in case should be done
          self.logger.critical("unknown topic {} and command '{}'".format(topic, command))
  
      async def kafka_read(self):
          self.first_start = True
          while self.consecutive_errors < 10:
              try:
-                 topics = ("ns", "vim_account", "wim_account", "sdn", "nsi")
+                 topics = ("ns", "vim_account", "wim_account", "sdn", "nsi", "k8scluster", "k8srepo")
                  topics_admin = ("admin", )
                  await asyncio.gather(
                      self.msg.aioread(topics, self.loop, self.kafka_read_callback),
          # and not parse integer or boolean
          try:
              with open(config_file) as f:
--                conf = yaml.load(f)
++                conf = yaml.load(f, Loader=yaml.Loader)
              for k, v in environ.items():
                  if not k.startswith("OSMLCM_"):
                      continue
  
  def usage():
      print("""Usage: {} [options]
-         -c|--config [configuration_file]: loads the configuration file (default: ./nbi.cfg)
+         -c|--config [configuration_file]: loads the configuration file (default: ./lcm.cfg)
          --health-check: do not run lcm, but inspect kafka bus to determine if lcm is healthy
          -h|--help: shows this help
          """.format(sys.argv[0]))
@@@ -562,8 -595,14 +601,15 @@@ def health_check()
  
  
  if __name__ == '__main__':
      try:
++        print("SYS.PATH='{}'".format(sys.path))
          # load parameters and configuration
+         # -h
+         # -c value
+         # --config value
+         # --help
+         # --health-check
          opts, args = getopt.getopt(sys.argv[1:], "hc:", ["config=", "help", "health-check"])
          # TODO add  "log-socket-host=", "log-socket-port=", "log-file="
          config_file = None
              #     log_file = a
              else:
                  assert False, "Unhandled option"
          if config_file:
              if not path.isfile(config_file):
-                 print("configuration file '{}' not exist".format(config_file), file=sys.stderr)
+                 print("configuration file '{}' does not exist".format(config_file), file=sys.stderr)
                  exit(1)
          else:
              for config_file in (__file__[:__file__.rfind(".")] + ".cfg", "./lcm.cfg", "/etc/osm/lcm.cfg"):
diff --combined osm_lcm/lcm_utils.py
@@@ -18,7 -18,6 +18,7 @@@
  
  import asyncio
  from collections import OrderedDict
 +from time import time
  # from osm_common.dbbase import DbException
  
  __author__ = "Alfonso Tierno"
@@@ -72,8 -71,6 +72,8 @@@ class LcmBase
          """
          if not _desc:
              return
 +        now = time()
 +        _desc["_admin.modified"] = now
          self.db.set_one(item, {"_id": _id}, _desc)
          _desc.clear()
          # except DbException as e:
@@@ -100,7 -97,7 +100,7 @@@ class TaskRegistry(LcmBase)
  
      # NS/NSI: "services" VIM/WIM/SDN: "accounts"
      topic_service_list = ['ns', 'nsi']
-     topic_account_list = ['vim', 'wim', 'sdn']
+     topic_account_list = ['vim', 'wim', 'sdn', 'k8scluster', 'k8srepo']
  
      # Map topic to InstanceID
      topic2instid_dict = {
          'nsi': 'nsilcmops',
          'vim': 'vim_accounts',
          'wim': 'wim_accounts',
-         'sdn': 'sdns'}
+         'sdn': 'sdns',
+         'k8scluster': 'k8sclusters',
+         'k8srepo': 'k8srepos'}
  
      def __init__(self, worker_id=None, db=None, logger=None):
          self.task_registry = {
              "vim_account": {},
              "wim_account": {},
              "sdn": {},
+             "k8scluster": {},
+             "k8srepo": {},
          }
          self.worker_id = worker_id
          self.db = db
          # NS/NSI: Use op_id as '_id'
          elif self._is_service_type_HA(topic):
              _id = op_id
-         # VIM/SDN/WIM: Split op_id to get Account ID and Operation Index, use Account ID as '_id'
+         # VIM/SDN/WIM/K8SCLUSTER: Split op_id to get Account ID and Operation Index, use Account ID as '_id'
          elif self._is_account_type_HA(topic):
              _id, _ = self._get_account_and_op_HA(op_id)
          return _id
          else:
              # NS/NSI
              if self._is_service_type_HA(topic):
 +                now = time()
                  starttime_this_op = db_lcmop.get("startTime")
                  instance_id_label = self.topic2instid_dict.get(topic)
                  instance_id = db_lcmop.get(instance_id_label)
                  _filter = {instance_id_label: instance_id,
                             'operationState': 'PROCESSING',
 -                           'startTime.lt': starttime_this_op}
 +                           'startTime.lt': starttime_this_op,
 +                           "_admin.modified.gt": now - 2*3600,  # ignore if tow hours of inactivity
 +                           }
-             # VIM/WIM/SDN
+             # VIM/WIM/SDN/K8scluster
              elif self._is_account_type_HA(topic):
                  _, op_index = self._get_account_and_op_HA(op_id)
                  _ops = db_lcmop['_admin']['operations']
          the task in this instance of LCM, without querying the DB.
          """
  
-         # Backward compatibility for VIM/WIM/SDN without op_id
+         # Backward compatibility for VIM/WIM/SDN/k8scluster without op_id
          if self._is_account_type_HA(topic) and op_id is None:
              return True
  
diff --combined osm_lcm/ns.py
@@@ -20,16 -20,17 +20,17 @@@ import asynci
  import yaml
  import logging
  import logging.handlers
- import functools
  import traceback
  from jinja2 import Environment, Template, meta, TemplateError, TemplateNotFound, TemplateSyntaxError
  
  from osm_lcm import ROclient
  from osm_lcm.lcm_utils import LcmException, LcmExceptionNoMgmtIP, LcmBase
+ from n2vc.k8s_helm_conn import K8sHelmConnector
  
  from osm_common.dbbase import DbException
  from osm_common.fsbase import FsException
- from n2vc.vnf import N2VC, N2VCPrimitiveExecutionFailed, NetworkServiceDoesNotExist, PrimitiveDoesNotExist
+ from n2vc.n2vc_juju_conn import N2VCJujuConnector
  
  from copy import copy, deepcopy
  from http import HTTPStatus
@@@ -98,32 -99,76 +99,76 @@@ class NsLcm(LcmBase)
          :param config: two level dictionary with configuration. Top level should contain 'database', 'storage',
          :return: None
          """
-         # logging
-         self.logger = logging.getLogger('lcm.ns')
+         super().__init__(
+             db=db,
+             msg=msg,
+             fs=fs,
+             logger=logging.getLogger('lcm.ns')
+         )
          self.loop = loop
          self.lcm_tasks = lcm_tasks
-         super().__init__(db, msg, fs, self.logger)
          self.ro_config = ro_config
+         self.vca_config = vca_config
+         if 'pubkey' in self.vca_config:
+             self.vca_config['public_key'] = self.vca_config['pubkey']
+         if 'cacert' in self.vca_config:
+             self.vca_config['ca_cert'] = self.vca_config['cacert']
+         # create N2VC connector
+         self.n2vc = N2VCJujuConnector(
+             db=self.db,
+             fs=self.fs,
+             log=self.logger,
+             loop=self.loop,
+             url='{}:{}'.format(self.vca_config['host'], self.vca_config['port']),
+             username=self.vca_config.get('user', None),
+             vca_config=self.vca_config,
+             on_update_db=self._on_update_n2vc_db
+             # TODO
+             # New N2VC argument
+             # api_proxy=vca_config.get('apiproxy')
+         )
  
-         self.n2vc = N2VC(
+         self.k8sclusterhelm = K8sHelmConnector(
+             kubectl_command=self.vca_config.get("kubectlpath"),
+             helm_command=self.vca_config.get("helmpath"),
+             fs=self.fs,
              log=self.logger,
-             server=vca_config['host'],
-             port=vca_config['port'],
-             user=vca_config['user'],
-             secret=vca_config['secret'],
-             # TODO: This should point to the base folder where charms are stored,
-             # if there is a common one (like object storage). Otherwise, leave
-             # it unset and pass it via DeployCharms
-             # artifacts=vca_config[''],
-             artifacts=None,
-             juju_public_key=vca_config.get('pubkey'),
-             ca_cert=vca_config.get('cacert'),
-             api_proxy=vca_config.get('apiproxy')
+             db=self.db,
+             on_update_db=None,
          )
+         # create RO client
          self.RO = ROclient.ROClient(self.loop, **self.ro_config)
  
+     def _on_update_n2vc_db(self, table, filter, path, updated_data):
+         self.logger.debug('_on_update_n2vc_db(table={}, filter={}, path={}, updated_data={}'
+                           .format(table, filter, path, updated_data))
+         return
+         # write NS status to database
+         # try:
+         #     # nsrs_id = filter.get('_id')
+         #     # print(nsrs_id)
+         #     # get ns record
+         #     nsr = self.db.get_one(table=table, q_filter=filter)
+         #     # get VCA deployed list
+         #     vca_list = deep_get(target_dict=nsr, key_list=('_admin', 'deployed', 'VCA'))
+         #     # get RO deployed
+         #     # ro_list = deep_get(target_dict=nsr, key_list=('_admin', 'deployed', 'RO'))
+         #     for vca in vca_list:
+         #         # status = vca.get('status')
+         #         # print(status)
+         #         # detailed_status = vca.get('detailed-status')
+         #         # print(detailed_status)
+         #     # for ro in ro_list:
+         #     #    print(ro)
+         #
+         # except Exception as e:
+         #     self.logger.error('Error writing NS status to db: {}'.format(e))
      def vnfd2RO(self, vnfd, new_id=None, additionalParams=None, nsrId=None):
          """
          Converts creates a new vnfd descriptor for RO base on input OSM IM vnfd
              vnfd_RO.pop("vnf-configuration", None)
              vnfd_RO.pop("monitoring-param", None)
              vnfd_RO.pop("scaling-group-descriptor", None)
+             vnfd_RO.pop("kdu", None)
+             vnfd_RO.pop("k8s-cluster", None)
              if new_id:
                  vnfd_RO["id"] = new_id
  
              raise LcmException("Error parsing Jinja2 to cloud-init content at vnfd[id={}]:vdu[id={}]: {}".
                                 format(vnfd["id"], vdu["id"], e))
  
-     def n2vc_callback(self, model_name, application_name, status, message, n2vc_info, task=None):
-         """
-         Callback both for charm status change and task completion
-         :param model_name: Charm model name
-         :param application_name: Charm application name
-         :param status: Can be
-             - blocked: The unit needs manual intervention
-             - maintenance: The unit is actively deploying/configuring
-             - waiting: The unit is waiting for another charm to be ready
-             - active: The unit is deployed, configured, and ready
-             - error: The charm has failed and needs attention.
-             - terminated: The charm has been destroyed
-             - removing,
-             - removed
-         :param message: detailed message error
-         :param n2vc_info: dictionary with information shared with instantiate task. It contains:
-             nsr_id:
-             nslcmop_id:
-             lcmOperationType: currently "instantiate"
-             deployed: dictionary with {<application>: {operational-status: <status>, detailed-status: <text>}}
-             db_update: dictionary to be filled with the changes to be wrote to database with format key.key.key: value
-             n2vc_event: event used to notify instantiation task that some change has been produced
-         :param task: None for charm status change, or task for completion task callback
-         :return:
-         """
-         try:
-             nsr_id = n2vc_info["nsr_id"]
-             deployed = n2vc_info["deployed"]
-             db_nsr_update = n2vc_info["db_update"]
-             nslcmop_id = n2vc_info["nslcmop_id"]
-             ns_operation = n2vc_info["lcmOperationType"]
-             n2vc_event = n2vc_info["n2vc_event"]
-             logging_text = "Task ns={} {}={} [n2vc_callback] application={}".format(nsr_id, ns_operation, nslcmop_id,
-                                                                                     application_name)
-             for vca_index, vca_deployed in enumerate(deployed):
-                 if not vca_deployed:
-                     continue
-                 if model_name == vca_deployed["model"] and application_name == vca_deployed["application"]:
-                     break
-             else:
-                 self.logger.error(logging_text + " Not present at nsr._admin.deployed.VCA. Received model_name={}".
-                                   format(model_name))
-                 return
-             if task:
-                 if task.cancelled():
-                     self.logger.debug(logging_text + " task Cancelled")
-                     vca_deployed['operational-status'] = "error"
-                     db_nsr_update["_admin.deployed.VCA.{}.operational-status".format(vca_index)] = "error"
-                     vca_deployed['detailed-status'] = "Task Cancelled"
-                     db_nsr_update["_admin.deployed.VCA.{}.detailed-status".format(vca_index)] = "Task Cancelled"
-                 elif task.done():
-                     exc = task.exception()
-                     if exc:
-                         self.logger.error(logging_text + " task Exception={}".format(exc))
-                         vca_deployed['operational-status'] = "error"
-                         db_nsr_update["_admin.deployed.VCA.{}.operational-status".format(vca_index)] = "error"
-                         vca_deployed['detailed-status'] = str(exc)
-                         db_nsr_update["_admin.deployed.VCA.{}.detailed-status".format(vca_index)] = str(exc)
-                     else:
-                         self.logger.debug(logging_text + " task Done")
-                         # task is Done, but callback is still ongoing. So ignore
-                         return
-             elif status:
-                 self.logger.debug(logging_text + " Enter status={} message={}".format(status, message))
-                 if vca_deployed['operational-status'] == status:
-                     return  # same status, ignore
-                 vca_deployed['operational-status'] = status
-                 db_nsr_update["_admin.deployed.VCA.{}.operational-status".format(vca_index)] = status
-                 vca_deployed['detailed-status'] = str(message)
-                 db_nsr_update["_admin.deployed.VCA.{}.detailed-status".format(vca_index)] = str(message)
-             else:
-                 self.logger.critical(logging_text + " Enter with bad parameters", exc_info=True)
-                 return
-             # wake up instantiate task
-             n2vc_event.set()
-         except Exception as e:
-             self.logger.critical(logging_text + " Exception {}".format(e), exc_info=True)
      def ns_params_2_RO(self, ns_params, nsd, vnfd_dict, n2vc_key_list):
          """
          Creates a RO ns descriptor from OSM ns_instantiate params
              "wim_account": wim_account_2_RO(ns_params.get("wimAccountId")),
              # "scenario": ns_params["nsdId"],
          }
          n2vc_key_list = n2vc_key_list or []
          for vnfd_ref, vnfd in vnfd_dict.items():
              vdu_needed_access = []
                      populate_dict(RO_ns_params, ("vnfs", vnf_params["member-vnf-index"], "networks",
                                                   internal_vld_params["name"], "ip-profile"),
                                    ip_profile_2_RO(internal_vld_params["ip-profile"]))
 +                if internal_vld_params.get("provider-network"):
 +
 +                    populate_dict(RO_ns_params, ("vnfs", vnf_params["member-vnf-index"], "networks",
 +                                                 internal_vld_params["name"], "provider-network"),
 +                                  internal_vld_params["provider-network"].copy())
  
                  for icp_params in get_iterable(internal_vld_params, "internal-connection-point"):
                      # look for interface
                  populate_dict(RO_ns_params, ("networks", vld_params["name"], "ip-profile"),
                                ip_profile_2_RO(vld_params["ip-profile"]))
  
 +            if vld_params.get("provider-network"):
 +
 +                populate_dict(RO_ns_params, ("networks", vld_params["name"], "provider-network"),
 +                              vld_params["provider-network"].copy())
 +
              if "wimAccountId" in vld_params and vld_params["wimAccountId"] is not None:
                  populate_dict(RO_ns_params, ("networks", vld_params["name"], "wim_account"),
                                wim_account_2_RO(vld_params["wimAccountId"])),
                      RO_vld_sites.append({"netmap-use": vld_params["vim-network-name"]})
                  if RO_vld_sites:
                      populate_dict(RO_ns_params, ("networks", vld_params["name"], "sites"), RO_vld_sites)
 +
              if vld_params.get("vim-network-id"):
                  RO_vld_sites = []
                  if isinstance(vld_params["vim-network-id"], dict):
                      for vld_id, instance_scenario_id in vld_params["ns-net"].items():
                          RO_vld_ns_net = {"instance_scenario_id": instance_scenario_id, "osm_id": vld_id}
                  if RO_vld_ns_net:
-                     populate_dict(RO_ns_params, ("networks", vld_params["name"], "use-network"), RO_vld_ns_net)
+                     populate_dict(RO_ns_params, ("networks", vld_params["name"], "use-network"), RO_vld_ns_net)            
              if "vnfd-connection-point-ref" in vld_params:
                  for cp_params in vld_params["vnfd-connection-point-ref"]:
                      # look for interface
                                      break
                              else:
                                  raise LcmException("ns_update_vnfr: Not found member_vnf_index={} vdur={} interface={} "
-                                                    "from VIM info".format(vnf_index, vdur["vdu-id-ref"],
-                                                                           ifacer["name"]))
+                                                    "from VIM info"
+                                                    .format(vnf_index, vdur["vdu-id-ref"], ifacer["name"]))
                          vnfr_update["vdur.{}".format(vdu_index)] = vdur
                          break
                      else:
              else:
                  raise LcmException("ns_update_vnfr: Not found member_vnf_index={} from VIM info".format(vnf_index))
  
 -
 -
 -        logging_text += "member_vnf_index={} vdu_id={}, vdu_index={} "\
 -            .format(db_vnfr["member-vnf-index-ref"], vdu_id, vdu_index)
 +    @staticmethod
 +    def _get_ns_config_info(vca_deployed_list):
 +        """
 +        Generates a mapping between vnf,vdu elements and the N2VC id
 +        :param vca_deployed_list: List of database _admin.deploy.VCA that contains this list
 +        :return: a dictionary with {osm-config-mapping: {}} where its element contains:
 +            "<member-vnf-index>": <N2VC-id>  for a vnf configuration, or
 +            "<member-vnf-index>.<vdu.id>.<vdu replica(0, 1,..)>": <N2VC-id>  for a vdu configuration
 +        """
 +        mapping = {}
 +        ns_config_info = {"osm-config-mapping": mapping}
 +        for vca in vca_deployed_list:
 +            if not vca["member-vnf-index"]:
 +                continue
 +            if not vca["vdu_id"]:
 +                mapping[vca["member-vnf-index"]] = vca["application"]
 +            else:
 +                mapping["{}.{}.{}".format(vca["member-vnf-index"], vca["vdu_id"], vca["vdu_count_index"])] =\
 +                    vca["application"]
 +        return ns_config_info
 +
 +    @staticmethod
 +    def _get_initial_config_primitive_list(desc_primitive_list, vca_deployed):
 +        """
 +        Generates a list of initial-config-primitive based on the list provided by the descriptor. It includes internal
 +        primitives as verify-ssh-credentials, or config when needed
 +        :param desc_primitive_list: information of the descriptor
 +        :param vca_deployed: information of the deployed, needed for known if it is related to an NS, VNF, VDU and if
 +            this element contains a ssh public key
 +        :return: The modified list. Can ba an empty list, but always a list
 +        """
 +        if desc_primitive_list:
 +            primitive_list = desc_primitive_list.copy()
 +        else:
 +            primitive_list = []
 +        # look for primitive config, and get the position. None if not present
 +        config_position = None
 +        for index, primitive in enumerate(primitive_list):
 +            if primitive["name"] == "config":
 +                config_position = index
 +                break
 +
 +        # for NS, add always a config primitive if not present (bug 874)
 +        if not vca_deployed["member-vnf-index"] and config_position is None:
 +            primitive_list.insert(0, {"name": "config", "parameter": []})
 +            config_position = 0
 +        # for VNF/VDU add verify-ssh-credentials after config
 +        if vca_deployed["member-vnf-index"] and config_position is not None and vca_deployed.get("ssh-public-key"):
 +            primitive_list.insert(config_position + 1, {"name": "verify-ssh-credentials", "parameter": []})
 +        return primitive_list
 +
+     async def instantiate_RO(self, logging_text, nsr_id, nsd, db_nsr,
+                              db_nslcmop, db_vnfrs, db_vnfds_ref, n2vc_key_list):
+         db_nsr_update = {}
+         RO_descriptor_number = 0   # number of descriptors created at RO
+         vnf_index_2_RO_id = {}    # map between vnfd/nsd id to the id used at RO
+         start_deploy = time()
+         vdu_flag = False  # If any of the VNFDs has VDUs
+         ns_params = db_nslcmop.get("operationParams")
+         # deploy RO
+         # get vnfds, instantiate at RO
+         for c_vnf in nsd.get("constituent-vnfd", ()):
+             member_vnf_index = c_vnf["member-vnf-index"]
+             vnfd = db_vnfds_ref[c_vnf['vnfd-id-ref']]
+             if vnfd.get("vdu"):
+                 vdu_flag = True
+             vnfd_ref = vnfd["id"]
+             step = db_nsr_update["_admin.deployed.RO.detailed-status"] = "Creating vnfd='{}' member_vnf_index='{}' at" \
+                                                                          " RO".format(vnfd_ref, member_vnf_index)
+             # self.logger.debug(logging_text + step)
+             vnfd_id_RO = "{}.{}.{}".format(nsr_id, RO_descriptor_number, member_vnf_index[:23])
+             vnf_index_2_RO_id[member_vnf_index] = vnfd_id_RO
+             RO_descriptor_number += 1
+             # look position at deployed.RO.vnfd if not present it will be appended at the end
+             for index, vnf_deployed in enumerate(db_nsr["_admin"]["deployed"]["RO"]["vnfd"]):
+                 if vnf_deployed["member-vnf-index"] == member_vnf_index:
+                     break
+             else:
+                 index = len(db_nsr["_admin"]["deployed"]["RO"]["vnfd"])
+                 db_nsr["_admin"]["deployed"]["RO"]["vnfd"].append(None)
+             # look if present
+             RO_update = {"member-vnf-index": member_vnf_index}
+             vnfd_list = await self.RO.get_list("vnfd", filter_by={"osm_id": vnfd_id_RO})
+             if vnfd_list:
+                 RO_update["id"] = vnfd_list[0]["uuid"]
+                 self.logger.debug(logging_text + "vnfd='{}'  member_vnf_index='{}' exists at RO. Using RO_id={}".
+                                   format(vnfd_ref, member_vnf_index, vnfd_list[0]["uuid"]))
+             else:
+                 vnfd_RO = self.vnfd2RO(vnfd, vnfd_id_RO, db_vnfrs[c_vnf["member-vnf-index"]].
+                                        get("additionalParamsForVnf"), nsr_id)
+                 desc = await self.RO.create("vnfd", descriptor=vnfd_RO)
+                 RO_update["id"] = desc["uuid"]
+                 self.logger.debug(logging_text + "vnfd='{}' member_vnf_index='{}' created at RO. RO_id={}".format(
+                     vnfd_ref, member_vnf_index, desc["uuid"]))
+             db_nsr_update["_admin.deployed.RO.vnfd.{}".format(index)] = RO_update
+             db_nsr["_admin"]["deployed"]["RO"]["vnfd"][index] = RO_update
+             self.update_db_2("nsrs", nsr_id, db_nsr_update)
+             self._on_update_n2vc_db("nsrs", {"_id": nsr_id}, "_admin.deployed", db_nsr_update)
+         # create nsd at RO
+         nsd_ref = nsd["id"]
+         step = db_nsr_update["_admin.deployed.RO.detailed-status"] = "Creating nsd={} at RO".format(nsd_ref)
+         # self.logger.debug(logging_text + step)
+         RO_osm_nsd_id = "{}.{}.{}".format(nsr_id, RO_descriptor_number, nsd_ref[:23])
+         RO_descriptor_number += 1
+         nsd_list = await self.RO.get_list("nsd", filter_by={"osm_id": RO_osm_nsd_id})
+         if nsd_list:
+             db_nsr_update["_admin.deployed.RO.nsd_id"] = RO_nsd_uuid = nsd_list[0]["uuid"]
+             self.logger.debug(logging_text + "nsd={} exists at RO. Using RO_id={}".format(
+                 nsd_ref, RO_nsd_uuid))
+         else:
+             nsd_RO = deepcopy(nsd)
+             nsd_RO["id"] = RO_osm_nsd_id
+             nsd_RO.pop("_id", None)
+             nsd_RO.pop("_admin", None)
+             for c_vnf in nsd_RO.get("constituent-vnfd", ()):
+                 member_vnf_index = c_vnf["member-vnf-index"]
+                 c_vnf["vnfd-id-ref"] = vnf_index_2_RO_id[member_vnf_index]
+             for c_vld in nsd_RO.get("vld", ()):
+                 for cp in c_vld.get("vnfd-connection-point-ref", ()):
+                     member_vnf_index = cp["member-vnf-index-ref"]
+                     cp["vnfd-id-ref"] = vnf_index_2_RO_id[member_vnf_index]
+             desc = await self.RO.create("nsd", descriptor=nsd_RO)
+             db_nsr_update["_admin.nsState"] = "INSTANTIATED"
+             db_nsr_update["_admin.deployed.RO.nsd_id"] = RO_nsd_uuid = desc["uuid"]
+             self.logger.debug(logging_text + "nsd={} created at RO. RO_id={}".format(nsd_ref, RO_nsd_uuid))
+         self.update_db_2("nsrs", nsr_id, db_nsr_update)
+         self._on_update_n2vc_db("nsrs", {"_id": nsr_id}, "_admin.deployed", db_nsr_update)
+         # Crate ns at RO
+         # if present use it unless in error status
+         RO_nsr_id = deep_get(db_nsr, ("_admin", "deployed", "RO", "nsr_id"))
+         if RO_nsr_id:
+             try:
+                 step = db_nsr_update["_admin.deployed.RO.detailed-status"] = "Looking for existing ns at RO"
+                 # self.logger.debug(logging_text + step + " RO_ns_id={}".format(RO_nsr_id))
+                 desc = await self.RO.show("ns", RO_nsr_id)
+             except ROclient.ROClientException as e:
+                 if e.http_code != HTTPStatus.NOT_FOUND:
+                     raise
+                 RO_nsr_id = db_nsr_update["_admin.deployed.RO.nsr_id"] = None
+             if RO_nsr_id:
+                 ns_status, ns_status_info = self.RO.check_ns_status(desc)
+                 db_nsr_update["_admin.deployed.RO.nsr_status"] = ns_status
+                 if ns_status == "ERROR":
+                     step = db_nsr_update["_admin.deployed.RO.detailed-status"] = "Deleting ns at RO. RO_ns_id={}"\
+                         .format(RO_nsr_id)
+                     self.logger.debug(logging_text + step)
+                     await self.RO.delete("ns", RO_nsr_id)
+                     RO_nsr_id = db_nsr_update["_admin.deployed.RO.nsr_id"] = None
+         if not RO_nsr_id:
+             step = db_nsr_update["_admin.deployed.RO.detailed-status"] = "Checking dependencies"
+             # self.logger.debug(logging_text + step)
+             # check if VIM is creating and wait  look if previous tasks in process
+             task_name, task_dependency = self.lcm_tasks.lookfor_related("vim_account", ns_params["vimAccountId"])
+             if task_dependency:
+                 step = "Waiting for related tasks to be completed: {}".format(task_name)
+                 self.logger.debug(logging_text + step)
+                 await asyncio.wait(task_dependency, timeout=3600)
+             if ns_params.get("vnf"):
+                 for vnf in ns_params["vnf"]:
+                     if "vimAccountId" in vnf:
+                         task_name, task_dependency = self.lcm_tasks.lookfor_related("vim_account",
+                                                                                     vnf["vimAccountId"])
+                     if task_dependency:
+                         step = "Waiting for related tasks to be completed: {}".format(task_name)
+                         self.logger.debug(logging_text + step)
+                         await asyncio.wait(task_dependency, timeout=3600)
+             step = db_nsr_update["_admin.deployed.RO.detailed-status"] = "Checking instantiation parameters"
+             RO_ns_params = self.ns_params_2_RO(ns_params, nsd, db_vnfds_ref, n2vc_key_list)
+             step = db_nsr_update["detailed-status"] = "Deploying ns at VIM"
+             # step = db_nsr_update["_admin.deployed.RO.detailed-status"] = "Deploying ns at VIM"
+             desc = await self.RO.create("ns", descriptor=RO_ns_params, name=db_nsr["name"], scenario=RO_nsd_uuid)
+             RO_nsr_id = db_nsr_update["_admin.deployed.RO.nsr_id"] = desc["uuid"]
+             db_nsr_update["_admin.nsState"] = "INSTANTIATED"
+             db_nsr_update["_admin.deployed.RO.nsr_status"] = "BUILD"
+             self.logger.debug(logging_text + "ns created at RO. RO_id={}".format(desc["uuid"]))
+         self.update_db_2("nsrs", nsr_id, db_nsr_update)
+         self._on_update_n2vc_db("nsrs", {"_id": nsr_id}, "_admin.deployed", db_nsr_update)
+         # wait until NS is ready
+         step = ns_status_detailed = detailed_status = "Waiting VIM to deploy ns. RO_ns_id={}".format(RO_nsr_id)
+         detailed_status_old = None
+         self.logger.debug(logging_text + step)
+         while time() <= start_deploy + self.total_deploy_timeout:
+             desc = await self.RO.show("ns", RO_nsr_id)
+             ns_status, ns_status_info = self.RO.check_ns_status(desc)
+             db_nsr_update["_admin.deployed.RO.nsr_status"] = ns_status
+             if ns_status == "ERROR":
+                 raise ROclient.ROClientException(ns_status_info)
+             elif ns_status == "BUILD":
+                 detailed_status = ns_status_detailed + "; {}".format(ns_status_info)
+             elif ns_status == "ACTIVE":
+                 step = detailed_status = "Waiting for management IP address reported by the VIM. Updating VNFRs"
+                 try:
+                     if vdu_flag:
+                         self.ns_update_vnfr(db_vnfrs, desc)
+                     break
+                 except LcmExceptionNoMgmtIP:
+                     pass
+             else:
+                 assert False, "ROclient.check_ns_status returns unknown {}".format(ns_status)
+             if detailed_status != detailed_status_old:
+                 detailed_status_old = db_nsr_update["_admin.deployed.RO.detailed-status"] = detailed_status
+                 self.update_db_2("nsrs", nsr_id, db_nsr_update)
+                 self._on_update_n2vc_db("nsrs", {"_id": nsr_id}, "_admin.deployed", db_nsr_update)
+             await asyncio.sleep(5, loop=self.loop)
+         else:  # total_deploy_timeout
+             raise ROclient.ROClientException("Timeout waiting ns to be ready")
+         step = "Updating NSR"
+         self.ns_update_nsr(db_nsr_update, db_nsr, desc)
+         db_nsr_update["_admin.deployed.RO.operational-status"] = "running"
+         db_nsr["_admin.deployed.RO.detailed-status"] = "Deployed at VIM"
+         db_nsr_update["_admin.deployed.RO.detailed-status"] = "Deployed at VIM"
+         self.update_db_2("nsrs", nsr_id, db_nsr_update)
+         self._on_update_n2vc_db("nsrs", {"_id": nsr_id}, "_admin.deployed", db_nsr_update)
+         step = "Deployed at VIM"
+         self.logger.debug(logging_text + step)
+     # wait for ip addres at RO, and optionally, insert public key in virtual machine
+     # returns IP address
+     async def insert_key_ro(self, logging_text, nsr_id, vnfr_id, vdu_id, vdu_index, pub_key=None, user=None):
+         self.logger.debug(logging_text + "Starting insert_key_ro")
+         ro_nsr_id = None
+         ip_address = None
+         nb_tries = 0
+         target_vdu_id = None
+         while True:
+             await asyncio.sleep(10, loop=self.loop)
+             # wait until NS is deployed at RO
+             if not ro_nsr_id:
+                 db_nsrs = self.db.get_one("nsrs", {"_id": nsr_id})
+                 ro_nsr_id = deep_get(db_nsrs, ("_admin", "deployed", "RO", "nsr_id"))
+             if not ro_nsr_id:
+                 continue
+             # get ip address
+             if not target_vdu_id:
+                 db_vnfr = self.db.get_one("vnfrs", {"_id": vnfr_id})
+                 if not vdu_id:
+                     ip_address = db_vnfr.get("ip-address")
+                     if not ip_address:
+                         continue
+                 for vdur in get_iterable(db_vnfr, "vdur"):
+                     if (vdur["vdu-id-ref"] == vdu_id and vdur["count-index"] == vdu_index) or \
+                             (ip_address and vdur.get("ip-address") == ip_address):
+                         if vdur["status"] == "ACTIVE":
+                             target_vdu_id = vdur["vdu-id-ref"]
+                         elif vdur["status"] == "ERROR":
+                             raise LcmException("Cannot inject ssh-key because target VM is in error state")
+                         break
+                 else:
+                     raise LcmException("Not found vnfr_id={}, vdu_index={}, vdu_index={}".format(
+                         vnfr_id, vdu_id, vdu_index
+                     ))
+             if not target_vdu_id:
+                 continue
+             self.logger.debug(logging_text + "IP address={}".format(ip_address))
+             # inject public key into machine
+             if pub_key and user:
+                 self.logger.debug(logging_text + "Inserting RO key")
+                 try:
+                     ro_vm_id = "{}-{}".format(db_vnfr["member-vnf-index-ref"], target_vdu_id)  # TODO add vdu_index
+                     result_dict = await self.RO.create_action(
+                         item="ns",
+                         item_id_name=ro_nsr_id,
+                         descriptor={"add_public_key": pub_key, "vms": [ro_vm_id], "user": user}
+                     )
+                     # result_dict contains the format {VM-id: {vim_result: 200, description: text}}
+                     if not result_dict or not isinstance(result_dict, dict):
+                         raise LcmException("Unknown response from RO when injecting key")
+                     for result in result_dict.values():
+                         if result.get("vim_result") == 200:
+                             break
+                         else:
+                             raise ROclient.ROClientException("error injecting key: {}".format(
+                                 result.get("description")))
+                     break
+                 except ROclient.ROClientException as e:
+                     nb_tries += 1
+                     if nb_tries >= 10:
+                         raise LcmException("Reaching max tries injecting key. Error: {}".format(e))
+                     self.logger.debug(logging_text + "error injecting key: {}".format(e))
+             else:
+                 break
+         return ip_address
+     async def instantiate_N2VC(self, logging_text, vca_index, nsi_id, db_nsr, db_vnfr, vdu_id,
+                                kdu_name, vdu_index, config_descriptor, deploy_params, base_folder):
+         nsr_id = db_nsr["_id"]
+         db_update_entry = "_admin.deployed.VCA.{}.".format(vca_index)
++        vca_deployed_list = db_nsr["_admin"]["deployed"]["VCA"]
+         vca_deployed = db_nsr["_admin"]["deployed"]["VCA"][vca_index]
+         db_dict = {
+             'collection': 'nsrs',
+             'filter': {'_id': nsr_id},
+             'path': db_update_entry
+         }
 -                step = "register execution envioronment"
++        logging_text += "member_vnf_index={} vdu_id={}, vdu_index={} ".format(db_vnfr["member-vnf-index-ref"],
++                                                                              vdu_id, vdu_index)
+         step = ""
+         try:
+             vnfr_id = None
+             if db_vnfr:
+                 vnfr_id = db_vnfr["_id"]
+             namespace = "{nsi}.{ns}".format(
+                 nsi=nsi_id if nsi_id else "",
+                 ns=nsr_id)
+             if vnfr_id:
+                 namespace += "." + vnfr_id
+                 if vdu_id:
+                     namespace += ".{}-{}".format(vdu_id, vdu_index or 0)
+             # Get artifact path
+             artifact_path = "/{}/{}/charms/{}".format(
+                 base_folder["folder"],
+                 base_folder["pkg-dir"],
+                 config_descriptor["juju"]["charm"]
+             )
+             is_proxy_charm = deep_get(config_descriptor, ('juju', 'charm')) is not None
+             if deep_get(config_descriptor, ('juju', 'proxy')) is False:
+                 is_proxy_charm = False
+             # n2vc_redesign STEP 3.1
+             # find old ee_id if exists
+             ee_id = vca_deployed.get("ee_id")
+             # create or register execution environment in VCA
+             if is_proxy_charm:
+                 step = "create execution environment"
+                 self.logger.debug(logging_text + step)
+                 ee_id, credentials = await self.n2vc.create_execution_environment(
+                     namespace=namespace,
+                     reuse_ee_id=ee_id,
+                     db_dict=db_dict
+                 )
+             else:
 -            initial_config_primitive_list = config_descriptor.get('initial-config-primitive', [])
++                step = "register execution environment"
+                 # TODO wait until deployed by RO, when IP address has been filled. By pooling????
+                 credentials = {}   # TODO db_credentials["ip_address"]
+                 # get username
+                 # TODO remove this when changes on IM regarding config-access:ssh-access:default-user were
+                 #  merged. Meanwhile let's get username from initial-config-primitive
+                 if config_descriptor.get("initial-config-primitive"):
+                     for param in config_descriptor["initial-config-primitive"][0].get("parameter", ()):
+                         if param["name"] == "ssh-username":
+                             credentials["username"] = param["value"]
+                 if config_descriptor.get("config-access") and config_descriptor["config-access"].get("ssh-access"):
+                     if config_descriptor["config-access"]["ssh-access"].get("required"):
+                         credentials["username"] = \
+                             config_descriptor["config-access"]["ssh-access"].get("default-user")
+                 # n2vc_redesign STEP 3.2
+                 self.logger.debug(logging_text + step)
+                 ee_id = await self.n2vc.register_execution_environment(
+                     credentials=credentials,
+                     namespace=namespace,
+                     db_dict=db_dict
+                 )
+             # for compatibility with MON/POL modules, the need model and application name at database
+             # TODO ask to N2VC instead of assuming the format "model_name.application_name"
+             ee_id_parts = ee_id.split('.')
+             model_name = ee_id_parts[0]
+             application_name = ee_id_parts[1]
+             self.update_db_2("nsrs", nsr_id, {db_update_entry + "model": model_name,
+                                               db_update_entry + "application": application_name,
+                                               db_update_entry + "ee_id": ee_id})
+             # n2vc_redesign STEP 3.3
+             # TODO check if already done
+             step = "Install configuration Software"
+             self.logger.debug(logging_text + step)
+             await self.n2vc.install_configuration_sw(
+                 ee_id=ee_id,
+                 artifact_path=artifact_path,
+                 db_dict=db_dict
+             )
+             # if SSH access is required, then get execution environment SSH public
+             required = deep_get(config_descriptor, ("config-access", "ssh-access", "required"))
+             if is_proxy_charm and required:
+                 pub_key = None
+                 pub_key = await self.n2vc.get_ee_ssh_public__key(
+                     ee_id=ee_id,
+                     db_dict=db_dict
+                 )
+                 user = deep_get(config_descriptor, ("config-access", "ssh-access", "default-user"))
+                 # insert pub_key into VM
+                 # n2vc_redesign STEP 5.1
+                 step = "Insert public key into VM"
+                 self.logger.debug(logging_text + step)
+             # wait for RO (ip-address)
+             rw_mgmt_ip = await self.insert_key_ro(
+                 logging_text=logging_text,
+                 nsr_id=nsr_id,
+                 vnfr_id=vnfr_id,
+                 vdu_id=vdu_id,
+                 vdu_index=vdu_index,
+                 user=user,
+                 pub_key=pub_key
+             )
+             # store rw_mgmt_ip in deploy params for later substitution
+             self.logger.debug('rw_mgmt_ip={}'.format(rw_mgmt_ip))
+             deploy_params["rw_mgmt_ip"] = rw_mgmt_ip
+             # n2vc_redesign STEP 6  Execute initial config primitive
++            initial_config_primitive_list = config_descriptor.get('initial-config-primitive')
+             step = 'execute initial config primitive'
+             # sort initial config primitives by 'seq'
+             try:
+                 initial_config_primitive_list.sort(key=lambda val: int(val['seq']))
+             except Exception:
+                 self.logger.warn(logging_text + 'Cannot sort by "seq" field' + step)
++            # add config if not present for NS charm
++            initial_config_primitive_list = self._get_initial_config_primitive_list(initial_config_primitive_list,
++                                                                                    vca_deployed)
++
+             for initial_config_primitive in initial_config_primitive_list:
++                # adding information on the vca_deployed if it is a NS execution environment
++                if not vca_deployed["member-vnf-index"]:
++                    deploy_params["ns_config_info"] = self._get_ns_config_info(vca_deployed_list)
+                 # TODO check if already done
+                 primitive_params_ = self._map_primitive_params(initial_config_primitive, {}, deploy_params)
+                 step = "execute primitive '{}' params '{}'".format(initial_config_primitive["name"], primitive_params_)
+                 self.logger.debug(logging_text + step)
+                 await self.n2vc.exec_primitive(
+                     ee_id=ee_id,
+                     primitive_name=initial_config_primitive["name"],
+                     params_dict=primitive_params_,
+                     db_dict=db_dict
+                 )
+                 # TODO register in database that primitive is done
+             step = "instantiated at VCA"
+             self.logger.debug(logging_text + step)
+         except Exception as e:  # TODO not use Exception but N2VC exception
+             raise Exception("{} {}".format(step, e)) from e
+             # TODO raise N2VC exception with 'step' extra information
      async def instantiate(self, nsr_id, nslcmop_id):
+         """
+         :param nsr_id: ns instance to deploy
+         :param nslcmop_id: operation to run
+         :return:
+         """
  
          # Try to lock HA task here
          task_is_locked_by_me = self.lcm_tasks.lock_HA('ns', 'nslcmops', nslcmop_id)
          if not task_is_locked_by_me:
+             self.logger.debug('instantiate() task is not locked by me')
              return
  
          logging_text = "Task ns={} instantiate={} ".format(nsr_id, nslcmop_id)
          self.logger.debug(logging_text + "Enter")
          # get all needed from database
-         start_deploy = time()
+         # database nsrs record
          db_nsr = None
+         # database nslcmops record
          db_nslcmop = None
-         db_nsr_update = {"_admin.nslcmop": nslcmop_id}
+         # update operation on nsrs
+         db_nsr_update = {"_admin.nslcmop": nslcmop_id,
+                          "_admin.current-operation": nslcmop_id,
+                          "_admin.operation-type": "instantiate"}
+         self.update_db_2("nsrs", nsr_id, db_nsr_update)
+         # update operation on nslcmops
          db_nslcmop_update = {}
          nslcmop_operation_state = None
-         db_vnfrs = {}
-         RO_descriptor_number = 0   # number of descriptors created at RO
-         vnf_index_2_RO_id = {}    # map between vnfd/nsd id to the id used at RO
-         n2vc_info = {}
-         n2vc_key_list = []  # list of public keys to be injected as authorized to VMs
+         db_vnfrs = {}     # vnf's info indexed by member-index
+         # n2vc_info = {}
+         # n2vc_key_list = []  # list of public keys to be injected as authorized to VMs
+         task_instantiation_list = []
          exc = None
          try:
              # wait for any previous tasks in process
 -            step = "Waiting for previous tasks"
 -            self.logger.debug(logging_text + step)
 +            step = "Waiting for previous operations to terminate"
              await self.lcm_tasks.waitfor_related_HA('ns', 'nslcmops', nslcmop_id)
  
+             # STEP 0: Reading database (nslcmops, nsrs, nsds, vnfrs, vnfds)
+             # read from db: operation
              step = "Getting nslcmop={} from db".format(nslcmop_id)
              db_nslcmop = self.db.get_one("nslcmops", {"_id": nslcmop_id})
+             # read from db: ns
              step = "Getting nsr={} from db".format(nsr_id)
              db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
-             ns_params = db_nslcmop.get("operationParams")
+             # nsd is replicated into ns (no db read)
              nsd = db_nsr["nsd"]
-             nsr_name = db_nsr["name"]   # TODO short-name??
+             nsr_name = db_nsr["name"]   # TODO short-name??
  
+             # read from db: vnf's of this ns
              step = "Getting vnfrs from db"
+             self.logger.debug(logging_text + step)
              db_vnfrs_list = self.db.get_list("vnfrs", {"nsr-id-ref": nsr_id})
-             db_vnfds_ref = {}
-             db_vnfds = {}
-             db_vnfds_index = {}
+             # read from db: vnfd's for every vnf
+             db_vnfds_ref = {}     # every vnfd data indexed by vnf name
+             db_vnfds = {}         # every vnfd data indexed by vnf id
+             db_vnfds_index = {}   # every vnfd data indexed by vnf member-index
+             # for each vnf in ns, read vnfd
              for vnfr in db_vnfrs_list:
-                 db_vnfrs[vnfr["member-vnf-index-ref"]] = vnfr
-                 vnfd_id = vnfr["vnfd-id"]
-                 vnfd_ref = vnfr["vnfd-ref"]
+                 db_vnfrs[vnfr["member-vnf-index-ref"]] = vnfr   # vnf's dict indexed by member-index: '1', '2', etc
+                 vnfd_id = vnfr["vnfd-id"]                       # vnfd uuid for this vnf
+                 vnfd_ref = vnfr["vnfd-ref"]                     # vnfd name for this vnf
+                 # if we haven't this vnfd, read it from db
                  if vnfd_id not in db_vnfds:
+                     # read from cb
                      step = "Getting vnfd={} id='{}' from db".format(vnfd_id, vnfd_ref)
+                     self.logger.debug(logging_text + step)
                      vnfd = self.db.get_one("vnfds", {"_id": vnfd_id})
-                     db_vnfds_ref[vnfd_ref] = vnfd
-                     db_vnfds[vnfd_id] = vnfd
-                 db_vnfds_index[vnfr["member-vnf-index-ref"]] = db_vnfds[vnfd_id]
  
-             # Get or generates the _admin.deployed,VCA list
+                     # store vnfd
+                     db_vnfds_ref[vnfd_ref] = vnfd     # vnfd's indexed by name
+                     db_vnfds[vnfd_id] = vnfd          # vnfd's indexed by id
+                 db_vnfds_index[vnfr["member-vnf-index-ref"]] = db_vnfds[vnfd_id]  # vnfd's indexed by member-index
+             # Get or generates the _admin.deployed.VCA list
              vca_deployed_list = None
-             vca_model_name = None
              if db_nsr["_admin"].get("deployed"):
                  vca_deployed_list = db_nsr["_admin"]["deployed"].get("VCA")
-                 vca_model_name = db_nsr["_admin"]["deployed"].get("VCA-model-name")
              if vca_deployed_list is None:
                  vca_deployed_list = []
                  db_nsr_update["_admin.deployed.VCA"] = vca_deployed_list
+                 # add _admin.deployed.VCA to db_nsr dictionary, value=vca_deployed_list
                  populate_dict(db_nsr, ("_admin", "deployed", "VCA"), vca_deployed_list)
              elif isinstance(vca_deployed_list, dict):
                  # maintain backward compatibility. Change a dict to list at database
  
              db_nsr_update["detailed-status"] = "creating"
              db_nsr_update["operational-status"] = "init"
              if not isinstance(deep_get(db_nsr, ("_admin", "deployed", "RO", "vnfd")), list):
                  populate_dict(db_nsr, ("_admin", "deployed", "RO", "vnfd"), [])
                  db_nsr_update["_admin.deployed.RO.vnfd"] = []
              # set state to INSTANTIATED. When instantiated NBI will not delete directly
              db_nsr_update["_admin.nsState"] = "INSTANTIATED"
              self.update_db_2("nsrs", nsr_id, db_nsr_update)
-             # Deploy charms
-             # The parameters we'll need to deploy a charm
-             number_to_configure = 0
-             def deploy_charm(vnf_index, vdu_id, vdu_name, vdu_count_index, charm_params, n2vc_info, native_charm=False):
-                 """An inner function to deploy the charm from either ns, vnf or vdu
-                 For ns both vnf_index and vdu_id are None.
-                 For vnf only vdu_id is None
-                 For vdu both vnf_index and vdu_id contain a value
-                 """
-                 # if not charm_params.get("rw_mgmt_ip") and vnf_index:  # if NS skip mgmt_ip checking
-                 #     raise LcmException("ns/vnfd/vdu has not management ip address to configure it")
-                 machine_spec = {}
-                 if native_charm:
-                     machine_spec["username"] = charm_params.get("username")
-                     machine_spec["hostname"] = charm_params.get("rw_mgmt_ip")
-                 # Note: The charm needs to exist on disk at the location
-                 # specified by charm_path.
-                 descriptor = vnfd if vnf_index else nsd
-                 base_folder = descriptor["_admin"]["storage"]
-                 storage_params = self.fs.get_params()
-                 charm_path = "{}{}/{}/charms/{}".format(
-                     storage_params["path"],
-                     base_folder["folder"],
-                     base_folder["pkg-dir"],
-                     proxy_charm
+             self.logger.debug(logging_text + "Before deploy_kdus")
+             db_k8scluster_list = self.db.get_list("k8sclusters", {})
+             # Call to deploy_kdus in case exists the "vdu:kdu" param
+             task_kdu = asyncio.ensure_future(
+                 self.deploy_kdus(
+                     logging_text=logging_text,
+                     nsr_id=nsr_id,
+                     nsd=nsd,
+                     db_nsr=db_nsr,
+                     db_nslcmop=db_nslcmop,
+                     db_vnfrs=db_vnfrs,
+                     db_vnfds_ref=db_vnfds_ref,
+                     db_k8scluster=db_k8scluster_list
                  )
-                 # ns_name will be ignored in the current version of N2VC
-                 # but will be implemented for the next point release.
-                 model_name = nsr_id
-                 vdu_id_text = (str(vdu_id) if vdu_id else "") + "-"
-                 vnf_index_text = (str(vnf_index) if vnf_index else "") + "-"
-                 application_name = self.n2vc.FormatApplicationName(nsr_name, vnf_index_text, vdu_id_text)
-                 vca_index = len(vca_deployed_list)
-                 # trunk name and add two char index at the end to ensure that it is unique. It is assumed no more than
-                 # 26*26 charm in the same NS
-                 application_name = application_name[0:48]
-                 application_name += chr(97 + vca_index // 26) + chr(97 + vca_index % 26)
-                 vca_deployed_ = {
-                     "member-vnf-index": vnf_index,
-                     "vdu_id": vdu_id,
-                     "model": model_name,
-                     "application": application_name,
-                     "operational-status": "init",
-                     "detailed-status": "",
-                     "step": "initial-deploy",
-                     "vnfd_id": vnfd_id,
-                     "vdu_name": vdu_name,
-                     "vdu_count_index": vdu_count_index,
-                 }
-                 vca_deployed_list.append(vca_deployed_)
-                 db_nsr_update["_admin.deployed.VCA.{}".format(vca_index)] = vca_deployed_
-                 self.update_db_2("nsrs", nsr_id, db_nsr_update)
-                 self.logger.debug("Task create_ns={} Passing artifacts path '{}' for {}".format(nsr_id, charm_path,
-                                                                                                 proxy_charm))
-                 if not n2vc_info:
-                     n2vc_info["nsr_id"] = nsr_id
-                     n2vc_info["nslcmop_id"] = nslcmop_id
-                     n2vc_info["n2vc_event"] = asyncio.Event(loop=self.loop)
-                     n2vc_info["lcmOperationType"] = "instantiate"
-                     n2vc_info["deployed"] = vca_deployed_list
-                     n2vc_info["db_update"] = db_nsr_update
-                 task = asyncio.ensure_future(
-                     self.n2vc.DeployCharms(
-                         model_name,          # The network service name
-                         application_name,    # The application name
-                         descriptor,          # The vnf/nsd descriptor
-                         charm_path,          # Path to charm
-                         charm_params,        # Runtime params, like mgmt ip
-                         machine_spec,        # for native charms only
-                         self.n2vc_callback,  # Callback for status changes
-                         n2vc_info,           # Callback parameter
-                         None,                # Callback parameter (task)
-                     )
+             )
+             self.lcm_tasks.register("ns", nsr_id, nslcmop_id, "instantiate_KDUs", task_kdu)
+             task_instantiation_list.append(task_kdu)
+             # n2vc_redesign STEP 1 Get VCA public ssh-key
+             # feature 1429. Add n2vc public key to needed VMs
+             n2vc_key = await self.n2vc.get_public_key()
+             # n2vc_redesign STEP 2 Deploy Network Scenario
+             task_ro = asyncio.ensure_future(
+                 self.instantiate_RO(
+                     logging_text=logging_text,
+                     nsr_id=nsr_id,
+                     nsd=nsd,
+                     db_nsr=db_nsr,
+                     db_nslcmop=db_nslcmop,
+                     db_vnfrs=db_vnfrs,
+                     db_vnfds_ref=db_vnfds_ref,
+                     n2vc_key_list=[n2vc_key]
                  )
-                 task.add_done_callback(functools.partial(self.n2vc_callback, model_name, application_name, None, None,
-                                                          n2vc_info))
-                 self.lcm_tasks.register("ns", nsr_id, nslcmop_id, "create_charm:" + application_name, task)
+             )
+             self.lcm_tasks.register("ns", nsr_id, nslcmop_id, "instantiate_RO", task_ro)
+             task_instantiation_list.append(task_ro)
  
+             # n2vc_redesign STEP 3 to 6 Deploy N2VC
              step = "Looking for needed vnfd to configure with proxy charm"
              self.logger.debug(logging_text + step)
  
+             nsi_id = None  # TODO put nsi_id when this nsr belongs to a NSI
+             # get_iterable() returns a value from a dict or empty tuple if key does not exist
              for c_vnf in get_iterable(nsd, "constituent-vnfd"):
                  vnfd_id = c_vnf["vnfd-id-ref"]
-                 vnf_index = str(c_vnf["member-vnf-index"])
                  vnfd = db_vnfds_ref[vnfd_id]
+                 member_vnf_index = str(c_vnf["member-vnf-index"])
+                 db_vnfr = db_vnfrs[member_vnf_index]
+                 base_folder = vnfd["_admin"]["storage"]
+                 vdu_id = None
+                 vdu_index = 0
+                 vdu_name = None
+                 kdu_name = None
  
                  # Get additional parameters
-                 vnfr_params = {}
-                 if db_vnfrs[vnf_index].get("additionalParamsForVnf"):
-                     vnfr_params = db_vnfrs[vnf_index]["additionalParamsForVnf"].copy()
-                 for k, v in vnfr_params.items():
+                 deploy_params = {}
+                 if db_vnfr.get("additionalParamsForVnf"):
+                     deploy_params = db_vnfr["additionalParamsForVnf"].copy()
+                 for k, v in deploy_params.items():
                      if isinstance(v, str) and v.startswith("!!yaml "):
-                         vnfr_params[k] = yaml.safe_load(v[7:])
-                 step = "deploying proxy charms for configuration"
-                 # Check if this VNF has a charm configuration
-                 vnf_config = vnfd.get("vnf-configuration")
-                 if vnf_config and vnf_config.get("juju"):
-                     proxy_charm = vnf_config["juju"]["charm"]
-                     if vnf_config["juju"].get("proxy") is False:
-                         # native_charm, will be deployed after VM. Skip
-                         proxy_charm = None
-                     if proxy_charm:
-                         if not vca_model_name:
-                             step = "creating VCA model name '{}'".format(nsr_id)
-                             self.logger.debug(logging_text + step)
-                             await self.n2vc.CreateNetworkService(nsr_id)
-                             vca_model_name = nsr_id
-                             db_nsr_update["_admin.deployed.VCA-model-name"] = nsr_id
-                             self.update_db_2("nsrs", nsr_id, db_nsr_update)
-                         step = "deploying proxy charm to configure vnf {}".format(vnf_index)
-                         vnfr_params["rw_mgmt_ip"] = db_vnfrs[vnf_index]["ip-address"]
-                         charm_params = {
-                             "user_values": vnfr_params,
-                             "rw_mgmt_ip": db_vnfrs[vnf_index]["ip-address"],
-                             "initial-config-primitive": {}    # vnf_config.get('initial-config-primitive') or {}
-                         }
-                         # Login to the VCA. If there are multiple calls to login(),
-                         # subsequent calls will be a nop and return immediately.
-                         await self.n2vc.login()
-                         deploy_charm(vnf_index, None, None, None, charm_params, n2vc_info)
-                         number_to_configure += 1
+                         deploy_params[k] = yaml.safe_load(v[7:])
+                 descriptor_config = vnfd.get("vnf-configuration")
+                 if descriptor_config and descriptor_config.get("juju"):
+                     self._deploy_n2vc(
+                         logging_text=logging_text,
+                         db_nsr=db_nsr,
+                         db_vnfr=db_vnfr,
+                         nslcmop_id=nslcmop_id,
+                         nsr_id=nsr_id,
+                         nsi_id=nsi_id,
+                         vnfd_id=vnfd_id,
+                         vdu_id=vdu_id,
+                         kdu_name=kdu_name,
+                         member_vnf_index=member_vnf_index,
+                         vdu_index=vdu_index,
+                         vdu_name=vdu_name,
+                         deploy_params=deploy_params,
+                         descriptor_config=descriptor_config,
+                         base_folder=base_folder,
+                         task_instantiation_list=task_instantiation_list
+                     )
  
                  # Deploy charms for each VDU that supports one.
-                 for vdu_index, vdu in enumerate(get_iterable(vnfd, 'vdu')):
-                     vdu_config = vdu.get('vdu-configuration')
-                     proxy_charm = None
-                     if vdu_config and vdu_config.get("juju"):
-                         proxy_charm = vdu_config["juju"]["charm"]
-                         if vdu_config["juju"].get("proxy") is False:
-                             # native_charm, will be deployed after VM. Skip
-                             proxy_charm = None
-                         if proxy_charm:
-                             if not vca_model_name:
-                                 step = "creating VCA model name"
-                                 await self.n2vc.CreateNetworkService(nsr_id)
-                                 vca_model_name = nsr_id
-                                 db_nsr_update["_admin.deployed.VCA-model-name"] = nsr_id
-                                 self.update_db_2("nsrs", nsr_id, db_nsr_update)
-                             step = "deploying proxy charm to configure member_vnf_index={} vdu={}".format(vnf_index,
-                                                                                                           vdu["id"])
-                             await self.n2vc.login()
-                             vdur = db_vnfrs[vnf_index]["vdur"][vdu_index]
-                             # TODO for the moment only first vdu_id contains a charm deployed
-                             if vdur["vdu-id-ref"] != vdu["id"]:
-                                 raise LcmException("Mismatch vdur {}, vdu {} at index {} for member_vnf_index={}"
-                                                    .format(vdur["vdu-id-ref"], vdu["id"], vdu_index, vnf_index))
-                             vnfr_params["rw_mgmt_ip"] = vdur["ip-address"]
-                             charm_params = {
-                                 "user_values": vnfr_params,
-                                 "rw_mgmt_ip": vdur["ip-address"],
-                                 "initial-config-primitive": {}  # vdu_config.get('initial-config-primitive') or {}
-                             }
-                             deploy_charm(vnf_index, vdu["id"], vdur.get("name"), vdur["count-index"],
-                                          charm_params, n2vc_info)
-                             number_to_configure += 1
+                 for vdud in get_iterable(vnfd, 'vdu'):
+                     vdu_id = vdud["id"]
+                     descriptor_config = vdud.get('vdu-configuration')
+                     if descriptor_config and descriptor_config.get("juju"):
+                         # look for vdu index in the db_vnfr["vdu"] section
+                         # for vdur_index, vdur in enumerate(db_vnfr["vdur"]):
+                         #     if vdur["vdu-id-ref"] == vdu_id:
+                         #         break
+                         # else:
+                         #     raise LcmException("Mismatch vdu_id={} not found in the vnfr['vdur'] list for "
+                         #                        "member_vnf_index={}".format(vdu_id, member_vnf_index))
+                         # vdu_name = vdur.get("name")
+                         vdu_name = None
+                         kdu_name = None
+                         for vdu_index in range(int(vdud.get("count", 1))):
+                             # TODO vnfr_params["rw_mgmt_ip"] = vdur["ip-address"]
+                             self._deploy_n2vc(
+                                 logging_text=logging_text,
+                                 db_nsr=db_nsr,
+                                 db_vnfr=db_vnfr,
+                                 nslcmop_id=nslcmop_id,
+                                 nsr_id=nsr_id,
+                                 nsi_id=nsi_id,
+                                 vnfd_id=vnfd_id,
+                                 vdu_id=vdu_id,
+                                 kdu_name=kdu_name,
+                                 member_vnf_index=member_vnf_index,
+                                 vdu_index=vdu_index,
+                                 vdu_name=vdu_name,
+                                 deploy_params=deploy_params,
+                                 descriptor_config=descriptor_config,
+                                 base_folder=base_folder,
+                                 task_instantiation_list=task_instantiation_list
+                             )
+                 for kdud in get_iterable(vnfd, 'kdu'):
+                     kdu_name = kdud["name"]
+                     descriptor_config = kdud.get('kdu-configuration')
+                     if descriptor_config and descriptor_config.get("juju"):
+                         vdu_id = None
+                         vdu_index = 0
+                         vdu_name = None
+                         # look for vdu index in the db_vnfr["vdu"] section
+                         # for vdur_index, vdur in enumerate(db_vnfr["vdur"]):
+                         #     if vdur["vdu-id-ref"] == vdu_id:
+                         #         break
+                         # else:
+                         #     raise LcmException("Mismatch vdu_id={} not found in the vnfr['vdur'] list for "
+                         #                        "member_vnf_index={}".format(vdu_id, member_vnf_index))
+                         # vdu_name = vdur.get("name")
+                         # vdu_name = None
+                         self._deploy_n2vc(
+                             logging_text=logging_text,
+                             db_nsr=db_nsr,
+                             db_vnfr=db_vnfr,
+                             nslcmop_id=nslcmop_id,
+                             nsr_id=nsr_id,
+                             nsi_id=nsi_id,
+                             vnfd_id=vnfd_id,
+                             vdu_id=vdu_id,
+                             kdu_name=kdu_name,
+                             member_vnf_index=member_vnf_index,
+                             vdu_index=vdu_index,
+                             vdu_name=vdu_name,
+                             deploy_params=deploy_params,
+                             descriptor_config=descriptor_config,
+                             base_folder=base_folder,
+                             task_instantiation_list=task_instantiation_list
+                         )
  
              # Check if this NS has a charm configuration
-             ns_config = nsd.get("ns-configuration")
-             if ns_config and ns_config.get("juju"):
-                 proxy_charm = ns_config["juju"]["charm"]
-                 if ns_config["juju"].get("proxy") is False:
-                     # native_charm, will be deployed after VM. Skip
-                     proxy_charm = None
-                 if proxy_charm:
-                     step = "deploying proxy charm to configure ns"
-                     # TODO is NS magmt IP address needed?
-                     # Get additional parameters
-                     additional_params = {}
-                     if db_nsr.get("additionalParamsForNs"):
-                         additional_params = db_nsr["additionalParamsForNs"].copy()
-                     for k, v in additional_params.items():
-                         if isinstance(v, str) and v.startswith("!!yaml "):
-                             additional_params[k] = yaml.safe_load(v[7:])
-                     # additional_params["rw_mgmt_ip"] = db_nsr["ip-address"]
-                     charm_params = {
-                         "user_values": additional_params,
-                         # "rw_mgmt_ip": db_nsr["ip-address"],
-                         "initial-config-primitive": {}   # ns_config.get('initial-config-primitive') or {}
-                     }
-                     # Login to the VCA. If there are multiple calls to login(),
-                     # subsequent calls will be a nop and return immediately.
-                     await self.n2vc.login()
-                     deploy_charm(None, None, None, None, charm_params, n2vc_info)
-                     number_to_configure += 1
-             db_nsr_update["operational-status"] = "running"
-             # Wait until all charms has reached blocked or active status
-             step = "waiting proxy charms to be ready"
-             if number_to_configure:
-                 # wait until all charms are configured.
-                 # steps are:
-                 #       initial-deploy
-                 #       get-ssh-public-key
-                 #       generate-ssh-key
-                 #       retry-get-ssh-public-key
-                 #       ssh-public-key-obtained
-                 while time() <= start_deploy + self.total_deploy_timeout:
-                     if db_nsr_update:
-                         self.update_db_2("nsrs", nsr_id, db_nsr_update)
-                     if db_nslcmop_update:
-                         self.update_db_2("nslcmops", nslcmop_id, db_nslcmop_update)
-                     all_active = True
-                     for vca_index, vca_deployed in enumerate(vca_deployed_list):
-                         database_entry = "_admin.deployed.VCA.{}.".format(vca_index)
-                         if vca_deployed["step"] == "initial-deploy":
-                             if vca_deployed["operational-status"] in ("active", "blocked"):
-                                 step = "execute charm primitive get-ssh-public-key for member_vnf_index={} vdu_id={}" \
-                                        .format(vca_deployed["member-vnf-index"],
-                                                vca_deployed["vdu_id"])
-                                 self.logger.debug(logging_text + step)
-                                 try:
-                                     primitive_id = await self.n2vc.ExecutePrimitive(
-                                         vca_deployed["model"],
-                                         vca_deployed["application"],
-                                         "get-ssh-public-key",
-                                         None,
-                                     )
-                                     vca_deployed["step"] = db_nsr_update[database_entry + "step"] = "get-ssh-public-key"
-                                     vca_deployed["primitive_id"] = db_nsr_update[database_entry + "primitive_id"] =\
-                                         primitive_id
-                                     db_nsr_update[database_entry + "operational-status"] =\
-                                         vca_deployed["operational-status"]
-                                 except PrimitiveDoesNotExist:
-                                     ssh_public_key = None
-                                     vca_deployed["step"] = db_nsr_update[database_entry + "step"] =\
-                                         "ssh-public-key-obtained"
-                                     vca_deployed["ssh-public-key"] = db_nsr_update[database_entry + "ssh-public-key"] =\
-                                         ssh_public_key
-                                     step = "charm ssh-public-key for  member_vnf_index={} vdu_id={} not needed".format(
-                                         vca_deployed["member-vnf-index"], vca_deployed["vdu_id"])
-                                     self.logger.debug(logging_text + step)
-                         elif vca_deployed["step"] in ("get-ssh-public-key", "retry-get-ssh-public-key"):
-                             primitive_id = vca_deployed["primitive_id"]
-                             primitive_status = await self.n2vc.GetPrimitiveStatus(vca_deployed["model"],
-                                                                                   primitive_id)
-                             if primitive_status in ("completed", "failed"):
-                                 primitive_result = await self.n2vc.GetPrimitiveOutput(vca_deployed["model"],
-                                                                                       primitive_id)
-                                 vca_deployed["primitive_id"] = db_nsr_update[database_entry + "primitive_id"] = None
-                                 if primitive_status == "completed" and isinstance(primitive_result, dict) and \
-                                         primitive_result.get("pubkey"):
-                                     ssh_public_key = primitive_result.get("pubkey")
-                                     vca_deployed["step"] = db_nsr_update[database_entry + "step"] =\
-                                         "ssh-public-key-obtained"
-                                     vca_deployed["ssh-public-key"] = db_nsr_update[database_entry + "ssh-public-key"] =\
-                                         ssh_public_key
-                                     n2vc_key_list.append(ssh_public_key)
-                                     step = "charm ssh-public-key for  member_vnf_index={} vdu_id={} is '{}'".format(
-                                         vca_deployed["member-vnf-index"], vca_deployed["vdu_id"], ssh_public_key)
-                                     self.logger.debug(logging_text + step)
-                                 else:  # primitive_status == "failed":
-                                     if vca_deployed["step"] == "get-ssh-public-key":
-                                         step = "execute charm primitive generate-ssh-public-key for member_vnf_index="\
-                                                "{} vdu_id={}".format(vca_deployed["member-vnf-index"],
-                                                                      vca_deployed["vdu_id"])
-                                         self.logger.debug(logging_text + step)
-                                         vca_deployed["step"] = db_nsr_update[database_entry + "step"] =\
-                                             "generate-ssh-key"
-                                         primitive_id = await self.n2vc.ExecutePrimitive(
-                                             vca_deployed["model"],
-                                             vca_deployed["application"],
-                                             "generate-ssh-key",
-                                             None,
-                                         )
-                                         vca_deployed["primitive_id"] = db_nsr_update[database_entry + "primitive_id"] =\
-                                             primitive_id
-                                     else:  # failed for second time
-                                         raise LcmException(
-                                             "error executing primitive get-ssh-public-key: {}".format(primitive_result))
-                         elif vca_deployed["step"] == "generate-ssh-key":
-                             primitive_id = vca_deployed["primitive_id"]
-                             primitive_status = await self.n2vc.GetPrimitiveStatus(vca_deployed["model"],
-                                                                                   primitive_id)
-                             if primitive_status in ("completed", "failed"):
-                                 primitive_result = await self.n2vc.GetPrimitiveOutput(vca_deployed["model"],
-                                                                                       primitive_id)
-                                 vca_deployed["primitive_id"] = db_nsr_update[
-                                     database_entry + "primitive_id"] = None
-                                 if primitive_status == "completed":
-                                     step = "execute primitive get-ssh-public-key again for member_vnf_index={} "\
-                                            "vdu_id={}".format(vca_deployed["member-vnf-index"],
-                                                               vca_deployed["vdu_id"])
-                                     self.logger.debug(logging_text + step)
-                                     vca_deployed["step"] = db_nsr_update[database_entry + "step"] = \
-                                         "retry-get-ssh-public-key"
-                                     primitive_id = await self.n2vc.ExecutePrimitive(
-                                         vca_deployed["model"],
-                                         vca_deployed["application"],
-                                         "get-ssh-public-key",
-                                         None,
-                                     )
-                                     vca_deployed["primitive_id"] = db_nsr_update[database_entry + "primitive_id"] =\
-                                         primitive_id
-                                 else:  # primitive_status == "failed":
-                                     raise LcmException("error executing primitive  generate-ssh-key: {}"
-                                                        .format(primitive_result))
-                         if vca_deployed["step"] != "ssh-public-key-obtained":
-                             all_active = False
-                     if all_active:
-                         break
-                     await asyncio.sleep(5)
-                 else:   # total_deploy_timeout
-                     raise LcmException("Timeout waiting charm to be initialized for member_vnf_index={} vdu_id={}"
-                                        .format(vca_deployed["member-vnf-index"], vca_deployed["vdu_id"]))
-             # deploy RO
-             # get vnfds, instantiate at RO
-             for c_vnf in nsd.get("constituent-vnfd", ()):
-                 member_vnf_index = c_vnf["member-vnf-index"]
-                 vnfd = db_vnfds_ref[c_vnf['vnfd-id-ref']]
-                 vnfd_ref = vnfd["id"]
-                 step = db_nsr_update["detailed-status"] = "Creating vnfd='{}' member_vnf_index='{}' at RO".format(
-                     vnfd_ref, member_vnf_index)
-                 # self.logger.debug(logging_text + step)
-                 vnfd_id_RO = "{}.{}.{}".format(nsr_id, RO_descriptor_number, member_vnf_index[:23])
-                 vnf_index_2_RO_id[member_vnf_index] = vnfd_id_RO
-                 RO_descriptor_number += 1
-                 # look position at deployed.RO.vnfd if not present it will be appended at the end
-                 for index, vnf_deployed in enumerate(db_nsr["_admin"]["deployed"]["RO"]["vnfd"]):
-                     if vnf_deployed["member-vnf-index"] == member_vnf_index:
-                         break
-                 else:
-                     index = len(db_nsr["_admin"]["deployed"]["RO"]["vnfd"])
-                     db_nsr["_admin"]["deployed"]["RO"]["vnfd"].append(None)
-                 # look if present
-                 RO_update = {"member-vnf-index": member_vnf_index}
-                 vnfd_list = await self.RO.get_list("vnfd", filter_by={"osm_id": vnfd_id_RO})
-                 if vnfd_list:
-                     RO_update["id"] = vnfd_list[0]["uuid"]
-                     self.logger.debug(logging_text + "vnfd='{}'  member_vnf_index='{}' exists at RO. Using RO_id={}".
-                                       format(vnfd_ref, member_vnf_index, vnfd_list[0]["uuid"]))
-                 else:
-                     vnfd_RO = self.vnfd2RO(vnfd, vnfd_id_RO, db_vnfrs[c_vnf["member-vnf-index"]].
-                                            get("additionalParamsForVnf"), nsr_id)
-                     desc = await self.RO.create("vnfd", descriptor=vnfd_RO)
-                     RO_update["id"] = desc["uuid"]
-                     self.logger.debug(logging_text + "vnfd='{}' member_vnf_index='{}' created at RO. RO_id={}".format(
-                         vnfd_ref, member_vnf_index, desc["uuid"]))
-                 db_nsr_update["_admin.deployed.RO.vnfd.{}".format(index)] = RO_update
-                 db_nsr["_admin"]["deployed"]["RO"]["vnfd"][index] = RO_update
-                 self.update_db_2("nsrs", nsr_id, db_nsr_update)
-             # create nsd at RO
-             nsd_ref = nsd["id"]
-             step = db_nsr_update["detailed-status"] = "Creating nsd={} at RO".format(nsd_ref)
-             # self.logger.debug(logging_text + step)
-             RO_osm_nsd_id = "{}.{}.{}".format(nsr_id, RO_descriptor_number, nsd_ref[:23])
-             RO_descriptor_number += 1
-             nsd_list = await self.RO.get_list("nsd", filter_by={"osm_id": RO_osm_nsd_id})
-             if nsd_list:
-                 db_nsr_update["_admin.deployed.RO.nsd_id"] = RO_nsd_uuid = nsd_list[0]["uuid"]
-                 self.logger.debug(logging_text + "nsd={} exists at RO. Using RO_id={}".format(
-                     nsd_ref, RO_nsd_uuid))
-             else:
-                 nsd_RO = deepcopy(nsd)
-                 nsd_RO["id"] = RO_osm_nsd_id
-                 nsd_RO.pop("_id", None)
-                 nsd_RO.pop("_admin", None)
-                 for c_vnf in nsd_RO.get("constituent-vnfd", ()):
-                     member_vnf_index = c_vnf["member-vnf-index"]
-                     c_vnf["vnfd-id-ref"] = vnf_index_2_RO_id[member_vnf_index]
-                 for c_vld in nsd_RO.get("vld", ()):
-                     for cp in c_vld.get("vnfd-connection-point-ref", ()):
-                         member_vnf_index = cp["member-vnf-index-ref"]
-                         cp["vnfd-id-ref"] = vnf_index_2_RO_id[member_vnf_index]
-                 desc = await self.RO.create("nsd", descriptor=nsd_RO)
-                 db_nsr_update["_admin.nsState"] = "INSTANTIATED"
-                 db_nsr_update["_admin.deployed.RO.nsd_id"] = RO_nsd_uuid = desc["uuid"]
-                 self.logger.debug(logging_text + "nsd={} created at RO. RO_id={}".format(nsd_ref, RO_nsd_uuid))
-             self.update_db_2("nsrs", nsr_id, db_nsr_update)
-             # Crate ns at RO
-             # if present use it unless in error status
-             RO_nsr_id = deep_get(db_nsr, ("_admin", "deployed", "RO", "nsr_id"))
-             if RO_nsr_id:
-                 try:
-                     step = db_nsr_update["detailed-status"] = "Looking for existing ns at RO"
-                     # self.logger.debug(logging_text + step + " RO_ns_id={}".format(RO_nsr_id))
-                     desc = await self.RO.show("ns", RO_nsr_id)
-                 except ROclient.ROClientException as e:
-                     if e.http_code != HTTPStatus.NOT_FOUND:
-                         raise
-                     RO_nsr_id = db_nsr_update["_admin.deployed.RO.nsr_id"] = None
-                 if RO_nsr_id:
-                     ns_status, ns_status_info = self.RO.check_ns_status(desc)
-                     db_nsr_update["_admin.deployed.RO.nsr_status"] = ns_status
-                     if ns_status == "ERROR":
-                         step = db_nsr_update["detailed-status"] = "Deleting ns at RO. RO_ns_id={}".format(RO_nsr_id)
-                         self.logger.debug(logging_text + step)
-                         await self.RO.delete("ns", RO_nsr_id)
-                         RO_nsr_id = db_nsr_update["_admin.deployed.RO.nsr_id"] = None
-             if not RO_nsr_id:
-                 step = db_nsr_update["detailed-status"] = "Checking dependencies"
-                 # self.logger.debug(logging_text + step)
-                 # check if VIM is creating and wait  look if previous tasks in process
-                 task_name, task_dependency = self.lcm_tasks.lookfor_related("vim_account", ns_params["vimAccountId"])
-                 if task_dependency:
-                     step = "Waiting for related tasks to be completed: {}".format(task_name)
-                     self.logger.debug(logging_text + step)
-                     await asyncio.wait(task_dependency, timeout=3600)
-                 if ns_params.get("vnf"):
-                     for vnf in ns_params["vnf"]:
-                         if "vimAccountId" in vnf:
-                             task_name, task_dependency = self.lcm_tasks.lookfor_related("vim_account",
-                                                                                         vnf["vimAccountId"])
-                         if task_dependency:
-                             step = "Waiting for related tasks to be completed: {}".format(task_name)
-                             self.logger.debug(logging_text + step)
-                             await asyncio.wait(task_dependency, timeout=3600)
-                 step = db_nsr_update["detailed-status"] = "Checking instantiation parameters"
-                 # feature 1429. Add n2vc public key to needed VMs
-                 n2vc_key = await self.n2vc.GetPublicKey()
-                 n2vc_key_list.append(n2vc_key)
-                 RO_ns_params = self.ns_params_2_RO(ns_params, nsd, db_vnfds_ref, n2vc_key_list)
-                 step = db_nsr_update["detailed-status"] = "Deploying ns at VIM"
-                 desc = await self.RO.create("ns", descriptor=RO_ns_params,
-                                             name=db_nsr["name"],
-                                             scenario=RO_nsd_uuid)
-                 RO_nsr_id = db_nsr_update["_admin.deployed.RO.nsr_id"] = desc["uuid"]
-                 db_nsr_update["_admin.nsState"] = "INSTANTIATED"
-                 db_nsr_update["_admin.deployed.RO.nsr_status"] = "BUILD"
-                 self.logger.debug(logging_text + "ns created at RO. RO_id={}".format(desc["uuid"]))
-             self.update_db_2("nsrs", nsr_id, db_nsr_update)
-             # wait until NS is ready
-             step = ns_status_detailed = detailed_status = "Waiting VIM to deploy ns. RO_id={}".format(RO_nsr_id)
-             detailed_status_old = None
-             self.logger.debug(logging_text + step)
-             while time() <= start_deploy + self.total_deploy_timeout:
-                 desc = await self.RO.show("ns", RO_nsr_id)
-                 ns_status, ns_status_info = self.RO.check_ns_status(desc)
-                 db_nsr_update["_admin.deployed.RO.nsr_status"] = ns_status
-                 if ns_status == "ERROR":
-                     raise ROclient.ROClientException(ns_status_info)
-                 elif ns_status == "BUILD":
-                     detailed_status = ns_status_detailed + "; {}".format(ns_status_info)
-                 elif ns_status == "ACTIVE":
-                     step = detailed_status = "Waiting for management IP address reported by the VIM. Updating VNFRs"
-                     try:
-                         self.ns_update_vnfr(db_vnfrs, desc)
-                         break
-                     except LcmExceptionNoMgmtIP:
-                         pass
-                 else:
-                     assert False, "ROclient.check_ns_status returns unknown {}".format(ns_status)
-                 if detailed_status != detailed_status_old:
-                     detailed_status_old = db_nsr_update["detailed-status"] = detailed_status
-                     self.update_db_2("nsrs", nsr_id, db_nsr_update)
-                 await asyncio.sleep(5, loop=self.loop)
-             else:   # total_deploy_timeout
-                 raise ROclient.ROClientException("Timeout waiting ns to be ready")
-             step = "Updating NSR"
-             self.ns_update_nsr(db_nsr_update, db_nsr, desc)
-             db_nsr_update["operational-status"] = "running"
-             db_nsr["detailed-status"] = "Configuring vnfr"
-             self.update_db_2("nsrs", nsr_id, db_nsr_update)
-             # Configure proxy charms once VMs are up
-             for vca_index, vca_deployed in enumerate(vca_deployed_list):
-                 vnf_index = vca_deployed.get("member-vnf-index")
-                 vdu_id = vca_deployed.get("vdu_id")
+             descriptor_config = nsd.get("ns-configuration")
+             if descriptor_config and descriptor_config.get("juju"):
+                 vnfd_id = None
+                 db_vnfr = None
+                 member_vnf_index = None
+                 vdu_id = None
+                 kdu_name = None
+                 vdu_index = 0
                  vdu_name = None
-                 vdu_count_index = None
-                 step = "executing proxy charm initial primitives for member_vnf_index={} vdu_id={}".format(vnf_index,
-                                                                                                            vdu_id)
-                 add_params = {}
-                 initial_config_primitive_list = None
-                 if vnf_index:
-                     if db_vnfrs[vnf_index].get("additionalParamsForVnf"):
-                         add_params = db_vnfrs[vnf_index]["additionalParamsForVnf"].copy()
-                     vnfd = db_vnfds_index[vnf_index]
-                     if vdu_id:
-                         for vdu_index, vdu in enumerate(get_iterable(vnfd, 'vdu')):
-                             if vdu["id"] == vdu_id:
-                                 initial_config_primitive_list = vdu['vdu-configuration'].get('initial-config-primitive')
-                                 break
-                         else:
-                             raise LcmException("Not found vdu_id={} at vnfd:vdu".format(vdu_id))
-                         vdur = db_vnfrs[vnf_index]["vdur"][vdu_index]
-                         # TODO for the moment only first vdu_id contains a charm deployed
-                         if vdur["vdu-id-ref"] != vdu["id"]:
-                             raise LcmException("Mismatch vdur {}, vdu {} at index {} for vnf {}"
-                                                .format(vdur["vdu-id-ref"], vdu["id"], vdu_index, vnf_index))
-                         add_params["rw_mgmt_ip"] = vdur["ip-address"]
-                     else:
-                         add_params["rw_mgmt_ip"] = db_vnfrs[vnf_index]["ip-address"]
-                         initial_config_primitive_list = vnfd["vnf-configuration"].get('initial-config-primitive')
-                 else:
-                     if db_nsr.get("additionalParamsForNs"):
-                         add_params = db_nsr["additionalParamsForNs"].copy()
-                     for k, v in add_params.items():
-                         if isinstance(v, str) and v.startswith("!!yaml "):
-                             add_params[k] = yaml.safe_load(v[7:])
-                     add_params["rw_mgmt_ip"] = None
-                     add_params["ns_config_info"] = self._get_ns_config_info(vca_deployed_list)
-                     initial_config_primitive_list = nsd["ns-configuration"].get('initial-config-primitive')
-                 # add primitive verify-ssh-credentials to the list after config only when is a vnf or vdu charm
-                 # add config if not present for NS charm
-                 initial_config_primitive_list = self._get_initial_config_primitive_list(initial_config_primitive_list,
-                                                                                         vca_deployed)
-                 for initial_config_primitive in initial_config_primitive_list:
-                     primitive_params_ = self._map_primitive_params(initial_config_primitive, {}, add_params)
-                     self.logger.debug(logging_text + step + " primitive '{}' params '{}'"
-                                       .format(initial_config_primitive["name"], primitive_params_))
-                     primitive_result, primitive_detail = await self._ns_execute_primitive(
-                         db_nsr["_admin"]["deployed"], vnf_index, vdu_id, vdu_name, vdu_count_index,
-                         initial_config_primitive["name"],
-                         primitive_params_,
-                         retries=10 if initial_config_primitive["name"] == "verify-ssh-credentials" else 0,
-                         retries_interval=30)
-                     if primitive_result != "COMPLETED":
-                         raise LcmException("charm error executing primitive {} for member_vnf_index={} vdu_id={}: '{}'"
-                                            .format(initial_config_primitive["name"], vca_deployed["member-vnf-index"],
-                                                    vca_deployed["vdu_id"], primitive_detail))
-             # Deploy native charms
-             step = "Looking for needed vnfd to configure with native charm"
-             self.logger.debug(logging_text + step)
-             for c_vnf in get_iterable(nsd, "constituent-vnfd"):
-                 vnfd_id = c_vnf["vnfd-id-ref"]
-                 vnf_index = str(c_vnf["member-vnf-index"])
-                 vnfd = db_vnfds_ref[vnfd_id]
 +
                  # Get additional parameters
-                 vnfr_params = {}
-                 if db_vnfrs[vnf_index].get("additionalParamsForVnf"):
-                     vnfr_params = db_vnfrs[vnf_index]["additionalParamsForVnf"].copy()
-                 for k, v in vnfr_params.items():
+                 deploy_params = {}
+                 if db_nsr.get("additionalParamsForNs"):
+                     deploy_params = db_nsr["additionalParamsForNs"].copy()
+                 for k, v in deploy_params.items():
                      if isinstance(v, str) and v.startswith("!!yaml "):
-                         vnfr_params[k] = yaml.safe_load(v[7:])
-                 # Check if this VNF has a charm configuration
-                 vnf_config = vnfd.get("vnf-configuration")
-                 if vnf_config and vnf_config.get("juju"):
-                     native_charm = vnf_config["juju"].get("proxy") is False
-                     proxy_charm = vnf_config["juju"]["charm"]
-                     if native_charm and proxy_charm:
-                         if not vca_model_name:
-                             step = "creating VCA model name '{}'".format(nsr_id)
-                             self.logger.debug(logging_text + step)
-                             await self.n2vc.CreateNetworkService(nsr_id)
-                             vca_model_name = nsr_id
-                             db_nsr_update["_admin.deployed.VCA-model-name"] = nsr_id
-                             self.update_db_2("nsrs", nsr_id, db_nsr_update)
-                         step = "deploying native charm for vnf_member_index={}".format(vnf_index)
-                         self.logger.debug(logging_text + step)
-                         vnfr_params["rw_mgmt_ip"] = db_vnfrs[vnf_index]["ip-address"]
-                         charm_params = {
-                             "user_values": vnfr_params,
-                             "rw_mgmt_ip": db_vnfrs[vnf_index]["ip-address"],
-                             "initial-config-primitive": vnf_config.get('initial-config-primitive') or {},
-                         }
-                         # get username
-                         # TODO remove this when changes on IM regarding config-access:ssh-access:default-user were
-                         #  merged. Meanwhile let's get username from initial-config-primitive
-                         if vnf_config.get("initial-config-primitive"):
-                             for param in vnf_config["initial-config-primitive"][0].get("parameter", ()):
-                                 if param["name"] == "ssh-username":
-                                     charm_params["username"] = param["value"]
-                         if vnf_config.get("config-access") and vnf_config["config-access"].get("ssh-access"):
-                             if vnf_config["config-access"]["ssh-access"].get("required"):
-                                 charm_params["username"] = vnf_config["config-access"]["ssh-access"].get("default-user")
-                         # Login to the VCA. If there are multiple calls to login(),
-                         # subsequent calls will be a nop and return immediately.
-                         await self.n2vc.login()
-                         deploy_charm(vnf_index, None, None, None, charm_params, n2vc_info, native_charm)
-                         number_to_configure += 1
-                 # Deploy charms for each VDU that supports one.
-                 for vdu_index, vdu in enumerate(get_iterable(vnfd, 'vdu')):
-                     vdu_config = vdu.get('vdu-configuration')
-                     native_charm = False
-                     if vdu_config and vdu_config.get("juju"):
-                         native_charm = vdu_config["juju"].get("proxy") is False
-                         proxy_charm = vdu_config["juju"]["charm"]
-                         if native_charm and proxy_charm:
-                             if not vca_model_name:
-                                 step = "creating VCA model name"
-                                 await self.n2vc.CreateNetworkService(nsr_id)
-                                 vca_model_name = nsr_id
-                                 db_nsr_update["_admin.deployed.VCA-model-name"] = nsr_id
-                                 self.update_db_2("nsrs", nsr_id, db_nsr_update)
-                             step = "deploying native charm for vnf_member_index={} vdu_id={}".format(vnf_index,
-                                                                                                      vdu["id"])
-                             self.logger.debug(logging_text + step)
-                             vdur = db_vnfrs[vnf_index]["vdur"][vdu_index]
-                             # TODO for the moment only first vdu_id contains a charm deployed
-                             if vdur["vdu-id-ref"] != vdu["id"]:
-                                 raise LcmException("Mismatch vdur {}, vdu {} at index {} for vnf {}"
-                                                    .format(vdur["vdu-id-ref"], vdu["id"], vdu_index, vnf_index))
-                             vnfr_params["rw_mgmt_ip"] = vdur["ip-address"]
-                             charm_params = {
-                                 "user_values": vnfr_params,
-                                 "rw_mgmt_ip": vdur["ip-address"],
-                                 "initial-config-primitive": vdu_config.get('initial-config-primitive') or {}
-                             }
-                             # get username
-                             # TODO remove this when changes on IM regarding config-access:ssh-access:default-user were
-                             #  merged. Meanwhile let's get username from initial-config-primitive
-                             if vdu_config.get("initial-config-primitive"):
-                                 for param in vdu_config["initial-config-primitive"][0].get("parameter", ()):
-                                     if param["name"] == "ssh-username":
-                                         charm_params["username"] = param["value"]
-                             if vdu_config.get("config-access") and vdu_config["config-access"].get("ssh-access"):
-                                 if vdu_config["config-access"]["ssh-access"].get("required"):
-                                     charm_params["username"] = vdu_config["config-access"]["ssh-access"].get(
-                                         "default-user")
-                             await self.n2vc.login()
-                             deploy_charm(vnf_index, vdu["id"], vdur.get("name"), vdur["count-index"],
-                                          charm_params, n2vc_info, native_charm)
-                             number_to_configure += 1
-             # Check if this NS has a charm configuration
-             ns_config = nsd.get("ns-configuration")
-             if ns_config and ns_config.get("juju"):
-                 native_charm = ns_config["juju"].get("proxy") is False
-                 proxy_charm = ns_config["juju"]["charm"]
-                 if native_charm and proxy_charm:
-                     step = "deploying native charm to configure ns"
-                     # TODO is NS magmt IP address needed?
-                     # Get additional parameters
-                     additional_params = {}
-                     if db_nsr.get("additionalParamsForNs"):
-                         additional_params = db_nsr["additionalParamsForNs"].copy()
-                     for k, v in additional_params.items():
-                         if isinstance(v, str) and v.startswith("!!yaml "):
-                             additional_params[k] = yaml.safe_load(v[7:])
-                     # additional_params["rw_mgmt_ip"] = db_nsr["ip-address"]
-                     charm_params = {
-                         "user_values": additional_params,
-                         "rw_mgmt_ip": db_nsr.get("ip-address"),
-                         "initial-config-primitive": ns_config.get('initial-config-primitive') or {}
-                     }
-                     # get username
-                     # TODO remove this when changes on IM regarding config-access:ssh-access:default-user were
-                     #  merged. Meanwhile let's get username from initial-config-primitive
-                     if ns_config.get("initial-config-primitive"):
-                         for param in ns_config["initial-config-primitive"][0].get("parameter", ()):
-                             if param["name"] == "ssh-username":
-                                 charm_params["username"] = param["value"]
-                     if ns_config.get("config-access") and ns_config["config-access"].get("ssh-access"):
-                         if ns_config["config-access"]["ssh-access"].get("required"):
-                             charm_params["username"] = ns_config["config-access"]["ssh-access"].get("default-user")
-                     # Login to the VCA. If there are multiple calls to login(),
-                     # subsequent calls will be a nop and return immediately.
-                     await self.n2vc.login()
-                     deploy_charm(None, None, None, None, charm_params, n2vc_info, native_charm)
-                     number_to_configure += 1
-             # waiting all charms are ok
-             configuration_failed = False
-             if number_to_configure:
-                 step = "Waiting all charms are active"
-                 old_status = "configuring: init: {}".format(number_to_configure)
-                 db_nsr_update["config-status"] = old_status
-                 db_nsr_update["detailed-status"] = old_status
-                 db_nslcmop_update["detailed-status"] = old_status
-                 # wait until all are configured.
-                 while time() <= start_deploy + self.total_deploy_timeout:
-                     if db_nsr_update:
-                         self.update_db_2("nsrs", nsr_id, db_nsr_update)
-                     if db_nslcmop_update:
-                         self.update_db_2("nslcmops", nslcmop_id, db_nslcmop_update)
-                     # TODO add a fake task that set n2vc_event after some time
-                     await n2vc_info["n2vc_event"].wait()
-                     n2vc_info["n2vc_event"].clear()
-                     all_active = True
-                     status_map = {}
-                     n2vc_error_text = []  # contain text error list. If empty no one is in error status
-                     now = time()
-                     for vca_deployed in vca_deployed_list:
-                         vca_status = vca_deployed["operational-status"]
-                         if vca_status not in status_map:
-                             # Initialize it
-                             status_map[vca_status] = 0
-                         status_map[vca_status] += 1
-                         if vca_status == "active":
-                             vca_deployed.pop("time_first_error", None)
-                             vca_deployed.pop("status_first_error", None)
-                             continue
+                         deploy_params[k] = yaml.safe_load(v[7:])
+                 base_folder = nsd["_admin"]["storage"]
+                 self._deploy_n2vc(
+                     logging_text=logging_text,
+                     db_nsr=db_nsr,
+                     db_vnfr=db_vnfr,
+                     nslcmop_id=nslcmop_id,
+                     nsr_id=nsr_id,
+                     nsi_id=nsi_id,
+                     vnfd_id=vnfd_id,
+                     vdu_id=vdu_id,
+                     kdu_name=kdu_name,
+                     member_vnf_index=member_vnf_index,
+                     vdu_index=vdu_index,
+                     vdu_name=vdu_name,
+                     deploy_params=deploy_params,
+                     descriptor_config=descriptor_config,
+                     base_folder=base_folder,
+                     task_instantiation_list=task_instantiation_list
+                 )
  
-                         all_active = False
-                         if vca_status in ("error", "blocked"):
-                             vca_deployed["detailed-status-error"] = vca_deployed["detailed-status"]
-                             # if not first time in this status error
-                             if not vca_deployed.get("time_first_error"):
-                                 vca_deployed["time_first_error"] = now
-                                 continue
-                         if vca_deployed.get("time_first_error") and \
-                                 now <= vca_deployed["time_first_error"] + self.timeout_vca_on_error:
-                             n2vc_error_text.append("member_vnf_index={} vdu_id={} {}: {}"
-                                                    .format(vca_deployed["member-vnf-index"],
-                                                            vca_deployed["vdu_id"], vca_status,
-                                                            vca_deployed["detailed-status-error"]))
-                     if all_active:
-                         break
-                     elif n2vc_error_text:
-                         db_nsr_update["config-status"] = "failed"
-                         error_text = "fail configuring " + ";".join(n2vc_error_text)
-                         db_nsr_update["detailed-status"] = error_text
-                         db_nslcmop_update["operationState"] = nslcmop_operation_state = "FAILED_TEMP"
-                         db_nslcmop_update["detailed-status"] = error_text
-                         db_nslcmop_update["statusEnteredTime"] = time()
-                         configuration_failed = True
-                         break
-                     else:
-                         cs = "configuring: "
-                         separator = ""
-                         for status, num in status_map.items():
-                             cs += separator + "{}: {}".format(status, num)
-                             separator = ", "
-                         if old_status != cs:
-                             db_nsr_update["config-status"] = cs
-                             db_nsr_update["detailed-status"] = cs
-                             db_nslcmop_update["detailed-status"] = cs
-                             old_status = cs
-                 else:   # total_deploy_timeout
-                     raise LcmException("Timeout waiting ns to be configured")
-             if not configuration_failed:
+             # Wait until all tasks of "task_instantiation_list" have been finished
+             # while time() <= start_deploy + self.total_deploy_timeout:
+             error_text = None
+             timeout = 3600  # time() - start_deploy
+             task_instantiation_set = set(task_instantiation_list)    # build a set with tasks
+             done = None
+             pending = None
+             if len(task_instantiation_set) > 0:
+                 done, pending = await asyncio.wait(task_instantiation_set, timeout=timeout)
+             if pending:
+                 error_text = "timeout"
+             for task in done:
+                 if task.cancelled():
+                     if not error_text:
+                         error_text = "cancelled"
+                 elif task.done():
+                     exc = task.exception()
+                     if exc:
+                         error_text = str(exc)
+             if error_text:
+                 db_nsr_update["config-status"] = "failed"
+                 error_text = "fail configuring " + error_text
+                 db_nsr_update["detailed-status"] = error_text
+                 db_nslcmop_update["operationState"] = nslcmop_operation_state = "FAILED_TEMP"
+                 db_nslcmop_update["detailed-status"] = error_text
+                 db_nslcmop_update["statusEnteredTime"] = time()
+             else:
                  # all is done
                  db_nslcmop_update["operationState"] = nslcmop_operation_state = "COMPLETED"
                  db_nslcmop_update["statusEnteredTime"] = time()
                  db_nsr_update["config-status"] = "configured"
                  db_nsr_update["detailed-status"] = "done"
  
-             return
          except (ROclient.ROClientException, DbException, LcmException) as e:
              self.logger.error(logging_text + "Exit Exception while '{}': {}".format(step, e))
              exc = e
              try:
                  if db_nsr:
                      db_nsr_update["_admin.nslcmop"] = None
+                     db_nsr_update["_admin.current-operation"] = None
+                     db_nsr_update["_admin.operation-type"] = None
                      self.update_db_2("nsrs", nsr_id, db_nsr_update)
                  if db_nslcmop_update:
                      self.update_db_2("nslcmops", nslcmop_id, db_nslcmop_update)
              self.logger.debug(logging_text + "Exit")
              self.lcm_tasks.remove("ns", nsr_id, nslcmop_id, "ns_instantiate")
  
-     async def _destroy_charm(self, model, application):
-         """
-         Order N2VC destroy a charm
-         :param model:
-         :param application:
-         :return: True if charm does not exist. False if it exist
-         """
-         if not await self.n2vc.HasApplication(model, application):
-             return True  # Already removed
-         await self.n2vc.RemoveCharms(model, application)
-         return False
+     async def deploy_kdus(self, logging_text, nsr_id, nsd, db_nsr, db_nslcmop, db_vnfrs, db_vnfds_ref, db_k8scluster):
+         # Launch kdus if present in the descriptor
+         logging_text = "Deploy kdus: "
+         db_nsr_update = {}
+         db_nsr_update["_admin.deployed.K8s"] = []
+         try:
+             # Look for all vnfds
+             # db_nsr_update["_admin.deployed.K8s"] = []
+             vnf_update = []
+             task_list = []
+             for c_vnf in nsd.get("constituent-vnfd", ()):
+                 vnfr = db_vnfrs[c_vnf["member-vnf-index"]]
+                 member_vnf_index = c_vnf["member-vnf-index"]
+                 vnfd = db_vnfds_ref[c_vnf['vnfd-id-ref']]
+                 vnfd_ref = vnfd["id"]
+                 desc_params = {}
  
-     async def _wait_charm_destroyed(self, model, application, timeout):
-         """
-         Wait until charm does not exist
-         :param model:
-         :param application:
-         :param timeout:
-         :return: True if not exist, False if timeout
-         """
-         while True:
-             if not await self.n2vc.HasApplication(model, application):
-                 return True
-             if timeout < 0:
-                 return False
-             await asyncio.sleep(10)
-             timeout -= 10
+                 step = "Checking kdu from vnf: {} - member-vnf-index: {}".format(vnfd_ref, member_vnf_index)
+                 self.logger.debug(logging_text + step)
+                 if vnfd.get("kdu"):
+                     step = "vnf: {} has kdus".format(vnfd_ref)
+                     self.logger.debug(logging_text + step)
+                     for vnfr_name, vnfr_data in db_vnfrs.items():
+                         if vnfr_data["vnfd-ref"] == vnfd["id"]:
+                             if vnfr_data.get("additionalParamsForVnf"):
+                                 desc_params = self._format_additional_params(vnfr_data["additionalParamsForVnf"])
+                             break
+                     else:
+                         raise LcmException("VNF descriptor not found with id: {}".format(vnfr_data["vnfd-ref"]))
+                         self.logger.debug(logging_text + step)
+                     for kdur in vnfr.get("kdur"):
+                         index = 0
+                         for k8scluster in db_k8scluster:
+                             if kdur["k8s-cluster"]["id"] == k8scluster["_id"]:
+                                 cluster_uuid = k8scluster["cluster-uuid"]
+                                 break
+                         else:
+                             raise LcmException("K8scluster not found with id: {}".format(kdur["k8s-cluster"]["id"]))
+                             self.logger.debug(logging_text + step)
+                         step = "Instantiate KDU {} in k8s cluster {}".format(kdur["kdu-name"], cluster_uuid)
+                         self.logger.debug(logging_text + step)
+                         for kdu in vnfd.get("kdu"):
+                             if kdu.get("name") == kdur["kdu-name"]:
+                                 break
+                         else:
+                             raise LcmException("KDU not found with name: {} in VNFD {}".format(kdur["kdu-name"],
+                                                                                                vnfd["name"]))
+                             self.logger.debug(logging_text + step)
+                         kdumodel = None
+                         k8sclustertype = None
+                         if kdu.get("helm-chart"):
+                             kdumodel = kdu["helm-chart"]
+                             k8sclustertype = "chart"
+                         elif kdu.get("juju-bundle"):
+                             kdumodel = kdu["juju-bundle"]
+                             k8sclustertype = "juju"
+                         k8s_instace_info = {"kdu-instance": None, "k8scluster-uuid": cluster_uuid,
+                                             "vnfr-id": vnfr["id"], "k8scluster-type": k8sclustertype,
+                                             "kdu-name": kdur["kdu-name"], "kdu-model": kdumodel}
+                         db_nsr_update["_admin.deployed.K8s"].append(k8s_instace_info)
+                         db_dict = {"collection": "nsrs", "filter": {"_id": nsr_id}, "path": "_admin.deployed.K8s."
+                                                                                             "{}".format(index)}
+                         if k8sclustertype == "chart":
 -                            task = self.k8sclusterhelm.install(cluster_uuid=cluster_uuid,
 -                                                           kdu_model=kdumodel, atomic=True, params=desc_params,
 -                                                           db_dict=db_dict, timeout=300)
++                            task = self.k8sclusterhelm.install(cluster_uuid=cluster_uuid, kdu_model=kdumodel,
++                                                               atomic=True, params=desc_params,
++                                                               db_dict=db_dict, timeout=300)
+                         else:
+                             # TODO I need the juju connector in place
+                             pass
+                         task_list.append(task)
+                         index += 1
+             self.update_db_2("nsrs", nsr_id, db_nsr_update)
+             done = None
+             pending = None
+             if len(task_list) > 0:
+                 self.logger.debug('Waiting for terminate pending tasks...')
+                 done, pending = await asyncio.wait(task_list, timeout=3600)
+                 if not pending:
+                     for fut in done:
+                         k8s_instance = fut.result()
+                         k8s_instace_info = {"kdu-instance": k8s_instance, "k8scluster-uuid": cluster_uuid,
+                                             "vnfr-id": vnfr["id"], "k8scluster-type": k8sclustertype,
+                                             "kdu-name": kdur["kdu-name"], "kdu-model": kdumodel}
+                         vnf_update.append(k8s_instace_info)
+                     self.logger.debug('All tasks finished...')
+                 else:
+                     self.logger.info('There are pending tasks: {}'.format(pending))
+             db_nsr_update["_admin.deployed.K8s"] = vnf_update
+         except Exception as e:
+             self.logger.critical(logging_text + "Exit Exception {} while '{}': {}".format(type(e).__name__, step, e))
+             raise LcmException("{} Exit Exception {} while '{}': {}".format(logging_text, type(e).__name__, step, e))
+         finally:
+             # TODO Write in data base
+             if db_nsr_update:
+                 self.update_db_2("nsrs", nsr_id, db_nsr_update)
++
+     def _deploy_n2vc(self, logging_text, db_nsr, db_vnfr, nslcmop_id, nsr_id, nsi_id, vnfd_id, vdu_id,
+                      kdu_name, member_vnf_index, vdu_index, vdu_name, deploy_params, descriptor_config,
+                      base_folder, task_instantiation_list):
+         # launch instantiate_N2VC in a asyncio task and register task object
+         # Look where information of this charm is at database <nsrs>._admin.deployed.VCA
+         # if not found, create one entry and update database
+         # fill db_nsr._admin.deployed.VCA.<index>
+         vca_index = -1
+         for vca_index, vca_deployed in enumerate(db_nsr["_admin"]["deployed"]["VCA"]):
+             if not vca_deployed:
+                 continue
+             if vca_deployed.get("member-vnf-index") == member_vnf_index and \
+                     vca_deployed.get("vdu_id") == vdu_id and \
+                     vca_deployed.get("kdu_name") == kdu_name and \
+                     vca_deployed.get("vdu_count_index", 0) == vdu_index:
+                 break
+         else:
+             # not found, create one.
+             vca_deployed = {
+                 "member-vnf-index": member_vnf_index,
+                 "vdu_id": vdu_id,
+                 "kdu_name": kdu_name,
+                 "vdu_count_index": vdu_index,
+                 "operational-status": "init",  # TODO revise
+                 "detailed-status": "",  # TODO revise
+                 "step": "initial-deploy",   # TODO revise
+                 "vnfd_id": vnfd_id,
+                 "vdu_name": vdu_name,
+             }
+             vca_index += 1
+             self.update_db_2("nsrs", nsr_id, {"_admin.deployed.VCA.{}".format(vca_index): vca_deployed})
+             db_nsr["_admin"]["deployed"]["VCA"].append(vca_deployed)
+         # Launch task
+         task_n2vc = asyncio.ensure_future(
+             self.instantiate_N2VC(
+                 logging_text=logging_text,
+                 vca_index=vca_index,
+                 nsi_id=nsi_id,
+                 db_nsr=db_nsr,
+                 db_vnfr=db_vnfr,
+                 vdu_id=vdu_id,
+                 kdu_name=kdu_name,
+                 vdu_index=vdu_index,
+                 deploy_params=deploy_params,
+                 config_descriptor=descriptor_config,
+                 base_folder=base_folder,
+             )
+         )
+         self.lcm_tasks.register("ns", nsr_id, nslcmop_id, "instantiate_N2VC-{}".format(vca_index), task_n2vc)
+         task_instantiation_list.append(task_n2vc)
  
      # Check if this VNFD has a configured terminate action
      def _has_terminate_config_primitive(self, vnfd):
          }
          return nslcmop
  
+     def _format_additional_params(self, params):
+         for key, value in params.items():
+             if str(value).startswith("!!yaml "):
+                 params[key] = yaml.safe_load(value[7:])
+         return params
      def _get_terminate_primitive_params(self, seq, vnf_index):
          primitive = seq.get('name')
          primitive_params = {}
      # 'detailed-status' : status message
      # 'operationType': may be any type, in the case of scaling: 'PRE-SCALE' | 'POST-SCALE'
      # Status and operation type are currently only used for 'scale', but NOT for 'terminate' sub-operations.
-     def _add_suboperation(self, db_nslcmop, vnf_index, vdu_id, vdu_count_index,
-                           vdu_name, primitive, mapped_primitive_params,
-                           operationState=None, detailed_status=None, operationType=None,
+     def _add_suboperation(self, db_nslcmop, vnf_index, vdu_id, vdu_count_index, vdu_name, primitive, 
+                           mapped_primitive_params, operationState=None, detailed_status=None, operationType=None,
                            RO_nsr_id=None, RO_scaling_info=None):
          if not (db_nslcmop):
              return self.SUBOPERATION_STATUS_NOT_FOUND
      # a. New: First time execution, return SUBOPERATION_STATUS_NEW
      # b. Skip: Existing sub-operation exists, operationState == 'COMPLETED', return SUBOPERATION_STATUS_SKIP
      # c. Reintent: Existing sub-operation exists, operationState != 'COMPLETED', return op_index to re-execute
-     def _check_or_add_scale_suboperation(self, db_nslcmop, vnf_index,
-                                          vnf_config_primitive, primitive_params, operationType,
-                                          RO_nsr_id=None, RO_scaling_info=None):
+     def _check_or_add_scale_suboperation(self, db_nslcmop, vnf_index, vnf_config_primitive, primitive_params,
+                                          operationType, RO_nsr_id=None, RO_scaling_info=None):
          # Find this sub-operation
          if (RO_nsr_id and RO_scaling_info):
              operationType = 'SCALE-RO'
                                         primitive,
                                         mapped_primitive_params)
                  # Sub-operations: Call _ns_execute_primitive() instead of action()
-                 db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
-                 nsr_deployed = db_nsr["_admin"]["deployed"]
-                 result, result_detail = await self._ns_execute_primitive(
-                     nsr_deployed, vnf_index, vdu_id, vdu_name, vdu_count_index, primitive,
-                     mapped_primitive_params)
+                 # db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
+                 # nsr_deployed = db_nsr["_admin"]["deployed"]
  
                  # nslcmop_operation_state, nslcmop_operation_state_detail = await self.action(
                  #    nsr_id, nslcmop_terminate_action_id)
                  # Launch Exception if action() returns other than ['COMPLETED', 'PARTIALLY_COMPLETED']
-                 result_ok = ['COMPLETED', 'PARTIALLY_COMPLETED']
-                 if result not in result_ok:
+                 # result_ok = ['COMPLETED', 'PARTIALLY_COMPLETED']
+                 # if result not in result_ok:
+                 #     raise LcmException(
+                 #         "terminate_primitive_action for vnf_member_index={}",
+                 #         " primitive={} fails with error {}".format(
+                 #             vnf_index, seq.get("name"), result_detail))
+                 # TODO: find ee_id
+                 ee_id = None
+                 try:
+                     await self.n2vc.exec_primitive(
+                         ee_id=ee_id,
+                         primitive_name=primitive,
+                         params_dict=mapped_primitive_params
+                     )
+                 except Exception as e:
+                     self.logger.error('Error executing primitive {}: {}'.format(primitive, e))
                      raise LcmException(
-                         "terminate_primitive_action for vnf_member_index={}",
-                         " primitive={} fails with error {}".format(
-                             vnf_index, seq.get("name"), result_detail))
+                         "terminate_primitive_action for vnf_member_index={}, primitive={} fails with error {}"
+                         .format(vnf_index, seq.get("name"), e),
+                     )
  
      async def terminate(self, nsr_id, nslcmop_id):
  
          db_nslcmop = None
          exc = None
          failed_detail = []   # annotates all failed error messages
-         vca_time_destroy = None   # time of where destroy charm order
-         db_nsr_update = {"_admin.nslcmop": nslcmop_id}
+         db_nsr_update = {"_admin.nslcmop": nslcmop_id,
+                          "_admin.current-operation": nslcmop_id,
+                          "_admin.operation-type": "terminate"}
+         self.update_db_2("nsrs", nsr_id, db_nsr_update)
          db_nslcmop_update = {}
          nslcmop_operation_state = None
          autoremove = False  # autoremove after terminated
+         pending_tasks = []
          try:
              # wait for any previous tasks in process
 +            step = "Waiting for previous operations to terminate"
              await self.lcm_tasks.waitfor_related_HA("ns", 'nslcmops', nslcmop_id)
  
              step = "Getting nslcmop={} from db".format(nslcmop_id)
              # Call internal terminate action
              await self._terminate_action(db_nslcmop, nslcmop_id, nsr_id)
  
+             pending_tasks = []
              db_nsr_update["operational-status"] = "terminating"
              db_nsr_update["config-status"] = "terminating"
  
-             if nsr_deployed and nsr_deployed.get("VCA-model-name"):
-                 vca_model_name = nsr_deployed["VCA-model-name"]
-                 step = "deleting VCA model name '{}' and all charms".format(vca_model_name)
+             # remove NS
+             try:
+                 step = "delete execution environment"
                  self.logger.debug(logging_text + step)
-                 try:
-                     await self.n2vc.DestroyNetworkService(vca_model_name)
-                 except NetworkServiceDoesNotExist:
-                     pass
-                 db_nsr_update["_admin.deployed.VCA-model-name"] = None
-                 if nsr_deployed.get("VCA"):
-                     for vca_index in range(0, len(nsr_deployed["VCA"])):
-                         db_nsr_update["_admin.deployed.VCA.{}".format(vca_index)] = None
-                 self.update_db_2("nsrs", nsr_id, db_nsr_update)
-             # for backward compatibility if charm have been created with "default"  model name delete one by one
-             elif nsr_deployed and nsr_deployed.get("VCA"):
-                 try:
-                     step = "Scheduling configuration charms removing"
-                     db_nsr_update["detailed-status"] = "Deleting charms"
-                     self.logger.debug(logging_text + step)
-                     self.update_db_2("nsrs", nsr_id, db_nsr_update)
-                     # for backward compatibility
-                     if isinstance(nsr_deployed["VCA"], dict):
-                         nsr_deployed["VCA"] = list(nsr_deployed["VCA"].values())
-                         db_nsr_update["_admin.deployed.VCA"] = nsr_deployed["VCA"]
-                         self.update_db_2("nsrs", nsr_id, db_nsr_update)
-                     for vca_index, vca_deployed in enumerate(nsr_deployed["VCA"]):
-                         if vca_deployed:
-                             if await self._destroy_charm(vca_deployed['model'], vca_deployed["application"]):
-                                 vca_deployed.clear()
-                                 db_nsr["_admin.deployed.VCA.{}".format(vca_index)] = None
-                             else:
-                                 vca_time_destroy = time()
-                 except Exception as e:
-                     self.logger.debug(logging_text + "Failed while deleting charms: {}".format(e))
+                 task_delete_ee = asyncio.ensure_future(self.n2vc.delete_namespace(namespace="." + nsr_id))
+                 pending_tasks.append(task_delete_ee)
+             except Exception as e:
+                 msg = "Failed while deleting NS in VCA: {}".format(e)
+                 self.logger.error(msg)
+                 failed_detail.append(msg)
+             try:
+                 # Delete from k8scluster
+                 step = "delete kdus"
+                 self.logger.debug(logging_text + step)
+                 print(nsr_deployed)
+                 if nsr_deployed:
+                     for kdu in nsr_deployed.get("K8s"):
+                         if kdu.get("k8scluster-type") == "chart":
+                             task_delete_kdu_instance = asyncio.ensure_future(self.k8sclusterhelm.uninstall(
+                                 cluster_uuid=kdu.get("k8scluster-uuid"), kdu_instance=kdu.get("kdu-instance")))
+                         elif kdu.get("k8scluster-type") == "juju":
+                             # TODO Juju connector needed
+                             pass
+                         else:
+                             msg = "k8scluster-type not defined"
+                             raise LcmException(msg)
+                         pending_tasks.append(task_delete_kdu_instance)
+             except LcmException as e:
+                 msg = "Failed while deleting KDUs from NS: {}".format(e)
+                 self.logger.error(msg)
+                 failed_detail.append(msg)
  
              # remove from RO
              RO_fail = False
  
                      delete_timeout = 20 * 60   # 20 minutes
                      while delete_timeout > 0:
-                         desc = await self.RO.show("ns", item_id_name=RO_nsr_id, extra_item="action",
-                                                   extra_item_id=RO_delete_action)
+                         desc = await self.RO.show(
+                             "ns",
+                             item_id_name=RO_nsr_id,
+                             extra_item="action",
+                             extra_item_id=RO_delete_action)
                          ns_status, ns_status_info = self.RO.check_action_status(desc)
                          if ns_status == "ERROR":
                              raise ROclient.ROClientException(ns_status_info)
                              failed_detail.append("RO_vnfd_id={} delete error: {}".format(RO_vnfd_id, e))
                              self.logger.error(logging_text + failed_detail[-1])
  
-             # wait until charm deleted
-             if vca_time_destroy:
-                 db_nsr_update["detailed-status"] = db_nslcmop_update["detailed-status"] = step = \
-                     "Waiting for deletion of configuration charms"
-                 self.update_db_2("nslcmops", nslcmop_id, db_nslcmop_update)
-                 self.update_db_2("nsrs", nsr_id, db_nsr_update)
-                 for vca_index, vca_deployed in enumerate(nsr_deployed["VCA"]):
-                     if not vca_deployed:
-                         continue
-                     step = "Waiting for deletion of charm application_name={}".format(vca_deployed["application"])
-                     timeout = self.timeout_charm_delete - int(time() - vca_time_destroy)
-                     if not await self._wait_charm_destroyed(vca_deployed['model'], vca_deployed["application"],
-                                                             timeout):
-                         failed_detail.append("VCA[application_name={}] Deletion timeout".format(
-                             vca_deployed["application"]))
-                     else:
-                         db_nsr["_admin.deployed.VCA.{}".format(vca_index)] = None
              if failed_detail:
                  self.logger.error(logging_text + " ;".join(failed_detail))
                  db_nsr_update["operational-status"] = "failed"
                      self.update_db_2("nslcmops", nslcmop_id, db_nslcmop_update)
                  if db_nsr:
                      db_nsr_update["_admin.nslcmop"] = None
+                     db_nsr_update["_admin.current-operation"] = None
+                     db_nsr_update["_admin.operation-type"] = None
                      self.update_db_2("nsrs", nsr_id, db_nsr_update)
              except DbException as e:
                  self.logger.error(logging_text + "Cannot update database: {}".format(e))
                                              loop=self.loop)
                  except Exception as e:
                      self.logger.error(logging_text + "kafka_write notification Exception {}".format(e))
+             # wait for pending tasks
+             done = None
+             pending = None
+             if pending_tasks:
+                 self.logger.debug(logging_text + 'Waiting for terminate pending tasks...')
+                 done, pending = await asyncio.wait(pending_tasks, timeout=3600)
+                 if not pending:
+                     self.logger.debug(logging_text + 'All tasks finished...')
+                 else:
+                     self.logger.info(logging_text + 'There are pending tasks: {}'.format(pending))
              self.logger.debug(logging_text + "Exit")
              self.lcm_tasks.remove("ns", nsr_id, nslcmop_id, "ns_terminate")
  
                          calculated_params[param_name] = instantiation_params[calculated_params[param_name][1:-1]]
                      else:
                          raise LcmException("Parameter {} needed to execute primitive {} not provided".
-                                            format(parameter["default-value"], primitive_desc["name"]))
+                                            format(calculated_params[param_name], primitive_desc["name"]))
              else:
                  raise LcmException("Parameter {} needed to execute primitive {} not provided".
                                     format(param_name, primitive_desc["name"]))
                                                                 width=256)
              elif isinstance(calculated_params[param_name], str) and calculated_params[param_name].startswith("!!yaml "):
                  calculated_params[param_name] = calculated_params[param_name][7:]
 +
 +        # add always ns_config_info if primitive name is config
 +        if primitive_desc["name"] == "config":
 +            if "ns_config_info" in instantiation_params:
 +                calculated_params["ns_config_info"] = instantiation_params["ns_config_info"]
          return calculated_params
  
      async def _ns_execute_primitive(self, db_deployed, member_vnf_index, vdu_id, vdu_name, vdu_count_index,
-                                     primitive, primitive_params, retries=0, retries_interval=30):
-         start_primitive_time = time()
+                                     primitive, primitive_params, retries=0, retries_interval=30) -> (str, str):
+         # find vca_deployed record for this action
          try:
              for vca_deployed in db_deployed["VCA"]:
                  if not vca_deployed:
                      continue
                  break
              else:
+                 # vca_deployed not found
                  raise LcmException("charm for member_vnf_index={} vdu_id={} vdu_name={} vdu_count_index={} is not "
                                     "deployed".format(member_vnf_index, vdu_id, vdu_name, vdu_count_index))
-             model_name = vca_deployed.get("model")
-             application_name = vca_deployed.get("application")
-             if not model_name or not application_name:
+             # get ee_id
+             ee_id = vca_deployed.get("ee_id")
+             if not ee_id:
                  raise LcmException("charm for member_vnf_index={} vdu_id={} vdu_name={} vdu_count_index={} has not "
-                                    "model or application name" .format(member_vnf_index, vdu_id, vdu_name,
-                                                                        vdu_count_index))
-             # if vca_deployed["operational-status"] != "active":
-             #   raise LcmException("charm for member_vnf_index={} vdu_id={} operational_status={} not 'active'".format(
-             #   member_vnf_index, vdu_id, vca_deployed["operational-status"]))
-             callback = None  # self.n2vc_callback
-             callback_args = ()  # [db_nsr, db_nslcmop, member_vnf_index, None]
-             await self.n2vc.login()
+                                    "execution environment"
+                                    .format(member_vnf_index, vdu_id, vdu_name, vdu_count_index))
              if primitive == "config":
                  primitive_params = {"params": primitive_params}
              while retries >= 0:
-                 primitive_id = await self.n2vc.ExecutePrimitive(
-                     model_name,
-                     application_name,
-                     primitive,
-                     callback,
-                     *callback_args,
-                     **primitive_params
-                 )
-                 while time() - start_primitive_time < self.timeout_primitive:
-                     primitive_result_ = await self.n2vc.GetPrimitiveStatus(model_name, primitive_id)
-                     if primitive_result_ in ("completed", "failed"):
-                         primitive_result = "COMPLETED" if primitive_result_ == "completed" else "FAILED"
-                         detailed_result = await self.n2vc.GetPrimitiveOutput(model_name, primitive_id)
-                         break
-                     elif primitive_result_ is None and primitive == "config":
-                         primitive_result = "COMPLETED"
-                         detailed_result = None
-                         break
-                     else:  # ("running", "pending", None):
-                         pass
-                     await asyncio.sleep(5)
-                 else:
-                     raise LcmException("timeout after {} seconds".format(self.timeout_primitive))
-                 if primitive_result == "COMPLETED":
+                 try:
+                     output = await self.n2vc.exec_primitive(
+                         ee_id=ee_id,
+                         primitive_name=primitive,
+                         params_dict=primitive_params
+                     )
+                     # execution was OK
                      break
-                 retries -= 1
-                 if retries >= 0:
-                     await asyncio.sleep(retries_interval)
+                 except Exception as e:
+                     retries -= 1
+                     if retries >= 0:
+                         self.logger.debug('Error executing action {} on {} -> {}'.format(primitive, ee_id, e))
+                         # wait and retry
+                         await asyncio.sleep(retries_interval, loop=self.loop)
+                     else:
+                         return 'Cannot execute action {} on {}: {}'.format(primitive, ee_id, e), 'FAIL'
  
-             return primitive_result, detailed_result
-         except (N2VCPrimitiveExecutionFailed, LcmException) as e:
-             return "FAILED", str(e)
+             return output, 'OK'
+         except Exception as e:
+             return 'Error executing action {}: {}'.format(primitive, e), 'FAIL'
  
      async def action(self, nsr_id, nslcmop_id):
  
          # get all needed from database
          db_nsr = None
          db_nslcmop = None
-         db_nsr_update = {"_admin.nslcmop": nslcmop_id}
+         db_nsr_update = {"_admin.nslcmop": nslcmop_id,
+                          "_admin.current-operation": nslcmop_id,
+                          "_admin.operation-type": "action"}
+         self.update_db_2("nsrs", nsr_id, db_nsr_update)
          db_nslcmop_update = {}
          nslcmop_operation_state = None
          nslcmop_operation_state_detail = None
          exc = None
          try:
              # wait for any previous tasks in process
 +            step = "Waiting for previous operations to terminate"
              await self.lcm_tasks.waitfor_related_HA('ns', 'nslcmops', nslcmop_id)
  
              step = "Getting information from database"
              nsr_deployed = db_nsr["_admin"].get("deployed")
              vnf_index = db_nslcmop["operationParams"].get("member_vnf_index")
              vdu_id = db_nslcmop["operationParams"].get("vdu_id")
+             kdu_name = db_nslcmop["operationParams"].get("kdu_name")
              vdu_count_index = db_nslcmop["operationParams"].get("vdu_count_index")
              vdu_name = db_nslcmop["operationParams"].get("vdu_name")
  
                              if config_primitive["name"] == primitive:
                                  config_primitive_desc = config_primitive
                                  break
 -                                                                       kdu_instance=kdu.get("kdu-instance"),
 -                                                                       atomic=True, kdu_model=kdu_model,
 -                                                                       params=desc_params, db_dict=db_dict, timeout=300)
+             elif kdu_name:
+                 self.logger.debug(logging_text + "Checking actions in KDUs")
+                 desc_params = {}
+                 if vnf_index:
+                     if db_vnfr.get("additionalParamsForVnf") and db_vnfr["additionalParamsForVnf"].\
+                             get("member-vnf-index") == vnf_index:
+                         desc_params = self._format_additional_params(db_vnfr["additionalParamsForVnf"].
+                                                                      get("additionalParams"))
+                     if primitive_params:
+                         desc_params.update(primitive_params)
+                 # TODO Check if we will need something at vnf level
+                 index = 0
+                 for kdu in get_iterable(nsr_deployed, "K8s"):
+                     if kdu_name == kdu["kdu-name"]:
+                         db_dict = {"collection": "nsrs", "filter": {"_id": nsr_id},
+                                    "path": "_admin.deployed.K8s.{}".format(index)}
+                         if primitive == "upgrade":
+                             if desc_params.get("kdu_model"):
+                                 kdu_model = desc_params.get("kdu_model")
+                                 del desc_params["kdu_model"]
+                             else:
+                                 kdu_model = kdu.get("kdu-model")
+                                 parts = kdu_model.split(sep=":")
+                                 if len(parts) == 2:
+                                     kdu_model = parts[0]
+                             if kdu.get("k8scluster-type") == "chart":
+                                 output = await self.k8sclusterhelm.upgrade(cluster_uuid=kdu.get("k8scluster-uuid"),
++                                                                           kdu_instance=kdu.get("kdu-instance"),
++                                                                           atomic=True, kdu_model=kdu_model,
++                                                                           params=desc_params, db_dict=db_dict,
++                                                                           timeout=300)
+                             elif kdu.get("k8scluster-type") == "juju":
+                                 # TODO Juju connector needed
+                                 pass
+                             else:
+                                 msg = "k8scluster-type not defined"
+                                 raise LcmException(msg)
+                             self.logger.debug(logging_text + " Upgrade of kdu {} done".format(output))
+                             break
+                         elif primitive == "rollback":
+                             if kdu.get("k8scluster-type") == "chart":
+                                 output = await self.k8sclusterhelm.rollback(cluster_uuid=kdu.get("k8scluster-uuid"),
+                                                                             kdu_instance=kdu.get("kdu-instance"),
+                                                                             db_dict=db_dict)
+                             elif kdu.get("k8scluster-type") == "juju":
+                                 # TODO Juju connector needed
+                                 pass
+                             else:
+                                 msg = "k8scluster-type not defined"
+                                 raise LcmException(msg)
+                             break
+                         elif primitive == "status":
+                             if kdu.get("k8scluster-type") == "chart":
+                                 output = await self.k8sclusterhelm.status_kdu(cluster_uuid=kdu.get("k8scluster-uuid"),
+                                                                               kdu_instance=kdu.get("kdu-instance"))
+                             elif kdu.get("k8scluster-type") == "juju":
+                                 # TODO Juju connector needed
+                                 pass
+                             else:
+                                 msg = "k8scluster-type not defined"
+                                 raise LcmException(msg)
+                             break
+                     index += 1
+                 else:
+                     raise LcmException("KDU '{}' not found".format(kdu_name))
+                 if output:
+                     db_nslcmop_update["detailed-status"] = output
+                     db_nslcmop_update["operationState"] = 'COMPLETED'
+                     db_nslcmop_update["statusEnteredTime"] = time()
+                 else:
+                     db_nslcmop_update["detailed-status"] = ''
+                     db_nslcmop_update["operationState"] = 'FAILED'
+                     db_nslcmop_update["statusEnteredTime"] = time()
+                 return
              elif vnf_index:
                  for config_primitive in db_vnfd.get("vnf-configuration", {}).get("config-primitive", ()):
                      if config_primitive["name"] == primitive:
                  if db_vnfr.get("additionalParamsForVnf"):
                      desc_params.update(db_vnfr["additionalParamsForVnf"])
              else:
-                 if db_nsr.get("additionalParamsForVnf"):
+                 if db_nsr.get("additionalParamsForNs"):
                      desc_params.update(db_nsr["additionalParamsForNs"])
  
              # TODO check if ns is in a proper status
-             result, result_detail = await self._ns_execute_primitive(
-                 nsr_deployed, vnf_index, vdu_id, vdu_name, vdu_count_index, primitive,
-                 self._map_primitive_params(config_primitive_desc, primitive_params, desc_params))
-             db_nslcmop_update["detailed-status"] = nslcmop_operation_state_detail = result_detail
+             output, detail = await self._ns_execute_primitive(
+                 db_deployed=nsr_deployed,
+                 member_vnf_index=vnf_index,
+                 vdu_id=vdu_id,
+                 vdu_name=vdu_name,
+                 vdu_count_index=vdu_count_index,
+                 primitive=primitive,
+                 primitive_params=self._map_primitive_params(config_primitive_desc, primitive_params, desc_params))
+             detailed_status = output
+             if detail == 'OK':
+                 result = 'COMPLETED'
+             else:
+                 result = 'FAILED'
+             db_nslcmop_update["detailed-status"] = nslcmop_operation_state_detail = detailed_status
              db_nslcmop_update["operationState"] = nslcmop_operation_state = result
              db_nslcmop_update["statusEnteredTime"] = time()
-             self.logger.debug(logging_text + " task Done with result {} {}".format(result, result_detail))
+             self.logger.debug(logging_text + " task Done with result {} {}".format(result, detailed_status))
              return  # database update is called inside finally
  
          except (DbException, LcmException) as e:
                      self.update_db_2("nslcmops", nslcmop_id, db_nslcmop_update)
                  if db_nsr:
                      db_nsr_update["_admin.nslcmop"] = None
+                     db_nsr_update["_admin.operation-type"] = None
+                     db_nsr_update["_admin.nslcmop"] = None
+                     db_nsr_update["_admin.current-operation"] = None
                      self.update_db_2("nsrs", nsr_id, db_nsr_update)
              except DbException as e:
                  self.logger.error(logging_text + "Cannot update database: {}".format(e))
          db_nslcmop = None
          db_nslcmop_update = {}
          nslcmop_operation_state = None
-         db_nsr_update = {"_admin.nslcmop": nslcmop_id}
+         db_nsr_update = {"_admin.nslcmop": nslcmop_id,
+                          "_admin.current-operation": nslcmop_id,
+                          "_admin.operation-type": "scale"}
+         self.update_db_2("nsrs", nsr_id, db_nsr_update)
          exc = None
          # in case of error, indicates what part of scale was failed to put nsr at error status
          scale_process = None
          vnfr_scaled = False
          try:
              # wait for any previous tasks in process
 +            step = "Waiting for previous operations to terminate"
              await self.lcm_tasks.waitfor_related_HA('ns', 'nslcmops', nslcmop_id)
  
              step = "Getting nslcmop from database"
              db_nsr_update["operational-status"] = "scaling"
              self.update_db_2("nsrs", nsr_id, db_nsr_update)
              nsr_deployed = db_nsr["_admin"].get("deployed")
 -            vdu_id = db_nslcmop["operationParams"].get("vdu_id")
 -            vdu_count_index = db_nslcmop["operationParams"].get("vdu_count_index")
 -            vdu_name = db_nslcmop["operationParams"].get("vdu_name")
+             #######
+             nsr_deployed = db_nsr["_admin"].get("deployed")
+             vnf_index = db_nslcmop["operationParams"].get("member_vnf_index")
++            # vdu_id = db_nslcmop["operationParams"].get("vdu_id")
++            # vdu_count_index = db_nslcmop["operationParams"].get("vdu_count_index")
++            # vdu_name = db_nslcmop["operationParams"].get("vdu_name")
+             #######
              RO_nsr_id = nsr_deployed["RO"]["nsr_id"]
              vnf_index = db_nslcmop["operationParams"]["scaleVnfData"]["scaleByStepData"]["member-vnf-index"]
              scaling_group = db_nslcmop["operationParams"]["scaleVnfData"]["scaleByStepData"]["scaling-group-descriptor"]
                          vnfr_params = {"VDU_SCALE_INFO": vdu_scaling_info}
                          if db_vnfr.get("additionalParamsForVnf"):
                              vnfr_params.update(db_vnfr["additionalParamsForVnf"])
                          scale_process = "VCA"
                          db_nsr_update["config-status"] = "configuring pre-scaling"
                          primitive_params = self._map_primitive_params(config_primitive, {}, vnfr_params)
                              else:
                                  assert False, "ROclient.check_action_status returns unknown {}".format(ns_status)
                          else:
                              if ns_status == "ERROR":
                                  raise ROclient.ROClientException(ns_status_info)
                              elif ns_status == "BUILD":
                  if db_nslcmop and db_nslcmop_update:
                      self.update_db_2("nslcmops", nslcmop_id, db_nslcmop_update)
                  if db_nsr:
+                     db_nsr_update["_admin.current-operation"] = None
+                     db_nsr_update["_admin.operation-type"] = None
                      db_nsr_update["_admin.nslcmop"] = None
                      self.update_db_2("nsrs", nsr_id, db_nsr_update)
              except DbException as e:
                                                               "operationState": nslcmop_operation_state},
                                              loop=self.loop)
                      # if cooldown_time:
-                     #     await asyncio.sleep(cooldown_time)
+                     #     await asyncio.sleep(cooldown_time, loop=self.loop)
                      # await self.msg.aiowrite("ns","scaled-cooldown-time", {"nsr_id": nsr_id, "nslcmop_id": nslcmop_id})
                  except Exception as e:
                      self.logger.error(logging_text + "kafka_write notification Exception {}".format(e))
diff --combined osm_lcm/tests/test_ns.py
@@@ -29,8 -29,6 +29,8 @@@ from osm_lcm.lcm_utils import TaskRegis
  from n2vc.vnf import N2VC
  from uuid import uuid4
  
 +from osm_lcm.tests import test_db_descriptors as descriptors
 +
  __author__ = "Alfonso Tierno <alfonso.tiernosepulveda@telefonica.com>"
  
  """ Perform unittests using asynctest of osm_lcm.ns module
@@@ -66,6 -64,869 +66,6 @@@ ro_config = 
      "loglevel": "DEBUG",
  }
  
 -db_vim_accounts_text = """
 ----
 --   _admin:
 -        created: 1566818150.3024442
 -        current_operation: 0
 -        deployed:
 -            RO: dc51ce6c-c7f2-11e9-b9c0-02420aff0004
 -            RO-account: dc5c67fa-c7f2-11e9-b9c0-02420aff0004
 -        detailed-status: Done
 -        modified: 1566818150.3024442
 -        operationalState: ENABLED
 -        operations:
 -        -   detailed-status: Done
 -            lcmOperationType: create
 -            operationParams: null
 -            operationState: COMPLETED
 -            startTime: 1566818150.3025382
 -            statusEnteredTime: 1566818150.3025382
 -            worker: 86434c2948e2
 -        projects_read:
 -        - 25b5aebf-3da1-49ed-99de-1d2b4a86d6e4
 -        projects_write:
 -        - 25b5aebf-3da1-49ed-99de-1d2b4a86d6e4
 -    _id: ea958ba5-4e58-4405-bf42-6e3be15d4c3a
 -    description: Openstack site 2, based on Mirantis, also called DSS9000-1, with
 -        tenant tid
 -    name: ost2-mrt-tid
 -    schema_version: '1.1'
 -    vim_password: 5g0yGX86qIhprX86YTMcpg==
 -    vim_tenant_name: osm
 -    vim_type: openstack
 -    vim_url: http://10.95.87.162:5000/v2.0
 -    vim_user: osm
 -"""
 -
 -db_vnfds_text = """
 ----
 --   _admin:
 -        created: 1566823352.7154346
 -        modified: 1566823353.9295402
 -        onboardingState: ONBOARDED
 -        operationalState: ENABLED
 -        projects_read:
 -        - 25b5aebf-3da1-49ed-99de-1d2b4a86d6e4
 -        projects_write:
 -        - 25b5aebf-3da1-49ed-99de-1d2b4a86d6e4
 -        storage:
 -            descriptor: hackfest_3charmed_vnfd/hackfest_3charmed_vnfd.yaml
 -            folder: 7637bcf8-cf14-42dc-ad70-c66fcf1e6e77
 -            fs: local
 -            path: /app/storage/
 -            pkg-dir: hackfest_3charmed_vnfd
 -            zipfile: package.tar.gz
 -        type: vnfd
 -        usageState: NOT_IN_USE
 -        userDefinedData: {}
 -    _id: 7637bcf8-cf14-42dc-ad70-c66fcf1e6e77
 -    connection-point:
 -    -   id: vnf-mgmt
 -        name: vnf-mgmt
 -        short-name: vnf-mgmt
 -        type: VPORT
 -    -   id: vnf-data
 -        name: vnf-data
 -        short-name: vnf-data
 -        type: VPORT
 -    description: A VNF consisting of 2 VDUs connected to an internal VL, and one VDU
 -        with cloud-init
 -    id: hackfest3charmed-vnf
 -    internal-vld:
 -    -   id: internal
 -        internal-connection-point:
 -        -   id-ref: mgmtVM-internal
 -        -   id-ref: dataVM-internal
 -        name: internal
 -        short-name: internal
 -        type: ELAN
 -    logo: osm.png
 -    mgmt-interface:
 -        cp: vnf-mgmt
 -    monitoring-param:
 -    -   aggregation-type: AVERAGE
 -        id: monitor1
 -        name: monitor1
 -        vdu-monitoring-param:
 -            vdu-monitoring-param-ref: dataVM_cpu_util
 -            vdu-ref: dataVM
 -    name: hackfest3charmed-vnf
 -    scaling-group-descriptor:
 -    -   max-instance-count: 10
 -        name: scale_dataVM
 -        scaling-config-action:
 -        -   trigger: post-scale-out
 -            vnf-config-primitive-name-ref: touch
 -        -   trigger: pre-scale-in
 -            vnf-config-primitive-name-ref: touch
 -        scaling-policy:
 -        -   cooldown-time: 60
 -            name: auto_cpu_util_above_threshold
 -            scaling-criteria:
 -            -   name: cpu_util_above_threshold
 -                scale-in-relational-operation: LE
 -                scale-in-threshold: '15.0000000000'
 -                scale-out-relational-operation: GE
 -                scale-out-threshold: '60.0000000000'
 -                vnf-monitoring-param-ref: monitor1
 -            scaling-type: automatic
 -            threshold-time: 0
 -        vdu:
 -        -   count: 1
 -            vdu-id-ref: dataVM
 -    short-name: hackfest3charmed-vnf
 -    vdu:
 -    -   count: '1'
 -        cloud-init-file: cloud-config.txt
 -        id: mgmtVM
 -        image: hackfest3-mgmt
 -        interface:
 -        -   external-connection-point-ref: vnf-mgmt
 -            name: mgmtVM-eth0
 -            position: 1
 -            type: EXTERNAL
 -            virtual-interface:
 -                type: VIRTIO
 -        -   internal-connection-point-ref: mgmtVM-internal
 -            name: mgmtVM-eth1
 -            position: 2
 -            type: INTERNAL
 -            virtual-interface:
 -                type: VIRTIO
 -        internal-connection-point:
 -        -   id: mgmtVM-internal
 -            name: mgmtVM-internal
 -            short-name: mgmtVM-internal
 -            type: VPORT
 -        name: mgmtVM
 -        vm-flavor:
 -            memory-mb: '1024'
 -            storage-gb: '10'
 -            vcpu-count: 1
 -    -   count: '1'
 -        id: dataVM
 -        image: hackfest3-mgmt
 -        interface:
 -        -   internal-connection-point-ref: dataVM-internal
 -            name: dataVM-eth0
 -            position: 1
 -            type: INTERNAL
 -            virtual-interface:
 -                type: VIRTIO
 -        -   external-connection-point-ref: vnf-data
 -            name: dataVM-xe0
 -            position: 2
 -            type: EXTERNAL
 -            virtual-interface:
 -                type: VIRTIO
 -        internal-connection-point:
 -        -   id: dataVM-internal
 -            name: dataVM-internal
 -            short-name: dataVM-internal
 -            type: VPORT
 -        monitoring-param:
 -        -   id: dataVM_cpu_util
 -            nfvi-metric: cpu_utilization
 -        name: dataVM
 -        vm-flavor:
 -            memory-mb: '1024'
 -            storage-gb: '10'
 -            vcpu-count: 1
 -    version: '1.0'
 -    vnf-configuration:
 -        config-access:
 -            ssh-access:
 -                required: True
 -                default-user: ubuntu
 -        config-primitive:
 -        -   name: touch
 -            parameter:
 -            -   data-type: STRING
 -                default-value: <touch_filename2>
 -                name: filename
 -        initial-config-primitive:
 -        -   name: config
 -            parameter:
 -            -   name: ssh-hostname
 -                value: <rw_mgmt_ip>
 -            -   name: ssh-username
 -                value: ubuntu
 -            -   name: ssh-password
 -                value: osm4u
 -            seq: '1'
 -        -   name: touch
 -            parameter:
 -            -   name: filename
 -                value: <touch_filename>
 -            seq: '2'
 -        juju:
 -            charm: simple
 -"""
 -
 -db_nsds_text = """
 ----
 --   _admin:
 -        created: 1566823353.971486
 -        modified: 1566823353.971486
 -        onboardingState: ONBOARDED
 -        operationalState: ENABLED
 -        projects_read:
 -        - 25b5aebf-3da1-49ed-99de-1d2b4a86d6e4
 -        projects_write:
 -        - 25b5aebf-3da1-49ed-99de-1d2b4a86d6e4
 -        storage:
 -            descriptor: hackfest_3charmed_nsd/hackfest_3charmed_nsd.yaml
 -            folder: 8c2f8b95-bb1b-47ee-8001-36dc090678da
 -            fs: local
 -            path: /app/storage/
 -            pkg-dir: hackfest_3charmed_nsd
 -            zipfile: package.tar.gz
 -        usageState: NOT_IN_USE
 -        userDefinedData: {}
 -    _id: 8c2f8b95-bb1b-47ee-8001-36dc090678da
 -    constituent-vnfd:
 -    -   member-vnf-index: '1'
 -        vnfd-id-ref: hackfest3charmed-vnf
 -    -   member-vnf-index: '2'
 -        vnfd-id-ref: hackfest3charmed-vnf
 -    description: NS with 2 VNFs hackfest3charmed-vnf connected by datanet and mgmtnet
 -        VLs
 -    id: hackfest3charmed-ns
 -    logo: osm.png
 -    name: hackfest3charmed-ns
 -    short-name: hackfest3charmed-ns
 -    version: '1.0'
 -    vld:
 -    -   id: mgmt
 -        mgmt-network: true
 -        name: mgmt
 -        short-name: mgmt
 -        type: ELAN
 -        vim-network-name: mgmt
 -        vnfd-connection-point-ref:
 -        -   member-vnf-index-ref: '1'
 -            vnfd-connection-point-ref: vnf-mgmt
 -            vnfd-id-ref: hackfest3charmed-vnf
 -        -   member-vnf-index-ref: '2'
 -            vnfd-connection-point-ref: vnf-mgmt
 -            vnfd-id-ref: hackfest3charmed-vnf
 -    -   id: datanet
 -        name: datanet
 -        short-name: datanet
 -        type: ELAN
 -        vnfd-connection-point-ref:
 -        -   member-vnf-index-ref: '1'
 -            vnfd-connection-point-ref: vnf-data
 -            vnfd-id-ref: hackfest3charmed-vnf
 -        -   member-vnf-index-ref: '2'
 -            vnfd-connection-point-ref: vnf-data
 -            vnfd-id-ref: hackfest3charmed-vnf
 -"""
 -
 -db_nsrs_text = """
 ----
 --   _admin:
 -        created: 1566823354.3716335
 -        deployed:
 -            RO:
 -                nsd_id: 876573b5-968d-40b9-b52b-91bf5c5844f7
 -                nsr_id: c9fe9908-3180-430d-b633-fca2f68db008
 -                nsr_status: ACTIVE
 -                vnfd:
 -                -   id: 1ab2a418-9fe3-4358-bf17-411e5155535f
 -                    member-vnf-index: '1'
 -                -   id: 0de348e3-c201-4f6a-91cc-7f957e2d5504
 -                    member-vnf-index: '2'
 -            VCA:
 -            -   application: alf-b-aa
 -                detailed-status: Ready!
 -                member-vnf-index: '1'
 -                model: f48163a6-c807-47bc-9682-f72caef5af85
 -                operational-status: active
 -                primitive_id: null
 -                ssh-public-key: ssh-rsa pub-key root@juju-145d3e-0
 -                step: ssh-public-key-obtained
 -                vdu_count_index: null
 -                vdu_id: null
 -                vdu_name: null
 -                vnfd_id: hackfest3charmed-vnf
 -            -   application: alf-c-ab
 -                detailed-status: Ready!
 -                member-vnf-index: '2'
 -                model: f48163a6-c807-47bc-9682-f72caef5af85
 -                operational-status: active
 -                primitive_id: null
 -                ssh-public-key: ssh-rsa pub-key root@juju-145d3e-0
 -                step: ssh-public-key-obtained
 -                vdu_count_index: null
 -                vdu_id: null
 -                vdu_name: null
 -                vnfd_id: hackfest3charmed-vnf
 -            VCA-model-name: f48163a6-c807-47bc-9682-f72caef5af85
 -        modified: 1566823354.3716335
 -        nsState: INSTANTIATED
 -        nslcmop: null
 -        projects_read:
 -        - 25b5aebf-3da1-49ed-99de-1d2b4a86d6e4
 -        projects_write:
 -        - 25b5aebf-3da1-49ed-99de-1d2b4a86d6e4
 -    _id: f48163a6-c807-47bc-9682-f72caef5af85
 -    additionalParamsForNs: null
 -    admin-status: ENABLED
 -    config-status: init
 -    constituent-vnfr-ref:
 -    - 88d90b0c-faff-4b9f-bccd-017f33985984
 -    - 1ca3bb1a-b29b-49fe-bed6-5f3076d77434
 -    create-time: 1566823354.36234
 -    datacenter: ea958ba5-4e58-4405-bf42-6e3be15d4c3a
 -    description: default description
 -    detailed-status: 'ERROR executing proxy charm initial primitives for member_vnf_index=1
 -        vdu_id=None: charm error executing primitive verify-ssh-credentials for member_vnf_index=1
 -        vdu_id=None: ''timeout after 600 seconds'''
 -    id: f48163a6-c807-47bc-9682-f72caef5af85
 -    instantiate_params:
 -        nsDescription: default description
 -        nsName: ALF
 -        nsdId: 8c2f8b95-bb1b-47ee-8001-36dc090678da
 -        vimAccountId: ea958ba5-4e58-4405-bf42-6e3be15d4c3a
 -    name: ALF
 -    name-ref: ALF
 -    ns-instance-config-ref: f48163a6-c807-47bc-9682-f72caef5af85
 -    nsd:
 -        _admin:
 -            created: 1566823353.971486
 -            modified: 1566823353.971486
 -            onboardingState: ONBOARDED
 -            operationalState: ENABLED
 -            projects_read:
 -            - 25b5aebf-3da1-49ed-99de-1d2b4a86d6e4
 -            projects_write:
 -            - 25b5aebf-3da1-49ed-99de-1d2b4a86d6e4
 -            storage:
 -                descriptor: hackfest_3charmed_nsd/hackfest_3charmed_nsd.yaml
 -                folder: 8c2f8b95-bb1b-47ee-8001-36dc090678da
 -                fs: local
 -                path: /app/storage/
 -                pkg-dir: hackfest_3charmed_nsd
 -                zipfile: package.tar.gz
 -            usageState: NOT_IN_USE
 -            userDefinedData: {}
 -        _id: 8c2f8b95-bb1b-47ee-8001-36dc090678da
 -        constituent-vnfd:
 -        -   member-vnf-index: '1'
 -            vnfd-id-ref: hackfest3charmed-vnf
 -        -   member-vnf-index: '2'
 -            vnfd-id-ref: hackfest3charmed-vnf
 -        description: NS with 2 VNFs hackfest3charmed-vnf connected by datanet and
 -            mgmtnet VLs
 -        id: hackfest3charmed-ns
 -        logo: osm.png
 -        name: hackfest3charmed-ns
 -        short-name: hackfest3charmed-ns
 -        version: '1.0'
 -        vld:
 -        -   id: mgmt
 -            mgmt-network: true
 -            name: mgmt
 -            short-name: mgmt
 -            type: ELAN
 -            vim-network-name: mgmt
 -            vnfd-connection-point-ref:
 -            -   member-vnf-index-ref: '1'
 -                vnfd-connection-point-ref: vnf-mgmt
 -                vnfd-id-ref: hackfest3charmed-vnf
 -            -   member-vnf-index-ref: '2'
 -                vnfd-connection-point-ref: vnf-mgmt
 -                vnfd-id-ref: hackfest3charmed-vnf
 -        -   id: datanet
 -            name: datanet
 -            short-name: datanet
 -            type: ELAN
 -            vnfd-connection-point-ref:
 -            -   member-vnf-index-ref: '1'
 -                vnfd-connection-point-ref: vnf-data
 -                vnfd-id-ref: hackfest3charmed-vnf
 -            -   member-vnf-index-ref: '2'
 -                vnfd-connection-point-ref: vnf-data
 -                vnfd-id-ref: hackfest3charmed-vnf
 -    nsd-id: 8c2f8b95-bb1b-47ee-8001-36dc090678da
 -    nsd-name-ref: hackfest3charmed-ns
 -    nsd-ref: hackfest3charmed-ns
 -    operational-events: []
 -    operational-status: failed
 -    orchestration-progress: {}
 -    resource-orchestrator: osmopenmano
 -    short-name: ALF
 -    ssh-authorized-key: null
 -    vld:
 -    -   id: mgmt
 -        name: null
 -        status: ACTIVE
 -        status-detailed: null
 -        vim-id: f99ae780-0e2f-4985-af41-574eae6919c0
 -        vim-network-name: mgmt
 -    -   id: datanet
 -        name: ALF-datanet
 -        status: ACTIVE
 -        status-detailed: null
 -        vim-id: c31364ba-f573-4ab6-bf1a-fed30ede39a8
 -    vnfd-id:
 -    - 7637bcf8-cf14-42dc-ad70-c66fcf1e6e77
 -"""
 -
 -db_nslcmops_text = """
 ----
 --   _admin:
 -        created: 1566823354.4148262
 -        modified: 1566823354.4148262
 -        projects_read:
 -        - 25b5aebf-3da1-49ed-99de-1d2b4a86d6e4
 -        projects_write:
 -        - 25b5aebf-3da1-49ed-99de-1d2b4a86d6e4
 -        worker: 86434c2948e2
 -    _id: a639fac7-e0bb-4225-8ecb-c1f8efcc125e
 -    detailed-status: 'FAILED executing proxy charm initial primitives for member_vnf_index=1
 -        vdu_id=None: charm error executing primitive verify-ssh-credentials for member_vnf_index=1
 -        vdu_id=None: ''timeout after 600 seconds'''
 -    id: a639fac7-e0bb-4225-8ecb-c1f8efcc125e
 -    isAutomaticInvocation: false
 -    isCancelPending: false
 -    lcmOperationType: instantiate
 -    links:
 -        nsInstance: /osm/nslcm/v1/ns_instances/f48163a6-c807-47bc-9682-f72caef5af85
 -        self: /osm/nslcm/v1/ns_lcm_op_occs/a639fac7-e0bb-4225-8ecb-c1f8efcc125e
 -    nsInstanceId: f48163a6-c807-47bc-9682-f72caef5af85
 -    operationParams:
 -        additionalParamsForVnf:
 -        -   additionalParams:
 -                touch_filename: /home/ubuntu/first-touch-1
 -                touch_filename2: /home/ubuntu/second-touch-1
 -            member-vnf-index: '1'
 -        -   additionalParams:
 -                touch_filename: /home/ubuntu/first-touch-2
 -                touch_filename2: /home/ubuntu/second-touch-2
 -            member-vnf-index: '2'
 -        lcmOperationType: instantiate
 -        nsDescription: default description
 -        nsInstanceId: f48163a6-c807-47bc-9682-f72caef5af85
 -        nsName: ALF
 -        nsdId: 8c2f8b95-bb1b-47ee-8001-36dc090678da
 -        vimAccountId: ea958ba5-4e58-4405-bf42-6e3be15d4c3a
 -    operationState: FAILED
 -    startTime: 1566823354.414689
 -    statusEnteredTime: 1566824534.5112448
 -"""
 -
 -db_vnfrs_text = """
 ----
 --   _admin:
 -        created: 1566823354.3668208
 -        modified: 1566823354.3668208
 -        nsState: NOT_INSTANTIATED
 -        projects_read:
 -        - 25b5aebf-3da1-49ed-99de-1d2b4a86d6e4
 -        projects_write:
 -        - 25b5aebf-3da1-49ed-99de-1d2b4a86d6e4
 -    _id: 88d90b0c-faff-4b9f-bccd-017f33985984
 -    additionalParamsForVnf:
 -        touch_filename: /home/ubuntu/first-touch-1
 -        touch_filename2: /home/ubuntu/second-touch-1
 -    connection-point:
 -    -   connection-point-id: vnf-mgmt
 -        id: vnf-mgmt
 -        name: vnf-mgmt
 -    -   connection-point-id: vnf-data
 -        id: vnf-data
 -        name: vnf-data
 -    created-time: 1566823354.36234
 -    id: 88d90b0c-faff-4b9f-bccd-017f33985984
 -    ip-address: 10.205.1.46
 -    member-vnf-index-ref: '1'
 -    nsr-id-ref: f48163a6-c807-47bc-9682-f72caef5af85
 -    vdur:
 -    -   _id: f0e7d7ce-2443-4dcb-ad0b-5ab9f3b13d37
 -        count-index: 0
 -        interfaces:
 -        -   ip-address: 10.205.1.46
 -            mac-address: fa:16:3e:b4:3e:b1
 -            mgmt-vnf: true
 -            name: mgmtVM-eth0
 -            ns-vld-id: mgmt
 -        -   ip-address: 192.168.54.2
 -            mac-address: fa:16:3e:6e:7e:78
 -            name: mgmtVM-eth1
 -            vnf-vld-id: internal
 -        internal-connection-point:
 -        -   connection-point-id: mgmtVM-internal
 -            id: mgmtVM-internal
 -            name: mgmtVM-internal
 -        ip-address: 10.205.1.46
 -        name: ALF-1-mgmtVM-1
 -        status: ACTIVE
 -        status-detailed: null
 -        vdu-id-ref: mgmtVM
 -        vim-id: c2538499-4c30-41c0-acd5-80cb92f48061
 -    -   _id: ab453219-2d9a-45c2-864d-2c0788385028
 -        count-index: 0
 -        interfaces:
 -        -   ip-address: 192.168.54.3
 -            mac-address: fa:16:3e:d9:7a:5d
 -            name: dataVM-eth0
 -            vnf-vld-id: internal
 -        -   ip-address: 192.168.24.3
 -            mac-address: fa:16:3e:d1:6c:0d
 -            name: dataVM-xe0
 -            ns-vld-id: datanet
 -        internal-connection-point:
 -        -   connection-point-id: dataVM-internal
 -            id: dataVM-internal
 -            name: dataVM-internal
 -        ip-address: null
 -        name: ALF-1-dataVM-1
 -        status: ACTIVE
 -        status-detailed: null
 -        vdu-id-ref: dataVM
 -        vim-id: 87973c3f-365d-4227-95c2-7a8abc74349c
 -    vim-account-id: ea958ba5-4e58-4405-bf42-6e3be15d4c3a
 -    vld:
 -    -   id: internal
 -        name: ALF-internal
 -        status: ACTIVE
 -        status-detailed: null
 -        vim-id: ff181e6d-2597-4244-b40b-bb0174bdfeb6
 -    vnfd-id: 7637bcf8-cf14-42dc-ad70-c66fcf1e6e77
 -    vnfd-ref: hackfest3charmed-vnf
 --   _admin:
 -        created: 1566823354.3703845
 -        modified: 1566823354.3703845
 -        nsState: NOT_INSTANTIATED
 -        projects_read:
 -        - 25b5aebf-3da1-49ed-99de-1d2b4a86d6e4
 -        projects_write:
 -        - 25b5aebf-3da1-49ed-99de-1d2b4a86d6e4
 -    _id: 1ca3bb1a-b29b-49fe-bed6-5f3076d77434
 -    additionalParamsForVnf:
 -        touch_filename: /home/ubuntu/first-touch-2
 -        touch_filename2: /home/ubuntu/second-touch-2
 -    connection-point:
 -    -   connection-point-id: vnf-mgmt
 -        id: vnf-mgmt
 -        name: vnf-mgmt
 -    -   connection-point-id: vnf-data
 -        id: vnf-data
 -        name: vnf-data
 -    created-time: 1566823354.36234
 -    id: 1ca3bb1a-b29b-49fe-bed6-5f3076d77434
 -    ip-address: 10.205.1.47
 -    member-vnf-index-ref: '2'
 -    nsr-id-ref: f48163a6-c807-47bc-9682-f72caef5af85
 -    vdur:
 -    -   _id: 190b4a2c-4f85-4cfe-9406-4cef7ffb1e67
 -        count-index: 0
 -        interfaces:
 -        -   ip-address: 10.205.1.47
 -            mac-address: fa:16:3e:cb:9f:c7
 -            mgmt-vnf: true
 -            name: mgmtVM-eth0
 -            ns-vld-id: mgmt
 -        -   ip-address: 192.168.231.1
 -            mac-address: fa:16:3e:1a:89:24
 -            name: mgmtVM-eth1
 -            vnf-vld-id: internal
 -        internal-connection-point:
 -        -   connection-point-id: mgmtVM-internal
 -            id: mgmtVM-internal
 -            name: mgmtVM-internal
 -        ip-address: 10.205.1.47
 -        name: ALF-2-mgmtVM-1
 -        status: ACTIVE
 -        status-detailed: null
 -        vdu-id-ref: mgmtVM
 -        vim-id: 248077b2-e3b8-4a37-8b72-575abb8ed912
 -    -   _id: 889b874d-e1c3-4e75-aa45-53a9b0ddabd9
 -        count-index: 0
 -        interfaces:
 -        -   ip-address: 192.168.231.3
 -            mac-address: fa:16:3e:7e:ba:8c
 -            name: dataVM-eth0
 -            vnf-vld-id: internal
 -        -   ip-address: 192.168.24.4
 -            mac-address: fa:16:3e:d2:e1:f5
 -            name: dataVM-xe0
 -            ns-vld-id: datanet
 -        internal-connection-point:
 -        -   connection-point-id: dataVM-internal
 -            id: dataVM-internal
 -            name: dataVM-internal
 -        ip-address: null
 -        name: ALF-2-dataVM-1
 -        status: ACTIVE
 -        status-detailed: null
 -        vdu-id-ref: dataVM
 -        vim-id: a4ce4372-e0ad-4ae3-8f9f-1c969f32e77b
 -    vim-account-id: ea958ba5-4e58-4405-bf42-6e3be15d4c3a
 -    vld:
 -    -   id: internal
 -        name: ALF-internal
 -        status: ACTIVE
 -        status-detailed: null
 -        vim-id: ff181e6d-2597-4244-b40b-bb0174bdfeb6
 -    vnfd-id: 7637bcf8-cf14-42dc-ad70-c66fcf1e6e77
 -    vnfd-ref: hackfest3charmed-vnf
 -"""
 -
 -ro_ns_text = """
 -datacenter_tenant_id: dc5c67fa-c7f2-11e9-b9c0-02420aff0004
 -description: null
 -name: ALF
 -nets:
 --   created: false
 -    datacenter_id: dc51ce6c-c7f2-11e9-b9c0-02420aff0004
 -    datacenter_tenant_id: dc5c67fa-c7f2-11e9-b9c0-02420aff0004
 -    error_msg: null
 -    ns_net_osm_id: mgmt
 -    related: c6bac394-fa27-4c43-bb34-42f621a9d343
 -    sce_net_id: 8f215bab-c35e-41e6-a035-42bfaa07af9f
 -    sdn_net_id: null
 -    status: ACTIVE
 -    uuid: c6bac394-fa27-4c43-bb34-42f621a9d343
 -    vim_info: "{vim_info: null}"
 -    vim_name: null
 -    vim_net_id: f99ae780-0e2f-4985-af41-574eae6919c0
 -    vnf_net_id: null
 -    vnf_net_osm_id: null
 --   created: true
 -    datacenter_id: dc51ce6c-c7f2-11e9-b9c0-02420aff0004
 -    datacenter_tenant_id: dc5c67fa-c7f2-11e9-b9c0-02420aff0004
 -    error_msg: null
 -    ns_net_osm_id: datanet
 -    related: 509d576c-120f-493a-99a1-5fea99dfe041
 -    sce_net_id: 3d766bbc-33a8-41aa-a986-2f35e8d25c16
 -    sdn_net_id: null
 -    status: ACTIVE
 -    uuid: 509d576c-120f-493a-99a1-5fea99dfe041
 -    vim_info: "{vim_info: null}"
 -    vim_name: ALF-datanet
 -    vim_net_id: c31364ba-f573-4ab6-bf1a-fed30ede39a8
 -    vnf_net_id: null
 -    vnf_net_osm_id: null
 --   created: true
 -    datacenter_id: dc51ce6c-c7f2-11e9-b9c0-02420aff0004
 -    datacenter_tenant_id: dc5c67fa-c7f2-11e9-b9c0-02420aff0004
 -    error_msg: null
 -    ns_net_osm_id: null
 -    related: 277fed09-3220-4bfd-9052-b96b21a32daf
 -    sce_net_id: null
 -    sdn_net_id: null
 -    status: ACTIVE
 -    uuid: 277fed09-3220-4bfd-9052-b96b21a32daf
 -    vim_info: "{vim_info: null}"
 -    vim_name: ALF-internal
 -    vim_net_id: ff181e6d-2597-4244-b40b-bb0174bdfeb6
 -    vnf_net_id: 62e62fae-c12b-4ebc-9a9b-30031c6c16fa
 -    vnf_net_osm_id: internal
 --   created: true
 -    datacenter_id: dc51ce6c-c7f2-11e9-b9c0-02420aff0004
 -    datacenter_tenant_id: dc5c67fa-c7f2-11e9-b9c0-02420aff0004
 -    error_msg: null
 -    ns_net_osm_id: null
 -    related: 92534d1a-e697-4372-a84d-aa0aa643b68a
 -    sce_net_id: null
 -    sdn_net_id: null
 -    status: ACTIVE
 -    uuid: 92534d1a-e697-4372-a84d-aa0aa643b68a
 -    vim_info: "{vim_info: null}"
 -    vim_name: ALF-internal
 -    vim_net_id: 09655387-b639-421a-b5f6-72b26d685fb4
 -    vnf_net_id: 13c6c77d-86a5-4914-832c-990d4ec7b54e
 -    vnf_net_osm_id: internal
 -nsd_osm_id: f48163a6-c807-47bc-9682-f72caef5af85.2.hackfest3charmed-ns
 -scenario_id: 876573b5-968d-40b9-b52b-91bf5c5844f7
 -scenario_name: hackfest3charmed-ns
 -sfis: []
 -sfps: []
 -sfs: []
 -tenant_id: 0ea38bd0-2729-47a9-ae07-c6ce76115eb2
 -uuid: c9fe9908-3180-430d-b633-fca2f68db008
 -vnfs:
 --   datacenter_id: dc51ce6c-c7f2-11e9-b9c0-02420aff0004
 -    datacenter_tenant_id: dc5c67fa-c7f2-11e9-b9c0-02420aff0004
 -    ip_address: 10.205.1.46
 -    member_vnf_index: '1'
 -    mgmt_access: '{interface_id: 61549ee3-cd6c-4930-8b90-eaad97fe345b, required: ''False'',
 -        vm_id: 6cf4a48f-3b6c-4395-8221-119fa37de24a}
 -
 -        '
 -    sce_vnf_id: 83be04a8-c513-42ba-9908-22728f686d31
 -    uuid: 94724042-7576-4fb0-82ec-6a7ab642741c
 -    vms:
 -    -   created_at: '2019-08-26T12:50:38'
 -        error_msg: null
 -        interfaces:
 -        -   external_name: vnf-mgmt
 -            instance_net_id: c6bac394-fa27-4c43-bb34-42f621a9d343
 -            internal_name: mgmtVM-eth0
 -            ip_address: 10.205.1.46
 -            mac_address: fa:16:3e:b4:3e:b1
 -            sdn_port_id: null
 -            type: mgmt
 -            vim_info: "{vim_info: null}"
 -            vim_interface_id: 4d3cb8fd-7040-4169-a0ad-2486d2b006a1
 -        -   external_name: null
 -            instance_net_id: 277fed09-3220-4bfd-9052-b96b21a32daf
 -            internal_name: mgmtVM-eth1
 -            ip_address: 192.168.54.2
 -            mac_address: fa:16:3e:6e:7e:78
 -            sdn_port_id: null
 -            type: bridge
 -            vim_info: "{vim_info: null}"
 -            vim_interface_id: 54ed68e2-9802-4dfe-b68a-280b3fc6e02d
 -        ip_address: 10.205.1.46
 -        name: mgmtVM
 -        related: d0b91293-a91d-4f08-b15f-0bf841216dfe
 -        status: ACTIVE
 -        uuid: d0b91293-a91d-4f08-b15f-0bf841216dfe
 -        vdu_osm_id: mgmtVM
 -        vim_info: "{vim_info: null}"
 -        vim_name: ALF-1-mgmtVM-1
 -        vim_vm_id: c2538499-4c30-41c0-acd5-80cb92f48061
 -    -   created_at: '2019-08-26T12:50:38'
 -        error_msg: null
 -        interfaces:
 -        -   external_name: null
 -            instance_net_id: 277fed09-3220-4bfd-9052-b96b21a32daf
 -            internal_name: dataVM-eth0
 -            ip_address: 192.168.54.3
 -            mac_address: fa:16:3e:d9:7a:5d
 -            sdn_port_id: null
 -            type: bridge
 -            vim_info: "{vim_info: null}"
 -            vim_interface_id: 1637f350-8840-4241-8ed0-4616bdcecfcf
 -        -   external_name: vnf-data
 -            instance_net_id: 509d576c-120f-493a-99a1-5fea99dfe041
 -            internal_name: dataVM-xe0
 -            ip_address: 192.168.24.3
 -            mac_address: fa:16:3e:d1:6c:0d
 -            sdn_port_id: null
 -            type: bridge
 -            vim_info: "{vim_info: null}"
 -            vim_interface_id: 54c73e83-7059-41fe-83a9-4c4ae997b481
 -        name: dataVM
 -        related: 5c08253d-8a35-474f-b0d3-c5297d174c13
 -        status: ACTIVE
 -        uuid: 5c08253d-8a35-474f-b0d3-c5297d174c13
 -        vdu_osm_id: dataVM
 -        vim_info: "{vim_info: null}"
 -        vim_name: ALF-1-dataVM-1
 -        vim_vm_id: 87973c3f-365d-4227-95c2-7a8abc74349c
 -    -   created_at: '2019-08-26T13:40:54'
 -        error_msg: null
 -        interfaces:
 -        -   external_name: null
 -            instance_net_id: 277fed09-3220-4bfd-9052-b96b21a32daf
 -            internal_name: dataVM-eth0
 -            ip_address: 192.168.54.5
 -            mac_address: fa:16:3e:e4:17:45
 -            sdn_port_id: null
 -            type: bridge
 -            vim_info: "{vim_info: null}"
 -            vim_interface_id: 7e246e40-8710-4c33-9c95-78fc3c02bc5b
 -        -   external_name: vnf-data
 -            instance_net_id: 509d576c-120f-493a-99a1-5fea99dfe041
 -            internal_name: dataVM-xe0
 -            ip_address: 192.168.24.5
 -            mac_address: fa:16:3e:29:6f:a6
 -            sdn_port_id: null
 -            type: bridge
 -            vim_info: "{vim_info: null}"
 -            vim_interface_id: ce81af7a-9adf-494b-950e-6581fd04ecc4
 -        name: dataVM
 -        related: 1ae5a0a2-c15a-49a4-a77c-2991d97f6dbe
 -        status: ACTIVE
 -        uuid: 1ae5a0a2-c15a-49a4-a77c-2991d97f6dbe
 -        vdu_osm_id: dataVM
 -        vim_info: "{vim_info: null}"
 -        vim_name: ALF-1-dataVM-2
 -        vim_vm_id: 4916533e-36c6-4861-9fe3-366a8fb0a5f8
 -    vnf_id: 1ab2a418-9fe3-4358-bf17-411e5155535f
 -    vnf_name: hackfest3charmed-vnf.1
 -    vnfd_osm_id: f48163a6-c807-47bc-9682-f72caef5af85.0.1
 --   datacenter_id: dc51ce6c-c7f2-11e9-b9c0-02420aff0004
 -    datacenter_tenant_id: dc5c67fa-c7f2-11e9-b9c0-02420aff0004
 -    ip_address: 10.205.1.47
 -    member_vnf_index: '2'
 -    mgmt_access: '{interface_id: 538604c3-5c5e-41eb-8f84-c0239c7fabcd, required: ''False'',
 -        vm_id: dd04d792-05c9-4ecc-bf28-f77384d00311}
 -
 -        '
 -    sce_vnf_id: c4f3607a-08ff-4f75-893c-fce507e2f240
 -    uuid: 00020403-e80f-4ef2-bb7e-b29669643035
 -    vms:
 -    -   created_at: '2019-08-26T12:50:38'
 -        error_msg: null
 -        interfaces:
 -        -   external_name: vnf-mgmt
 -            instance_net_id: c6bac394-fa27-4c43-bb34-42f621a9d343
 -            internal_name: mgmtVM-eth0
 -            ip_address: 10.205.1.47
 -            mac_address: fa:16:3e:cb:9f:c7
 -            sdn_port_id: null
 -            type: mgmt
 -            vim_info: "{vim_info: null}"
 -            vim_interface_id: dcd6d2de-3c68-481c-883e-e9d38c671dc4
 -        -   external_name: null
 -            instance_net_id: 92534d1a-e697-4372-a84d-aa0aa643b68a
 -            internal_name: mgmtVM-eth1
 -            ip_address: 192.168.231.1
 -            mac_address: fa:16:3e:1a:89:24
 -            sdn_port_id: null
 -            type: bridge
 -            vim_info: "{vim_info: null}"
 -            vim_interface_id: 50e538e3-aba0-4652-93bb-20487f3f28e1
 -        ip_address: 10.205.1.47
 -        name: mgmtVM
 -        related: 4543ab5d-578c-427c-9df2-affd17e21b66
 -        status: ACTIVE
 -        uuid: 4543ab5d-578c-427c-9df2-affd17e21b66
 -        vdu_osm_id: mgmtVM
 -        vim_info: "{vim_info: null}"
 -        vim_name: ALF-2-mgmtVM-1
 -        vim_vm_id: 248077b2-e3b8-4a37-8b72-575abb8ed912
 -    -   created_at: '2019-08-26T12:50:38'
 -        error_msg: null
 -        interfaces:
 -        -   external_name: null
 -            instance_net_id: 92534d1a-e697-4372-a84d-aa0aa643b68a
 -            internal_name: dataVM-eth0
 -            ip_address: 192.168.231.3
 -            mac_address: fa:16:3e:7e:ba:8c
 -            sdn_port_id: null
 -            type: bridge
 -            vim_info: "{vim_info: null}"
 -            vim_interface_id: 15274862-14ea-4527-b405-101cae8bc1a0
 -        -   external_name: vnf-data
 -            instance_net_id: 509d576c-120f-493a-99a1-5fea99dfe041
 -            internal_name: dataVM-xe0
 -            ip_address: 192.168.24.4
 -            mac_address: fa:16:3e:d2:e1:f5
 -            sdn_port_id: null
 -            type: bridge
 -            vim_info: "{vim_info: null}"
 -            vim_interface_id: 253ebe4e-38d5-46be-8777-dbb57510a2ec
 -        name: dataVM
 -        related: 6f03f16b-295a-47a1-9a69-2d069d574a33
 -        status: ACTIVE
 -        uuid: 6f03f16b-295a-47a1-9a69-2d069d574a33
 -        vdu_osm_id: dataVM
 -        vim_info: "{vim_info: null}"
 -        vim_name: ALF-2-dataVM-1
 -        vim_vm_id: a4ce4372-e0ad-4ae3-8f9f-1c969f32e77b
 -    vnf_id: 0de348e3-c201-4f6a-91cc-7f957e2d5504
 -    vnf_name: hackfest3charmed-vnf.2
 -    vnfd_osm_id: f48163a6-c807-47bc-9682-f72caef5af85.1.2
 -"""
 -
  
  class TestMyNS(asynctest.TestCase):
  
              yield "app_name-{}".format(num_calls)
              num_calls += 1
  
-     def _n2vc_CreateExecutionEnvironment(self, namespace):
+     def _n2vc_CreateExecutionEnvironment(self, namespace, reuse_ee_id, db_dict):
          k_list = namespace.split(".")
          ee_id = k_list[1] + "."
          if len(k_list) >= 2:
                  ee_id += k[:8]
          else:
              ee_id += "_NS_"
-         return ee_id
+         return ee_id, {}
  
      def _ro_show(self, *args, **kwargs):
 -        ro_ns_desc = yaml.load(ro_ns_text)
 +        ro_ns_desc = yaml.load(descriptors.db_ro_ns_text, Loader=yaml.Loader)
  
          # if ip address provided, replace descriptor
          ip_addresses = getenv("OSMLCMTEST_NS_IPADDRESS", "")
              self.db.get_list.side_effect = self._db_get_list
              self.db.set_one.side_effect = self._db_set_one
              self.db_content = {
 -                "nsrs": yaml.load(db_nsrs_text),
 -                "nslcmops": yaml.load(db_nslcmops_text),
 -                "vnfrs": yaml.load(db_vnfrs_text),
 -                "vnfds": yaml.load(db_vnfds_text),
 -                "vim_accounts": yaml.load(db_vim_accounts_text),
 +                "nsrs": yaml.load(descriptors.db_nsrs_text, Loader=yaml.Loader),
 +                "nslcmops": yaml.load(descriptors.db_nslcmops_text, Loader=yaml.Loader),
 +                "vnfrs": yaml.load(descriptors.db_vnfrs_text, Loader=yaml.Loader),
 +                "vnfds": yaml.load(descriptors.db_vnfds_text, Loader=yaml.Loader),
 +                "vim_accounts": yaml.load(descriptors.db_vim_accounts_text, Loader=yaml.Loader),
              }
 -            self.db_vim_accounts = yaml.load(db_vim_accounts_text)
 +            self.db_vim_accounts = yaml.load(descriptors.db_vim_accounts_text, Loader=yaml.Loader)
  
          # Mock kafka
          self.msg = asynctest.Mock(MsgKafka())
              # allow several versions of n2vc
              self.my_ns.n2vc.FormatApplicationName = asynctest.Mock(side_effect=self._n2vc_FormatApplicationName())
              self.my_ns.n2vc.DeployCharms = asynctest.CoroutineMock(side_effect=self._n2vc_DeployCharms)
-             self.my_ns.n2vc.CreateExecutionEnvironment = asynctest.CoroutineMock(
+             self.my_ns.n2vc.create_execution_environment = asynctest.CoroutineMock(
                  side_effect=self._n2vc_CreateExecutionEnvironment)
-             self.my_ns.n2vc.InstallConfigurationSW = asynctest.CoroutineMock(return_value=pub_key)
-             self.my_ns.n2vc.ExecutePrimitive = asynctest.CoroutineMock(side_effect=self._return_uuid)
+             self.my_ns.n2vc.install_configuration_sw = asynctest.CoroutineMock(return_value=pub_key)
+             self.my_ns.n2vc.get_ee_ssh_public__key = asynctest.CoroutineMock(return_value=pub_key)
+             self.my_ns.n2vc.exec_primitive = asynctest.CoroutineMock(side_effect=self._return_uuid)
              self.my_ns.n2vc.GetPrimitiveStatus = asynctest.CoroutineMock(return_value="completed")
              self.my_ns.n2vc.GetPrimitiveOutput = asynctest.CoroutineMock(return_value={"result": "ok",
                                                                                         "pubkey": pub_key})
+             self.my_ns.n2vc.get_public_key = asynctest.CoroutineMock(
+                 return_value=getenv("OSMLCM_VCA_PUBKEY", "public_key"))
  
          # Mock RO
          if not getenv("OSMLCMTEST_RO_NOMOCK"):
              self.my_ns.RO.get_list = asynctest.CoroutineMock(self.my_ns.RO.get_list, return_value=[])
              self.my_ns.RO.create = asynctest.CoroutineMock(self.my_ns.RO.create, side_effect=self._ro_create())
              self.my_ns.RO.show = asynctest.CoroutineMock(self.my_ns.RO.show, side_effect=self._ro_show())
-             self.my_ns.RO.create_action = asynctest.CoroutineMock(self.my_ns.RO.create_action)
+             self.my_ns.RO.create_action = asynctest.CoroutineMock(self.my_ns.RO.create_action,
+                                                                   return_value={"vm-id": {"vim_result": 200,
+                                                                                           "description": "done"}})
  
      @asynctest.fail_on(active_handles=True)   # all async tasks must be completed
      async def test_instantiate(self):
                                "vnfs": {"5": {"vdus": {"vdu_id": {"mgmt_keys": n2vc_key_list}}}}}
          self.assertEqual(ro_ns_params, ro_params_expected)
  
 +    # Test scale() and related methods
      @asynctest.fail_on(active_handles=True)   # all async tasks must be completed
      async def test_scale(self):
 -        pass
 +        # print("Test scale started")
 +
 +        # TODO: Add more higher-lever tests here, for example:
 +        # scale-out/scale-in operations with success/error result
 +
 +        # Test scale() with missing 'scaleVnfData', should return operationState = 'FAILED'
 +        nsr_id = self.db_content["nsrs"][0]["_id"]
 +        nslcmop_id = self.db_content["nslcmops"][0]["_id"]
 +        await self.my_ns.scale(nsr_id, nslcmop_id)
 +        expected_value = 'FAILED'
 +        return_value = self._db_get_one("nslcmops", {"_id": nslcmop_id}).get("operationState")
 +        self.assertEqual(return_value, expected_value)
 +        # print("scale_result: {}".format(self._db_get_one("nslcmops", {"_id": nslcmop_id}).get("detailed-status")))
 +
 +    # Test _reintent_or_skip_suboperation()
 +    # Expected result:
 +    # - if a suboperation's 'operationState' is marked as 'COMPLETED', SUBOPERATION_STATUS_SKIP is expected
 +    # - if marked as anything but 'COMPLETED', the suboperation index is expected
 +    def test_scale_reintent_or_skip_suboperation(self):
 +        # Load an alternative 'nslcmops' YAML for this test
 +        self.db_content['nslcmops'] = yaml.load(descriptors.db_nslcmops_scale_text, Loader=yaml.Loader)
 +        db_nslcmop = self.db_content['nslcmops'][0]
 +        op_index = 2
 +        # Test when 'operationState' is 'COMPLETED'
 +        db_nslcmop['_admin']['operations'][op_index]['operationState'] = 'COMPLETED'
 +        return_value = self.my_ns._reintent_or_skip_suboperation(db_nslcmop, op_index)
 +        expected_value = self.my_ns.SUBOPERATION_STATUS_SKIP
 +        self.assertEqual(return_value, expected_value)
 +        # Test when 'operationState' is not 'COMPLETED'
 +        db_nslcmop['_admin']['operations'][op_index]['operationState'] = None
 +        return_value = self.my_ns._reintent_or_skip_suboperation(db_nslcmop, op_index)
 +        expected_value = op_index
 +        self.assertEqual(return_value, expected_value)
 +
 +    # Test _find_suboperation()
 +    # Expected result: index of the found sub-operation, or SUBOPERATION_STATUS_NOT_FOUND if not found
 +    def test_scale_find_suboperation(self):
 +        # Load an alternative 'nslcmops' YAML for this test
 +        self.db_content['nslcmops'] = yaml.load(descriptors.db_nslcmops_scale_text, Loader=yaml.Loader)
 +        db_nslcmop = self.db_content['nslcmops'][0]
 +        # Find this sub-operation
 +        op_index = 2
 +        vnf_index = db_nslcmop['_admin']['operations'][op_index]['member_vnf_index']
 +        primitive = db_nslcmop['_admin']['operations'][op_index]['primitive']
 +        primitive_params = db_nslcmop['_admin']['operations'][op_index]['primitive_params']
 +        match = {
 +            'member_vnf_index': vnf_index,
 +            'primitive': primitive,
 +            'primitive_params': primitive_params,
 +        }
 +        found_op_index = self.my_ns._find_suboperation(db_nslcmop, match)
 +        self.assertEqual(found_op_index, op_index)
 +        # Test with not-matching params
 +        match = {
 +            'member_vnf_index': vnf_index,
 +            'primitive': '',
 +            'primitive_params': primitive_params,
 +        }
 +        found_op_index = self.my_ns._find_suboperation(db_nslcmop, match)
 +        self.assertEqual(found_op_index, self.my_ns.SUBOPERATION_STATUS_NOT_FOUND)
 +        # Test with None
 +        match = None
 +        found_op_index = self.my_ns._find_suboperation(db_nslcmop, match)
 +        self.assertEqual(found_op_index, self.my_ns.SUBOPERATION_STATUS_NOT_FOUND)
 +
 +    # Test _update_suboperation_status()
 +    def test_scale_update_suboperation_status(self):
 +        db_nslcmop = self.db_content['nslcmops'][0]
 +        op_index = 0
 +        # Force the initial values to be distinct from the updated ones
 +        db_nslcmop['_admin']['operations'][op_index]['operationState'] = 'PROCESSING'
 +        db_nslcmop['_admin']['operations'][op_index]['detailed-status'] = 'In progress'
 +        # Test to change 'operationState' and 'detailed-status'
 +        operationState = 'COMPLETED'
 +        detailed_status = 'Done'
 +        self.my_ns._update_suboperation_status(
 +            db_nslcmop, op_index, operationState, detailed_status)
 +        operationState_new = db_nslcmop['_admin']['operations'][op_index]['operationState']
 +        detailed_status_new = db_nslcmop['_admin']['operations'][op_index]['detailed-status']
 +        # print("DEBUG: operationState_new={}, detailed_status_new={}".format(operationState_new, detailed_status_new))
 +        self.assertEqual(operationState, operationState_new)
 +        self.assertEqual(detailed_status, detailed_status_new)
 +
 +    # Test _add_suboperation()
 +    def test_scale_add_suboperation(self):
 +        db_nslcmop = self.db_content['nslcmops'][0]
 +        vnf_index = '1'
 +        num_ops_before = len(db_nslcmop.get('_admin', {}).get('operations', [])) - 1
 +        vdu_id = None
 +        vdu_count_index = None
 +        vdu_name = None
 +        primitive = 'touch'
 +        mapped_primitive_params = {'parameter':
 +                                   [{'data-type': 'STRING',
 +                                     'name': 'filename',
 +                                     'default-value': '<touch_filename2>'}],
 +                                   'name': 'touch'}
 +        operationState = 'PROCESSING'
 +        detailed_status = 'In progress'
 +        operationType = 'PRE-SCALE'
 +        # Add a 'pre-scale' suboperation
 +        op_index_after = self.my_ns._add_suboperation(db_nslcmop, vnf_index, vdu_id, vdu_count_index,
 +                                                      vdu_name, primitive, mapped_primitive_params,
 +                                                      operationState, detailed_status, operationType)
 +        self.assertEqual(op_index_after, num_ops_before + 1)
 +
 +        # Delete all suboperations and add the same operation again
 +        del db_nslcmop['_admin']['operations']
 +        op_index_zero = self.my_ns._add_suboperation(db_nslcmop, vnf_index, vdu_id, vdu_count_index,
 +                                                     vdu_name, primitive, mapped_primitive_params,
 +                                                     operationState, detailed_status, operationType)
 +        self.assertEqual(op_index_zero, 0)
 +
 +        # Add a 'RO' suboperation
 +        RO_nsr_id = '1234567890'
 +        RO_scaling_info = [{'type': 'create', 'count': 1, 'member-vnf-index': '1', 'osm_vdu_id': 'dataVM'}]
 +        op_index = self.my_ns._add_suboperation(db_nslcmop, vnf_index, vdu_id, vdu_count_index,
 +                                                vdu_name, primitive, mapped_primitive_params,
 +                                                operationState, detailed_status, operationType,
 +                                                RO_nsr_id, RO_scaling_info)
 +        db_RO_nsr_id = db_nslcmop['_admin']['operations'][op_index]['RO_nsr_id']
 +        self.assertEqual(op_index, 1)
 +        self.assertEqual(RO_nsr_id, db_RO_nsr_id)
 +
 +        # Try to add an invalid suboperation, should return SUBOPERATION_STATUS_NOT_FOUND
 +        op_index_invalid = self.my_ns._add_suboperation(None, None, None, None, None,
 +                                                        None, None, None,
 +                                                        None, None, None)
 +        self.assertEqual(op_index_invalid, self.my_ns.SUBOPERATION_STATUS_NOT_FOUND)
 +
 +    # Test _check_or_add_scale_suboperation() and _check_or_add_scale_suboperation_RO()
 +    # check the possible return values:
 +    # - SUBOPERATION_STATUS_NEW: This is a new sub-operation
 +    # - op_index (non-negative number): This is an existing sub-operation, operationState != 'COMPLETED'
 +    # - SUBOPERATION_STATUS_SKIP: This is an existing sub-operation, operationState == 'COMPLETED'
 +    def test_scale_check_or_add_scale_suboperation(self):
 +        db_nslcmop = self.db_content['nslcmops'][0]
 +        operationType = 'PRE-SCALE'
 +        vnf_index = '1'
 +        primitive = 'touch'
 +        primitive_params = {'parameter':
 +                            [{'data-type': 'STRING',
 +                              'name': 'filename',
 +                              'default-value': '<touch_filename2>'}],
 +                            'name': 'touch'}
 +
 +        # Delete all sub-operations to be sure this is a new sub-operation
 +        del db_nslcmop['_admin']['operations']
 +
 +        # Add a new sub-operation
 +        # For new sub-operations, operationState is set to 'PROCESSING' by default
 +        op_index_new = self.my_ns._check_or_add_scale_suboperation(
 +            db_nslcmop, vnf_index, primitive, primitive_params, operationType)
 +        self.assertEqual(op_index_new, self.my_ns.SUBOPERATION_STATUS_NEW)
 +
 +        # Use the same parameters again to match the already added sub-operation
 +        # which has status 'PROCESSING' (!= 'COMPLETED') by default
 +        # The expected return value is a non-negative number
 +        op_index_existing = self.my_ns._check_or_add_scale_suboperation(
 +            db_nslcmop, vnf_index, primitive, primitive_params, operationType)
 +        self.assertTrue(op_index_existing >= 0)
 +
 +        # Change operationState 'manually' for this sub-operation
 +        db_nslcmop['_admin']['operations'][op_index_existing]['operationState'] = 'COMPLETED'
 +        # Then use the same parameters again to match the already added sub-operation,
 +        # which now has status 'COMPLETED'
 +        # The expected return value is SUBOPERATION_STATUS_SKIP
 +        op_index_skip = self.my_ns._check_or_add_scale_suboperation(
 +            db_nslcmop, vnf_index, primitive, primitive_params, operationType)
 +        self.assertEqual(op_index_skip, self.my_ns.SUBOPERATION_STATUS_SKIP)
 +
 +        # RO sub-operation test:
 +        # Repeat tests for the very similar _check_or_add_scale_suboperation_RO(),
 +        RO_nsr_id = '1234567890'
 +        RO_scaling_info = [{'type': 'create', 'count': 1, 'member-vnf-index': '1', 'osm_vdu_id': 'dataVM'}]
 +        op_index_new_RO = self.my_ns._check_or_add_scale_suboperation(
 +            db_nslcmop, vnf_index, None, None, 'SCALE-RO', RO_nsr_id, RO_scaling_info)
 +        self.assertEqual(op_index_new_RO, self.my_ns.SUBOPERATION_STATUS_NEW)
 +
 +        # Use the same parameters again to match the already added RO sub-operation
 +        op_index_existing_RO = self.my_ns._check_or_add_scale_suboperation(
 +            db_nslcmop, vnf_index, None, None, 'SCALE-RO', RO_nsr_id, RO_scaling_info)
 +        self.assertTrue(op_index_existing_RO >= 0)
 +
 +        # Change operationState 'manually' for this RO sub-operation
 +        db_nslcmop['_admin']['operations'][op_index_existing_RO]['operationState'] = 'COMPLETED'
 +        # Then use the same parameters again to match the already added sub-operation,
 +        # which now has status 'COMPLETED'
 +        # The expected return value is SUBOPERATION_STATUS_SKIP
 +        op_index_skip_RO = self.my_ns._check_or_add_scale_suboperation(
 +            db_nslcmop, vnf_index, None, None, 'SCALE-RO', RO_nsr_id, RO_scaling_info)
 +        self.assertEqual(op_index_skip_RO, self.my_ns.SUBOPERATION_STATUS_SKIP)
  
  
  if __name__ == '__main__':
diff --combined setup.py
+++ b/setup.py
@@@ -51,7 -51,7 +51,7 @@@ setup
      ],
      install_requires=[
          # 'pymongo',
--        'PyYAML==3.*',
++        'PyYAML>=3.*',
          'aiohttp==0.20.2',
          'osm-common',
          'n2vc',