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

@@@ -18,14 -18,27 +18,25 @@@ 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
@@@ -15,4 -15,4 +15,4 @@@
  ##
  
  tox -e flake8
--tox -e unittest
++tox -e unittest
@@@ -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 --cc osm_lcm/lcm.py
@@@ -487,7 -520,7 +526,7 @@@ class Lcm
          # 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
@@@ -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
@@@ -257,10 -257,8 +261,10 @@@ class TaskRegistry(LcmBase)
                  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']
diff --cc osm_lcm/ns.py
@@@ -663,58 -621,432 +632,489 @@@ class NsLcm(LcmBase)
              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)
          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
              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()
              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):
          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)
                              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:
              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"]
@@@ -127,10 -988,10 +127,10 @@@ class TestMyNS(asynctest.TestCase)
                  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", "")
diff --cc 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',