genericparser seed code
[modeling/etsicatalog.git] / genericparser / 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 genericparser.packages.biz.service_descriptor import ServiceDescriptor
21 from genericparser.pub.config.config import GENERICPARSER_ROOT_PATH, REG_TO_MSB_REG_PARAM, GENERICPARSER_URL_PATH
22 from genericparser.pub.database.models import ServicePackageModel
23 from genericparser.pub.exceptions import GenericparserException, PackageNotFoundException, \
24     PackageHasExistsException
25 from genericparser.pub.msapi import sdc
26 from genericparser.pub.utils import fileutil, toscaparsers
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             artifact = sdc.get_artifact(sdc.ASSETTYPE_SERVICES, csar_id)
45             local_path = os.path.join(GENERICPARSER_ROOT_PATH, csar_id)
46             csar_name = "%s.csar" % artifact.get("name", csar_id)
47             local_file_name = sdc.download_artifacts(artifact["toscaModelURL"], local_path, csar_name)
48             if local_file_name.endswith(".csar") or local_file_name.endswith(".zip"):
49                 fileutil.unzip_file(local_file_name, local_path, "")
50             data = {
51                 'userDefinedData': {}
52             }
53             serviced = ServiceDescriptor()
54             serviced.create(data, csar_id)
55             serviced.parse_serviced_and_save(csar_id, local_file_name)
56
57         except Exception as e:
58             logger.error(traceback.format_exc())
59             if ServicePackageModel.objects.filter(servicePackageId=csar_id):
60                 ServicePackage().delete_csar(csar_id)
61             raise e
62
63     def delete_csar(self, csar_id):
64         serviced = ServiceDescriptor()
65         serviced.delete_single(csar_id)
66
67     def get_csars(self):
68         csars = []
69         packages = ServicePackageModel.objects.filter()
70         for package in packages:
71             csar = self.get_csar(package.servicePackageId)
72             csars.append(csar)
73         return csars
74
75     def get_csar(self, csar_id):
76         package_info = {}
77         csars = ServicePackageModel.objects.filter(servicePackageId=csar_id)
78         if csars:
79             package_info["servicedId"] = csars[0].servicedId
80             package_info["servicePackageId"] = csars[0].servicePackageId
81             package_info["servicedProvider"] = csars[0].servicedDesigner
82             package_info["servicedVersion"] = csars[0].servicedVersion
83             package_info["csarName"] = csars[0].servicePackageUri
84             package_info["servicedModel"] = csars[0].servicedModel
85             package_info["servicedInvariantId"] = csars[0].invariantId
86             package_info["downloadUrl"] = "http://%s:%s/%s/%s/%s" % (
87                 REG_TO_MSB_REG_PARAM[0]["nodes"][0]["ip"],
88                 REG_TO_MSB_REG_PARAM[0]["nodes"][0]["port"],
89                 GENERICPARSER_URL_PATH,
90                 csar_id,
91                 csars[0].servicePackageUri)
92         else:
93             error_message = "Service package[%s] not Found." % csar_id
94             logger.error(error_message)
95             raise PackageNotFoundException(error_message)
96
97         return {"csarId": csar_id, "packageInfo": package_info}
98
99     def parse_serviced(self, csar_id, inputs):
100         service_pkg = ServicePackageModel.objects.filter(servicePackageId=csar_id)
101         if not service_pkg:
102             raise PackageNotFoundException("Service CSAR(%s) does not exist." % csar_id)
103
104         try:
105             csar_path = service_pkg[0].localFilePath
106             ret = {"model": toscaparsers.parse_sd(csar_path, inputs)}
107             return ret
108         except GenericparserException as e:
109             logger.error(e.message)
110             raise e
111         except Exception as e:
112             logger.error(e.message)
113             logger.error(traceback.format_exc())
114             raise e