remove internal content at ns.nsd
[osm/NBI.git] / osm_nbi / instance_topics.py
index 986d4d3..d444116 100644 (file)
@@ -18,7 +18,8 @@ from uuid import uuid4
 from http import HTTPStatus
 from time import time
 from copy import copy, deepcopy
-from osm_nbi.validation import validate_input, ValidationError, ns_instantiate, ns_action, ns_scale, nsi_instantiate
+from osm_nbi.validation import validate_input, ValidationError, ns_instantiate, ns_terminate, ns_action, ns_scale,\
+    nsi_instantiate
 from osm_nbi.base_topic import BaseTopic, EngineException, get_iterable, deep_get
 # from descriptor_topics import DescriptorTopic
 from yaml import safe_dump
@@ -74,13 +75,14 @@ class NsrTopic(BaseTopic):
                                   "Launch 'terminate' operation first; or force deletion".format(_id),
                                   http_code=HTTPStatus.CONFLICT)
 
-    def delete_extra(self, session, _id, db_content):
+    def delete_extra(self, session, _id, db_content, not_send_msg=None):
         """
         Deletes associated nslcmops and vnfrs from database. Deletes associated filesystem.
          Set usageState of pdu, vnfd, nsd
         :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
         :param _id: server internal id
         :param db_content: The database content of the descriptor
+        :param not_send_msg: To not send message (False) or store content (list) instead
         :return: None if ok or raises EngineException with the problem
         """
         self.fs.file_delete(_id, ignore_non_exist=True)
@@ -231,7 +233,15 @@ class NsrTopic(BaseTopic):
                 "name-ref": ns_request["nsName"],
                 "short-name": ns_request["nsName"],
                 "admin-status": "ENABLED",
-                "nsd": nsd,
+                "nsState": "NOT_INSTANTIATED",
+                "currentOperation": "IDLE",
+                "currentOperationID": None,
+                "errorDescription": None,
+                "errorDetail": None,
+                "deploymentStatus": None,
+                "configurationStatus": None,
+                "vcaStatus": None,
+                "nsd": {k: v for k, v in nsd.items() if k in ("vld", "_id", "id", "constituent-vnfd", "name")},
                 "datacenter": ns_request["vimAccountId"],
                 "resource-orchestrator": "osmopenmano",
                 "description": ns_request.get("nsDescription", ""),
@@ -261,10 +271,7 @@ class NsrTopic(BaseTopic):
             ns_request["nsr_id"] = nsr_id
             # Create vld
             if nsd.get("vld"):
-                nsr_descriptor["vld"] = []
-                for nsd_vld in nsd.get("vld"):
-                    nsr_descriptor["vld"].append(
-                        {key: nsd_vld[key] for key in ("id", "vim-network-name", "vim-network-id") if key in nsd_vld})
+                nsr_descriptor["vld"] = nsd["vld"]
 
             # Create VNFR
             needed_vnfds = {}
@@ -350,10 +357,10 @@ class NsrTopic(BaseTopic):
                     kdur = {x: kdu[x] for x in kdu if x in ("helm-chart", "juju-bundle")}
                     kdur["kdu-name"] = kdu["name"]
                     # TODO      "name": ""     Name of the VDU in the VIM
-                    kdur["ip-address"] = None,  # mgmt-interface filled by LCM
-                    kdur["k8s-cluster"] = {},
+                    kdur["ip-address"] = None  # mgmt-interface filled by LCM
+                    kdur["k8s-cluster"] = {}
                     kdur["additionalParams"] = self._format_addional_params(ns_request, member_vnf["member-vnf-index"],
-                                                                            kdu_name=kdu["name"], descriptor=vnfd),
+                                                                            kdu_name=kdu["name"], descriptor=vnfd)
                     if not vnfr_descriptor.get("kdur"):
                         vnfr_descriptor["kdur"] = []
                     vnfr_descriptor["kdur"].append(kdur)
