Fixed bug 1476: VLD params (ip-profile) inside a NS not used
[osm/LCM.git] / osm_lcm / ns.py
index 75db8e5..1bcf4c7 100644 (file)
@@ -137,7 +137,7 @@ class NsLcm(LcmBase):
             juju_command=self.vca_config.get("jujupath"),
             log=self.logger,
             loop=self.loop,
-            on_update_db=None,
+            on_update_db=self._on_update_k8s_db,
             vca_config=self.vca_config,
             fs=self.fs,
             db=self.db
@@ -208,7 +208,6 @@ class NsLcm(LcmBase):
 
         # self.logger.debug('_on_update_n2vc_db(table={}, filter={}, path={}, updated_data={}'
         #                   .format(table, filter, path, updated_data))
-
         try:
 
             nsr_id = filter.get('_id')
@@ -223,6 +222,7 @@ class NsLcm(LcmBase):
             # vcaStatus
             db_dict = dict()
             db_dict['vcaStatus'] = status_dict
+            await self.n2vc.update_vca_status(db_dict['vcaStatus'])
 
             # update configurationStatus for this VCA
             try:
@@ -289,6 +289,40 @@ class NsLcm(LcmBase):
         except Exception as e:
             self.logger.warn('Error updating NS state for ns={}: {}'.format(nsr_id, e))
 
+    async def _on_update_k8s_db(self, cluster_uuid, kdu_instance, filter=None):
+        """
+        Updating vca status in NSR record
+        :param cluster_uuid: UUID of a k8s cluster
+        :param kdu_instance: The unique name of the KDU instance
+        :param filter: To get nsr_id
+        :return: none
+        """
+
+        # self.logger.debug("_on_update_k8s_db(cluster_uuid={}, kdu_instance={}, filter={}"
+        #                   .format(cluster_uuid, kdu_instance, filter))
+
+        try:
+            nsr_id = filter.get('_id')
+
+            # get vca status for NS
+            vca_status = await self.k8sclusterjuju.status_kdu(cluster_uuid,
+                                                              kdu_instance,
+                                                              complete_status=True,
+                                                              yaml_format=False)
+            # vcaStatus
+            db_dict = dict()
+            db_dict['vcaStatus'] = {nsr_id: vca_status}
+
+            await self.k8sclusterjuju.update_vca_status(db_dict['vcaStatus'], kdu_instance)
+
+            # write to database
+            self.update_db_2("nsrs", nsr_id, db_dict)
+
+        except (asyncio.CancelledError, asyncio.TimeoutError):
+            raise
+        except Exception as e:
+            self.logger.warn('Error updating NS state for ns={}: {}'.format(nsr_id, e))
+
     @staticmethod
     def _parse_cloud_init(cloud_init_text, additional_params, vnfd_id, vdu_id):
         try:
@@ -595,7 +629,7 @@ class NsLcm(LcmBase):
             for param in ("vim-network-name", "vim-network-id"):
                 if vld_params.get(param):
                     if isinstance(vld_params[param], dict):
-                        for vim, vim_net in vld_params[param]:
+                        for vim, vim_net in vld_params[param].items():
                             other_target_vim = "vim:" + vim
                             populate_dict(target_vld["vim_info"], (other_target_vim, param.replace("-", "_")), vim_net)
                     else:  # isinstance str
@@ -664,12 +698,25 @@ class NsLcm(LcmBase):
 
             # check at nsd descriptor, if there is an ip-profile
             vld_params = {}
-            virtual_link_profiles = get_virtual_link_profiles(nsd)
+            nsd_vlp = find_in_list(
+                get_virtual_link_profiles(nsd),
+                lambda a_link_profile: a_link_profile["virtual-link-desc-id"] == vld["id"])
+            if nsd_vlp and nsd_vlp.get("virtual-link-protocol-data") and \
+                    nsd_vlp["virtual-link-protocol-data"].get("l3-protocol-data"):
+                ip_profile_source_data = nsd_vlp["virtual-link-protocol-data"]["l3-protocol-data"]
+                ip_profile_dest_data = {}
+                if "ip-version" in ip_profile_source_data:
+                    ip_profile_dest_data["ip-version"] = ip_profile_source_data["ip-version"]
+                if "cidr" in ip_profile_source_data:
+                    ip_profile_dest_data["subnet-address"] = ip_profile_source_data["cidr"]
+                if "gateway-ip" in ip_profile_source_data:
+                    ip_profile_dest_data["gateway-address"] = ip_profile_source_data["gateway-ip"]
+                if "dhcp-enabled" in ip_profile_source_data:
+                    ip_profile_dest_data["dhcp-params"] = {
+                        "enabled": ip_profile_source_data["dhcp-enabled"]
+                    }
+                vld_params["ip-profile"] = ip_profile_dest_data
 
-            for vlp in virtual_link_profiles:
-                ip_profile = find_in_list(nsd["ip-profiles"],
-                                          lambda profile: profile["name"] == vlp["ip-profile-ref"])
-                vld_params["ip-profile"] = ip_profile["ip-profile-params"]
             # update vld_params with instantiation params
             vld_instantiation_params = find_in_list(get_iterable(ns_params, "vld"),
                                                     lambda a_vld: a_vld["name"] in (vld["name"], vld["id"]))
