New topics: K8sClusters, K8sRepos
[osm/NBI.git] / osm_nbi / instance_topics.py
index e36a723..4cb1e9c 100644 (file)
@@ -23,6 +23,8 @@ from osm_nbi.base_topic import BaseTopic, EngineException, get_iterable
 # from descriptor_topics import DescriptorTopic
 from yaml import safe_dump
 from osm_common.dbbase import DbException
+from osm_common.msgbase import MsgException
+from osm_common.fsbase import FsException
 from re import match  # For checking that additional parameter names are valid Jinja2 identifiers
 
 __author__ = "Alfonso Tierno <alfonso.tiernosepulveda@telefonica.com>"
@@ -33,8 +35,8 @@ class NsrTopic(BaseTopic):
     topic_msg = "ns"
     schema_new = ns_instantiate
 
-    def __init__(self, db, fs, msg):
-        BaseTopic.__init__(self, db, fs, msg)
+    def __init__(self, db, fs, msg, auth):
+        BaseTopic.__init__(self, db, fs, msg, auth)
 
     def _check_descriptor_dependencies(self, session, descriptor):
         """
@@ -178,10 +180,15 @@ class NsrTopic(BaseTopic):
         :param indata: params to be used for the nsr
         :param kwargs: used to override the indata descriptor
         :param headers: http request headers
-        :return: the _id of nsr descriptor created at database
+        :return: the _id of nsr descriptor created at database. Or an exception of type
+            EngineException, ValidationError, DbException, FsException, MsgException.
+            Note: Exceptions are not captured on purpose. They should be captured at called
         """
 
         try:
+            step = "checking quotas"
+            self.check_quota(session)
+
             step = "validating input parameters"
             ns_request = self._remove_envelop(indata)
             # Override descriptor with query string kwargs
@@ -377,11 +384,8 @@ class NsrTopic(BaseTopic):
             self.fs.mkdir(nsr_id)
 
             return nsr_id, None
-        except ValidationError as e:   # TODO remove try Except, it is captured at nbi.py
-            raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
-        except Exception as e:
-            self.logger.exception("Exception {} at NsrTopic.new()".format(e), exc_info=True)
-            raise EngineException("Error {}: {}".format(step, e))
+        except (ValidationError, EngineException, DbException, MsgException, FsException) as e:
+            raise type(e)("{} while '{}".format(e, step), http_code=e.http_code)
 
     def edit(self, session, _id, indata=None, kwargs=None, content=None):
         raise EngineException("Method edit called directly", HTTPStatus.INTERNAL_SERVER_ERROR)
@@ -391,8 +395,8 @@ class VnfrTopic(BaseTopic):
     topic = "vnfrs"
     topic_msg = None
 
-    def __init__(self, db, fs, msg):
-        BaseTopic.__init__(self, db, fs, msg)
+    def __init__(self, db, fs, msg, auth):
+        BaseTopic.__init__(self, db, fs, msg, auth)
 
     def delete(self, session, _id, dry_run=False):
         raise EngineException("Method delete called directly", HTTPStatus.INTERNAL_SERVER_ERROR)
@@ -415,8 +419,8 @@ class NsLcmOpTopic(BaseTopic):
         "terminate": None,
     }
 
-    def __init__(self, db, fs, msg):
-        BaseTopic.__init__(self, db, fs, msg)
+    def __init__(self, db, fs, msg, auth):
+        BaseTopic.__init__(self, db, fs, msg, auth)
 
     def _check_ns_operation(self, session, nsr, operation, indata):
         """
@@ -426,22 +430,27 @@ class NsLcmOpTopic(BaseTopic):
         :param indata: descriptor with the parameters of the operation
         :return: None
         """
-        vnfds = {}
+        vnf_member_index_to_vnfd = {}  # map between vnf_member_index to vnf descriptor.
         vim_accounts = []
         wim_accounts = []
         nsd = nsr["nsd"]
 
         def check_valid_vnf_member_index(member_vnf_index):
-            # TODO change to vnfR
-            for vnf in nsd["constituent-vnfd"]:
-                if member_vnf_index == vnf["member-vnf-index"]:
-                    vnfd_id = vnf["vnfd-id-ref"]
-                    if vnfd_id not in vnfds:
-                        vnfds[vnfd_id] = self.db.get_one("vnfds", {"id": vnfd_id})
-                    return vnfds[vnfd_id]
-            else:
+            # Obtain vnf descriptor. The vnfr is used to get the vnfd._id used for this member_vnf_index
+            if vnf_member_index_to_vnfd.get(member_vnf_index):
+                return vnf_member_index_to_vnfd[member_vnf_index]
+            vnfr = self.db.get_one("vnfrs",
+                                   {"nsr-id-ref": nsr["_id"], "member-vnf-index-ref": member_vnf_index},
+                                   fail_on_empty=False)
+            if not vnfr:
                 raise EngineException("Invalid parameter member_vnf_index='{}' is not one of the "
                                       "nsd:constituent-vnfd".format(member_vnf_index))