@@ -367,7 +374,7 @@ class NsrTopic(BaseTopic):
                         "internal-connection-point": [],
                         "interfaces": [],
                         "additionalParams": self._format_addional_params(ns_request, member_vnf["member-vnf-index"],
-                                                                         vdu_id=vdu["id"], descriptor=vnfd),
+                                                                         vdu_id=vdu["id"], descriptor=vnfd)
                     }
                     if vdu.get("pdu-type"):
                         vdur["pdu-type"] = vdu["pdu-type"]
@@ -458,7 +465,7 @@ class VnfrTopic(BaseTopic):
     def __init__(self, db, fs, msg, auth):
         BaseTopic.__init__(self, db, fs, msg, auth)
 
-    def delete(self, session, _id, dry_run=False):
+    def delete(self, session, _id, dry_run=False, not_send_msg=None):
         raise EngineException("Method delete called directly", HTTPStatus.INTERNAL_SERVER_ERROR)
 
     def edit(self, session, _id, indata=None, kwargs=None, content=None):
@@ -476,7 +483,7 @@ class NsLcmOpTopic(BaseTopic):
         "instantiate": ns_instantiate,
         "action": ns_action,
         "scale": ns_scale,
-        "terminate": None,
+        "terminate": ns_terminate,
     }
 
     def __init__(self, db, fs, msg, auth):
@@ -675,7 +682,6 @@ class NsLcmOpTopic(BaseTopic):
         Look for a free PDU in the catalog matching vdur type and interfaces. Fills vnfr.vdur with the interface
         (ip_address, ...) information.
         Modifies PDU _admin.usageState to 'IN_USE'
-        
         :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
         :param rollback: list with the database modifications to rollback if needed
         :param vnfr: vnfr to be updated. It is modified with pdu interface info if pdu is found
@@ -751,12 +757,13 @@ class NsLcmOpTopic(BaseTopic):
                                 vnfr_update[iface_text + ".{}".format(k)] = v
                                 vnfr_update_rollback[iface_text + ".{}".format(k)] = vdur_interface.get(v)
                         if pdu_interface.get("ip-address"):
-                            if vdur_interface.get("mgmt-interface"):
+                            if vdur_interface.get("mgmt-interface") or vdur_interface.get("mgmt-vnf"):
                                 vnfr_update_rollback[vdu_text + ".ip-address"] = vdur.get("ip-address")
                                 vnfr_update[vdu_text + ".ip-address"] = pdu_interface["ip-address"]
                             if vdur_interface.get("mgmt-vnf"):
                                 vnfr_update_rollback["ip-address"] = vnfr.get("ip-address")
                                 vnfr_update["ip-address"] = pdu_interface["ip-address"]