@@ -2195,6 +2242,7 @@ class NsLcm(LcmBase):
             kdu_instance = self.k8scluster_map[k8sclustertype].generate_kdu_instance_name(
                 db_dict=db_dict_install,
                 kdu_model=k8s_instance_info["kdu-model"],
+                kdu_name=k8s_instance_info["kdu-name"],
             )
             self.update_db_2("nsrs", nsr_id, {nsr_db_path + ".kdu-instance": kdu_instance})
             await self.k8scluster_map[k8sclustertype].install(
@@ -2258,7 +2306,7 @@ class NsLcm(LcmBase):
                             cluster_uuid=k8s_instance_info["k8scluster-uuid"],
                             kdu_instance=kdu_instance,
                             primitive_name=initial_config_primitive["name"],
-                            params=primitive_params_, db_dict={}),
+                            params=primitive_params_, db_dict=db_dict_install),
                         timeout=timeout)
 
         except Exception as e:
@@ -3371,6 +3419,29 @@ class NsLcm(LcmBase):
         except Exception as e:
             return 'FAIL', 'Error executing action {}: {}'.format(primitive, e)
 
+    async def vca_status_refresh(self, nsr_id, nslcmop_id):
+        """
+        Updating the vca_status with latest juju information in nsrs record
+        :param: nsr_id: Id of the nsr
+        :param: nslcmop_id: Id of the nslcmop
+        :return: None
+        """
+
+        self.logger.debug("Task ns={} action={} Enter".format(nsr_id, nslcmop_id))
+        db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
+        if db_nsr['_admin']['deployed']['K8s']:
+            for k8s_index, k8s in enumerate(db_nsr['_admin']['deployed']['K8s']):
+                cluster_uuid, kdu_instance = k8s["k8scluster-uuid"], k8s["kdu-instance"]
+                await self._on_update_k8s_db(cluster_uuid, kdu_instance, filter={'_id': nsr_id})
+        else:
+            for vca_index, _ in enumerate(db_nsr['_admin']['deployed']['VCA']):
+                table, filter = "nsrs", {"_id": nsr_id}
+                path = "_admin.deployed.VCA.{}.".format(vca_index)
+                await self._on_update_n2vc_db(table, filter, path, {})
+
+        self.logger.debug("Task ns={} action={} Exit".format(nsr_id, nslcmop_id))
+        self.lcm_tasks.remove("ns", nsr_id, nslcmop_id, "ns_vca_status_refresh")
+
     async def action(self, nsr_id, nslcmop_id):
         # Try to lock HA task here
         task_is_locked_by_me = self.lcm_tasks.lock_HA('ns', 'nslcmops', nslcmop_id)
@@ -3549,16 +3620,19 @@ class NsLcm(LcmBase):
                 ee_id, vca_type = self._look_for_deployed_vca(nsr_deployed["VCA"], member_vnf_index=vnf_index,
                                                               vdu_id=vdu_id, vdu_count_index=vdu_count_index,
                                                               ee_descriptor_id=ee_descriptor_id)
-                db_nslcmop_notif = {"collection": "nslcmops",
-                                    "filter": {"_id": nslcmop_id},
-                                    "path": "admin.VCA"}
+                for vca_index, vca_deployed in enumerate(db_nsr['_admin']['deployed']['VCA']):
+                    if vca_deployed.get("member-vnf-index") == vnf_index:
+                        db_dict = {"collection": "nsrs",
+                                   "filter": {"_id": nsr_id},
+                                   "path": "_admin.deployed.VCA.{}.".format(vca_index)}
+                        break
                 nslcmop_operation_state, detailed_status = await self._ns_execute_primitive(
                     ee_id,
                     primitive=primitive_name,
                     primitive_params=self._map_primitive_params(config_primitive_desc, primitive_params, desc_params),
                     timeout=timeout_ns_action,
                     vca_type=vca_type,
-                    db_dict=db_nslcmop_notif)
+                    db_dict=db_dict)
 
             db_nslcmop_update["detailed-status"] = detailed_status
             error_description_nslcmop = detailed_status if nslcmop_operation_state == "FAILED" else ""
@@ -3895,7 +3969,7 @@ class NsLcm(LcmBase):
                                                                           vdu_count_index=None,
                                                                           ee_descriptor_id=ee_descriptor_id)
                             result, result_detail = await self._ns_execute_primitive(
-                                ee_id, primitive_name, primitive_params, vca_type)
+                                ee_id, primitive_name, primitive_params, vca_type=vca_type)
                             self.logger.debug(logging_text + "vnf_config_primitive={} Done with result {} {}".format(
                                 vnf_config_primitive, result, result_detail))
                             # Update operationState = COMPLETED | FAILED
@@ -4160,7 +4234,7 @@ class NsLcm(LcmBase):
                                                                           vdu_count_index=None,
                                                                           ee_descriptor_id=ee_descriptor_id)
                             result, result_detail = await self._ns_execute_primitive(
-                                ee_id, primitive_name, primitive_params, vca_type)
+                                ee_id, primitive_name, primitive_params, vca_type=vca_type)
                             self.logger.debug(logging_text + "vnf_config_primitive={} Done with result {} {}".format(
                                 vnf_config_primitive, result, result_detail))
                             # Update operationState = COMPLETED | FAILED