d0db6bf111db66d281e6a40d5036e13a03d53f4d
[modeling/etsicatalog.git] / catalog / packages / biz / sdc_service_package.py
1 # Copyright (c) 2019, CMCC Technologies. Co., Ltd.
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 #         http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14
15 import logging
16 import traceback
17
18 from coverage.xmlreport import os
19
20 from catalog.packages.biz.service_descriptor import ServiceDescriptor
21 from catalog.pub.config.config import CATALOG_ROOT_PATH, REG_TO_MSB_REG_PARAM, CATALOG_URL_PATH
22 from catalog.pub.database.models import ServicePackageModel, VnfPackageModel, PnfPackageModel
23 from catalog.pub.exceptions import CatalogException, PackageNotFoundException, \
24     PackageHasExistsException
25 from catalog.pub.msapi import sdc
26 from catalog.pub.utils import fileutil, toscaparser
27
28 logger = logging.getLogger(__name__)
29
30
31 class ServicePackage(object):
32     """
33     Actions for sdc service package.
34     """
35
36     def __init__(self):
37         pass
38
39     def on_distribute(self, csar_id):
40         if ServicePackageModel.objects.filter(servicePackageId=csar_id):
41             raise PackageHasExistsException("Service CSAR(%s) already exists." % csar_id)
42
43         try:
44             service = sdc.get_asset(sdc.ASSETTYPE_SERVICES, csar_id)
45             # check if the related resources exist
46             resources = service.get('resources', None)
47             if resources:
48                 for resource in resources:
49                     if not VnfPackageModel.objects.filter(vnfPackageId=resource['resourceUUID']) and \
50                             not PnfPackageModel.objects.filter(pnfPackageId=resource['resourceUUID']):
51                         logger.error("Resource [%s] is not distributed.", resource['resourceUUID'])
52                         raise CatalogException("Resource (%s) is not distributed." % resource['resourceUUID'])
53
54             # download csar package
55             local_path = os.path.join(CATALOG_ROOT_PATH, csar_id)
56             csar_name = "%s.csar" % service.get("name", csar_id)
57             local_file_name = sdc.download_artifacts(service["toscaModelURL"], local_path, csar_name)
58             if local_file_name.endswith(".csar") or local_file_name.endswith(".zip"):
59                 fileutil.unzip_file(local_file_name, local_path, "")
60             data = {
61                 'userDefinedData': {}
62             }
63             serviced = ServiceDescriptor()
64             serviced.create(data, csar_id)
65             serviced.parse_serviced_and_save(csar_id, local_file_name)
66
67         except Exception as e:
68             logger.error(traceback.format_exc())
69             if ServicePackageModel.objects.filter(servicePackageId=csar_id):
70                 ServicePackage().delete_csar(csar_id)
71             raise e
72
73     def delete_csar(self, csar_id):
74         serviced = ServiceDescriptor()
75         serviced.delete_single(csar_id)
76
77     def get_csars(self):
78         csars = []
79         packages = ServicePackageModel.objects.filter()
80         for package in packages:
81             csar = self.get_csar(package.servicePackageId)
82             csars.append(csar)
83         return csars
84
85     def get_csar(self, csar_id):
86         package_info = {}
87         csars = ServicePackageModel.objects.filter(servicePackageId=csar_id)
88         if csars:
89             package_info["servicedId"] = csars[0].servicedId
90             package_info["servicePackageId"] = csars[0].servicePackageId
91             package_info["servicedProvider"] = csars[0].servicedDesigner
92             package_info["servicedVersion"] = csars[0].servicedVersion
93             package_info["csarName"] = csars[0].servicePackageUri
94             package_info["servicedModel"] = csars[0].servicedModel
95             package_info["servicedInvariantId"] = csars[0].invariantId
96             package_info["downloadUrl"] = "http://%s:%s/%s/%s/%s" % (
97                 REG_TO_MSB_REG_PARAM[0]["nodes"][0]["ip"],
98                 REG_TO_MSB_REG_PARAM[0]["nodes"][0]["port"],
99                 CATALOG_URL_PATH,
100                 csar_id,
101                 csars[0].servicePackageUri)
102         else:
103             error_message = "Service package[%s] not Found." % csar_id
104             logger.error(error_message)
105             raise PackageNotFoundException(error_message)
106
107         return {"csarId": csar_id, "packageInfo": package_info}
108
109     def parse_serviced(self, csar_id, inputs):
110         service_pkg = ServicePackageModel.objects.filter(servicePackageId=csar_id)
111         if not service_pkg:
112             raise PackageNotFoundException("Service CSAR(%s) does not exist." % csar_id)
113
114         try:
115             csar_path = service_pkg[0].localFilePath
116             ret = {"model": toscaparser.parse_sd(csar_path, inputs)}
117             return ret
118         except CatalogException as e:
119             logger.error(e.args[0])
120             raise e
121         except Exception as e:
122             logger.error(e.args[0])
123             logger.error(traceback.format_exc())
124             raise e