+                                vnfr_update[vdu_text + ".ip-address"] = pdu_interface["ip-address"]
                         if pdu_interface.get("vim-network-name") or pdu_interface.get("vim-network-id"):
                             ifaces_forcing_vim_network.append({
                                 "name": vdur_interface.get("vnf-vld-id") or vdur_interface.get("ns-vld-id"),
@@ -921,6 +928,10 @@ class NsLcmOpTopic(BaseTopic):
             "id": _id,
             "_id": _id,
             "operationState": "PROCESSING",  # COMPLETED,PARTIALLY_COMPLETED,FAILED_TEMP,FAILED,ROLLING_BACK,ROLLED_BACK
+            "queuePosition": None,
+            "stage": None,
+            "errorMessage": None,
+            "detailedStatus": None,
             "statusEnteredTime": now,
             "nsInstanceId": nsr_id,
             "lcmOperationType": operation,
@@ -935,6 +946,19 @@ class NsLcmOpTopic(BaseTopic):
         }
         return nslcmop
 
+    def _get_enabled_vims(self, session):
+        """
+        Retrieve and return VIM accounts that are accessible by current user and has state ENABLE
+        :param session: current session with user information
+        """
+        db_filter = self._get_project_filter(session)
+        db_filter["_admin.operationalState"] = "ENABLED"
+        vims = self.db.get_list("vim_accounts", db_filter)
+        vimAccounts = []
+        for vim in vims:
+            vimAccounts.append(vim['_id'])
+        return vimAccounts
+
     def new(self, rollback, session, indata=None, kwargs=None, headers=None, slice_object=False):
         """
         Performs a new operation over a ns
@@ -958,7 +982,7 @@ class NsLcmOpTopic(BaseTopic):
 
         try:
             # Override descriptor with query string kwargs
-            self._update_input_with_kwargs(indata, kwargs)
+            self._update_input_with_kwargs(indata, kwargs, yaml_format=True)
             operation = indata["lcmOperationType"]
             nsInstanceId = indata["nsInstanceId"]
 
@@ -990,6 +1014,9 @@ class NsLcmOpTopic(BaseTopic):
             nslcmop_desc = self._create_nslcmop(nsInstanceId, operation, indata)
             _id = nslcmop_desc["_id"]
             self.format_on_new(nslcmop_desc, session["project_id"], make_public=session["public"])
+            if indata.get("placement-engine"):
+                # Save valid vim accounts in lcm operation descriptor
+                nslcmop_desc['operationParams']['validVimAccounts'] = self._get_enabled_vims(session)
             self.db.create("nslcmops", nslcmop_desc)
             rollback.append({"topic": "nslcmops", "_id": _id})
             if not slice_object:
@@ -1000,7 +1027,7 @@ class NsLcmOpTopic(BaseTopic):
         # except DbException as e:
         #     raise EngineException("Cannot get ns_instance '{}': {}".format(e), HTTPStatus.NOT_FOUND)
 
-    def delete(self, session, _id, dry_run=False):
+    def delete(self, session, _id, dry_run=False, not_send_msg=None):
         raise EngineException("Method delete called directly", HTTPStatus.INTERNAL_SERVER_ERROR)
 
     def edit(self, session, _id, indata=None, kwargs=None, content=None):
@@ -1071,13 +1098,14 @@ class NsiTopic(BaseTopic):
                                   "Launch 'terminate' operation first; or force deletion".format(_id),
                                   http_code=HTTPStatus.CONFLICT)
 
-    def delete_extra(self, session, _id, db_content):
+    def delete_extra(self, session, _id, db_content, not_send_msg=None):
         """
         Deletes associated nsilcmops from database. Deletes associated filesystem.
          Set usageState of nst
         :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
         :param _id: server internal id
         :param db_content: The database content of the descriptor
+        :param not_send_msg: To not send message (False) or store content (list) instead
         :return: None if ok or raises EngineException with the problem
         """
 
@@ -1093,7 +1121,7 @@ class NsiTopic(BaseTopic):
                 if nsi:  # last one using nsr
                     continue
             try:
-                self.nsrTopic.delete(session, nsr_id, dry_run=False)
+                self.nsrTopic.delete(session, nsr_id, dry_run=False, not_send_msg=not_send_msg)
             except (DbException, EngineException) as e:
                 if e.http_code == HTTPStatus.NOT_FOUND:
                     pass
@@ -1231,7 +1259,7 @@ class NsiTopic(BaseTopic):
                 nsi_vlds.append(nsi_vld)
 
             nsi_descriptor["_admin"]["netslice-vld"] = nsi_vlds
-            # Creating netslice-subnet_record. 
+            # Creating netslice-subnet_record.
             needed_nsds = {}
             services = []
 
@@ -1511,7 +1539,7 @@ class NsiLcmOpTopic(BaseTopic):
         except ValidationError as e:
             raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
 
-    def delete(self, session, _id, dry_run=False):
+    def delete(self, session, _id, dry_run=False, not_send_msg=None):
         raise EngineException("Method delete called directly", HTTPStatus.INTERNAL_SERVER_ERROR)
 
     def edit(self, session, _id, indata=None, kwargs=None, content=None):