+            vnfd = self.db.get_one("vnfds", {"_id": vnfr["vnfd-id"]}, fail_on_empty=False)
+            if not vnfd:
+                raise EngineException("vnfd id={} has been deleted!. Operation cannot be performed".
+                                      format(vnfr["vnfd-id"]))
+            vnf_member_index_to_vnfd[member_vnf_index] = vnfd  # add to cache, avoiding a later look for
+            return vnfd
 
         def check_valid_vdu(vnfd, vdu_id):
             for vdud in get_iterable(vnfd.get("vdu")):
@@ -481,7 +490,7 @@ class NsLcmOpTopic(BaseTopic):
             for in_ivld in get_iterable(in_vnfd.get("internal-vld")):
                 for ivld in get_iterable(vnfd.get("internal-vld")):
                     if in_ivld["name"] == ivld["name"] or in_ivld["name"] == ivld["id"]:
-                        for in_icp in get_iterable(in_ivld["internal-connection-point"]):
+                        for in_icp in get_iterable(in_ivld.get("internal-connection-point")):
                             for icp in ivld["internal-connection-point"]:
                                 if in_icp["id-ref"] == icp["id-ref"]:
                                     break
@@ -804,7 +813,7 @@ class NsLcmOpTopic(BaseTopic):
             if not nsr["_admin"].get("nsState") or nsr["_admin"]["nsState"] == "NOT_INSTANTIATED":
                 if operation == "terminate" and indata.get("autoremove"):
                     # NSR must be deleted
-                    return None    # a none in this case is used to indicate not instantiated. It can be removed
+                    return None, None    # a none in this case is used to indicate not instantiated. It can be removed
                 if operation != "instantiate":
                     raise EngineException("ns_instance '{}' cannot be '{}' because it is not instantiated".format(
                         nsInstanceId, operation), HTTPStatus.CONFLICT)
@@ -818,8 +827,9 @@ class NsLcmOpTopic(BaseTopic):
                 self._update_vnfrs(session, rollback, nsr, indata)
 
             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"])
-            _id = self.db.create("nslcmops", nslcmop_desc)
+            self.db.create("nslcmops", nslcmop_desc)
             rollback.append({"topic": "nslcmops", "_id": _id})
             if not slice_object:
                 self.msg.write("ns", operation, nslcmop_desc)
@@ -840,9 +850,9 @@ class NsiTopic(BaseTopic):
     topic = "nsis"
     topic_msg = "nsi"
 
-    def __init__(self, db, fs, msg):
-        BaseTopic.__init__(self, db, fs, msg)
-        self.nsrTopic = NsrTopic(db, fs, msg)
+    def __init__(self, db, fs, msg, auth):
+        BaseTopic.__init__(self, db, fs, msg, auth)
+        self.nsrTopic = NsrTopic(db, fs, msg, auth)
 
     @staticmethod
     def _format_ns_request(ns_request):
@@ -1001,6 +1011,9 @@ class NsiTopic(BaseTopic):
         """
 
         try:
+            step = "checking quotas"
+            self.check_quota(session)
+
             step = ""
             slice_request = self._remove_envelop(indata)
             # Override descriptor with query string kwargs
@@ -1164,9 +1177,9 @@ class NsiLcmOpTopic(BaseTopic):
         "terminate": None
     }
     
-    def __init__(self, db, fs, msg):
-        BaseTopic.__init__(self, db, fs, msg)
-        self.nsi_NsLcmOpTopic = NsLcmOpTopic(self.db, self.fs, self.msg)
+    def __init__(self, db, fs, msg, auth):
+        BaseTopic.__init__(self, db, fs, msg, auth)
+        self.nsi_NsLcmOpTopic = NsLcmOpTopic(self.db, self.fs, self.msg, self.auth)
 
     def _check_nsi_operation(self, session, nsir, operation, indata):
         """
@@ -1259,7 +1272,7 @@ class NsiLcmOpTopic(BaseTopic):
             if not nsir["_admin"].get("nsiState") or nsir["_admin"]["nsiState"] == "NOT_INSTANTIATED":
                 if operation == "terminate" and indata.get("autoremove"):
                     # NSIR must be deleted
-                    return None    # a none in this case is used to indicate not instantiated. It can be removed
+                    return None, None    # a none in this case is used to indicate not instantiated. It can be removed
                 if operation != "instantiate":
                     raise EngineException("netslice_instance '{}' cannot be '{}' because it is not instantiated".format(
                         netsliceInstanceId, operation), HTTPStatus.CONFLICT)