Notify about NSD and PNFD changes
[modeling/etsicatalog.git] / catalog / packages / biz / vnf_package.py
index 21d5819..be73595 100644 (file)
 import json
 import logging
 import os
-import sys
+
 import threading
 import traceback
 import urllib
 import uuid
+import zipfile
 
+from catalog.packages import const
 from catalog.packages.biz.common import parse_file_range, read, save
+from catalog.packages.biz.notificationsutil import prepare_vnfpkg_notification, NotificationsUtil
 from catalog.pub.config.config import CATALOG_ROOT_PATH
 from catalog.pub.database.models import VnfPackageModel, NSPackageModel
 from catalog.pub.exceptions import CatalogException, ResourceNotFoundException
-from catalog.pub.utils.values import ignore_case_get
 from catalog.pub.utils import fileutil, toscaparser
-from catalog.packages import const
-from catalog.packages.biz.notificationsutil import prepare_vnfpkg_notification, NotificationsUtil
-
+from catalog.pub.utils.values import ignore_case_get
 
 logger = logging.getLogger(__name__)
 
@@ -111,8 +111,6 @@ class VnfPackage(object):
         #     logger.error("VNF package(%s) is not CREATED" % vnf_pkg_id)
         #     raise CatalogException("VNF package(%s) is not CREATED" % vnf_pkg_id)
         vnf_pkg.update(onboardingState=const.PKG_STATUS.UPLOADING)
-        send_notification(vnf_pkg_id, const.PKG_NOTIFICATION_TYPE.ONBOARDING,
-                          const.PKG_CHANGE_TYPE.OP_STATE_CHANGE)
 
         local_file_name = save(remote_file, vnf_pkg_id)
         logger.info('VNF package(%s) has been uploaded.' % vnf_pkg_id)
@@ -132,6 +130,58 @@ class VnfPackage(object):
         logger.info('VNF package (%s) has been downloaded.' % vnf_pkg_id)
         return read(local_file_path, start, end)
 
+    def download_vnfd(self, vnf_pkg_id):
+        logger.info('Start to download VNFD of VNF package(%s)...' % vnf_pkg_id)
+        nf_pkg = VnfPackageModel.objects.filter(vnfPackageId=vnf_pkg_id)
+        if not nf_pkg.exists():
+            logger.error('VNF package(%s) does not exist.' % vnf_pkg_id)
+            raise ResourceNotFoundException('VNF package(%s) does not exist.' % vnf_pkg_id)
+        if nf_pkg[0].onboardingState != const.PKG_STATUS.ONBOARDED:
+            raise CatalogException("VNF package (%s) is not on-boarded" % vnf_pkg_id)
+
+        vnfd_zip_file = self.creat_vnfd(vnf_pkg_id, nf_pkg[0].localFilePath)
+        logger.info('VNFD of VNF package (%s) has been downloaded.' % vnf_pkg_id)
+        return read(vnfd_zip_file, 0, os.path.getsize(vnfd_zip_file))
+
+    def creat_vnfd(self, vnf_pkg_id, vendor_pkg_file):
+        """
+        Create VNFD zip file from vendor original package
+        :param self:
+        :param vnf_pkg_id: VNF package id (CSAR id)
+        :param vendor_pkg_file: vendor original package
+        :return:
+        """
+        vnf_package_path = os.path.join(CATALOG_ROOT_PATH, vnf_pkg_id)
+        if not os.path.exists(vnf_package_path):
+            os.makedirs(vnf_package_path)
+        vnfd_zip_file = os.path.join(vnf_package_path, "VNFD.zip")
+        if os.path.exists(vnfd_zip_file):
+            return vnfd_zip_file
+        else:
+            if vendor_pkg_file.endswith(".csar") or vendor_pkg_file.endswith(".zip"):
+                try:
+                    vnfd_path = os.path.join(vnf_package_path, "vnfd")
+                    with zipfile.ZipFile(vendor_pkg_file, 'r') as vendor_zip:
+                        vender_files = vendor_zip.namelist()
+                        for vender_file in vender_files:
+                            if str(vender_file).startswith("Definitions"):
+                                vendor_zip.extract(vender_file, vnfd_path)
+                    with zipfile.ZipFile(vnfd_zip_file, 'w', zipfile.ZIP_DEFLATED) as vnfd_zip:
+                        def_path = os.path.join(vnfd_path, "Definitions")
+                        if os.path.exists(def_path):
+                            def_files = os.listdir(def_path)
+                            for def_file in def_files:
+                                full_path = os.path.join(def_path, def_file)
+                                vnfd_zip.write(full_path, def_file)
+                    return vnfd_zip_file
+                except Exception as e:
+                    logger.error(e)
+                    if os.path.exists(vnfd_zip):
+                        os.remove(vnfd_zip)
+                    raise e
+                finally:
+                    fileutil.delete_dirs(vnfd_path)
+
 
 class VnfPkgUploadThread(threading.Thread):
     def __init__(self, data, vnf_pkg_id):
@@ -140,16 +190,21 @@ class VnfPkgUploadThread(threading.Thread):
         self.data = data
         self.upload_file_name = None
 
+    def vnf_pkg_upload_failed_handle(self, error_msg):
+        logger.error(error_msg)
+        logger.error(traceback.format_exc())
+        vnf_pkg = VnfPackageModel.objects.filter(vnfPackageId=self.vnf_pkg_id)
+        if vnf_pkg and vnf_pkg[0].onboardingState == const.PKG_STATUS.UPLOADING:
+            vnf_pkg.update(onboardingState=const.PKG_STATUS.CREATED)
+
     def run(self):
         try:
             self.upload_vnf_pkg_from_uri()
             parse_vnfd_and_save(self.vnf_pkg_id, self.upload_file_name)
         except CatalogException as e:
-            logger.error(e.args[0])
+            self.vnf_pkg_upload_failed_handle(e.args[0])
         except Exception as e:
-            logger.error(e.args[0])
-            logger.error(traceback.format_exc())
-            logger.error(str(sys.exc_info()))
+            self.vnf_pkg_upload_failed_handle(e.args[0])
 
     def upload_vnf_pkg_from_uri(self):
         logger.info("Start to upload VNF packge(%s) from URI..." % self.vnf_pkg_id)
@@ -225,6 +280,8 @@ def parse_vnfd_and_save(vnf_pkg_id, vnf_pkg_path):
             localFilePath=vnf_pkg_path,
             vnfPackageUri=os.path.split(vnf_pkg_path)[-1]
         )
+        send_notification(vnf_pkg_id, const.PKG_NOTIFICATION_TYPE.ONBOARDING,
+                          const.PKG_CHANGE_TYPE.OP_STATE_CHANGE)
     else:
         raise CatalogException("VNF propeties and metadata in VNF Package(id=%s) are empty." % vnf_pkg_id)
     logger.info('VNF package(%s) has been processed(done).' % vnf_pkg_id)