Add log and comment
[modeling/etsicatalog.git] / catalog / pub / msapi / sdc.py
1 # Copyright 2017 ZTE Corporation.
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 json
16 import logging
17 import os
18
19 from catalog.pub.config.config import SDC_BASE_URL, SDC_USER, SDC_PASSWD
20 from catalog.pub.exceptions import CatalogException
21 from catalog.pub.utils import fileutil
22 from catalog.pub.utils import restcall
23
24 logger = logging.getLogger(__name__)
25
26 ASSETTYPE_RESOURCES = "resources"
27 ASSETTYPE_SERVICES = "services"
28 DISTRIBUTED = "DISTRIBUTED"
29
30
31 def call_sdc(resource, method, content=''):
32     additional_headers = {
33         'X-ECOMP-InstanceID': 'Modeling',
34     }
35     return restcall.call_req(base_url=SDC_BASE_URL,
36                              user=SDC_USER,
37                              passwd=SDC_PASSWD,
38                              auth_type=restcall.rest_no_auth,
39                              resource=resource,
40                              method=method,
41                              content=content,
42                              additional_headers=additional_headers)
43
44
45 """
46 sample of return value
47 [
48     {
49         "uuid": "c94490a0-f7ef-48be-b3f8-8d8662a37236",
50         "invariantUUID": "63eaec39-ffbe-411c-a838-448f2c73f7eb",
51         "name": "underlayvpn",
52         "version": "2.0",
53         "toscaModelURL": "/sdc/v1/catalog/resources/c94490a0-f7ef-48be-b3f8-8d8662a37236/toscaModel",
54         "category": "Volte",
55         "subCategory": "VolteVF",
56         "resourceType": "VF",
57         "lifecycleState": "CERTIFIED",
58         "lastUpdaterUserId": "jh0003"
59     }
60 ]
61 """
62
63
64 def get_artifacts(asset_type):
65     """
66     Get artifacts by given asset type
67     :param asset_type:
68     :return:
69     """
70     resource = "/sdc/v1/catalog/{assetType}"
71     resource = resource.format(assetType=asset_type)
72     ret = call_sdc(resource, "GET")
73     if ret[0] != 0:
74         logger.error("Status code is %s, detail is %s.", ret[2], ret[1])
75         raise CatalogException("Failed to query artifacts(%s) from sdc." % asset_type)
76     return json.JSONDecoder().decode(ret[1])
77
78
79 def get_artifact(asset_type, csar_id):
80     """
81     Get artifact by given asset type and csar id
82     :param asset_type:
83     :param csar_id:
84     :return:
85     """
86     artifacts = get_artifacts(asset_type)
87     for artifact in artifacts:
88         if artifact["uuid"] == csar_id:
89             if asset_type == ASSETTYPE_SERVICES and \
90                     artifact.get("distributionStatus", None) != DISTRIBUTED:
91                 raise CatalogException("The artifact (%s,%s) is not distributed from sdc." % (asset_type, csar_id))
92             else:
93                 return artifact
94     raise CatalogException("Failed to query artifact(%s,%s) from sdc." % (asset_type, csar_id))
95
96
97 def get_asset(asset_type, uuid):
98     """
99     Get asset by given type and UUID
100     :param asset_type:
101     :param uuid:
102     :return:
103     """
104     resource = "/sdc/v1/catalog/{assetType}/{uuid}/metadata".format(assetType=asset_type, uuid=uuid)
105     ret = call_sdc(resource, "GET")
106     if ret[0] != 0:
107         logger.error("Status code is %s, detail is %s.", ret[2], ret[1])
108         raise CatalogException("Failed to get asset(%s, %s) from sdc." % (asset_type, uuid))
109     asset = json.JSONDecoder().decode(ret[1])
110     if len(asset) == 0:
111         raise CatalogException("Failed to get asset(%s, %s) from sdc." % (asset_type, uuid))
112     if asset.get("distributionStatus", None) != DISTRIBUTED:
113         raise CatalogException("The asset (%s,%s) is not distributed from sdc." % (asset_type, uuid))
114     else:
115         return asset
116
117
118 def delete_artifact(asset_type, asset_id, artifact_id):
119     """
120     Delete artifact by conditions from SDC
121     :param asset_type:
122     :param asset_id:
123     :param artifact_id:
124     :return:
125     """
126     resource = "/sdc/v1/catalog/{assetType}/{uuid}/artifacts/{artifactUUID}"
127     resource = resource.format(assetType=asset_type, uuid=asset_id, artifactUUID=artifact_id)
128     ret = call_sdc(resource, "DELETE")
129     if ret[0] != 0:
130         logger.error("Status code is %s, detail is %s.", ret[2], ret[1])
131         raise CatalogException("Failed to delete artifacts(%s) from sdc." % artifact_id)
132     return json.JSONDecoder().decode(ret[1])
133
134
135 def download_artifacts(download_url, local_path, file_name):
136     """
137     Downlaod artifacts from SDC
138     :param download_url:
139     :param local_path:
140     :param file_name:
141     :return:
142     """
143     additional_headers = {
144         'X-ECOMP-InstanceID': 'VFC',
145         'accept': 'application/octet-stream'
146     }
147     ret = restcall.call_req(base_url=SDC_BASE_URL,
148                             user=SDC_USER,
149                             passwd=SDC_PASSWD,
150                             auth_type=restcall.rest_no_auth,
151                             resource=download_url,
152                             method="GET",
153                             additional_headers=additional_headers)
154     if ret[0] != 0:
155         logger.error("Status code is %s, detail is %s.", ret[2], ret[1])
156         raise CatalogException("Failed to download %s from sdc." % download_url)
157     fileutil.make_dirs(local_path)
158     local_file_name = os.path.join(local_path, file_name)
159     local_file = open(local_file_name, 'wb')
160     local_file.write(ret[1])
161     local_file.close()
162     return local_file_name
163
164
165 def create_consumer(name, salt, password):
166     """
167     Create a consumer to access the SDC
168     :param name:
169     :param salt:
170     :param password:
171     :return:
172     """
173     req_data = {
174         'consumerName': name,
175         'consumerSalt': salt,
176         'consumerPassword': password
177     }
178     req_data = json.JSONEncoder().encode(req_data)
179     resource = '/sdc2/rest/v1/consumers'
180     headers = {'USER_ID': 'jh0003'}
181     ret = restcall.call_req(base_url=SDC_BASE_URL,
182                             user="",
183                             passwd="",
184                             auth_type=restcall.rest_no_auth,
185                             resource=resource,
186                             method="POST",
187                             content=req_data,
188                             additional_headers=headers)
189     if ret[0] != 0:
190         logger.error("Status code is %s, detail is %s.", ret[2], ret[1])
191         raise CatalogException("Failed to create consumer from sdc.")
192
193
194 def register_for_topics(key):
195     """
196     Register a topics of SDC
197     :param key:
198     :return:
199     """
200     req_data = {
201         'apiPublicKey': key,
202         'distrEnvName': 'AUTO',
203         'isConsumerToSdcDistrStatusTopic': False,
204         'distEnvEndPoints': []
205     }
206     req_data = json.JSONEncoder().encode(req_data)
207     url = '/sdc/v1/registerForDistribution'
208     ret = call_sdc(url, 'POST', req_data)
209     if ret[0] != 0:
210         logger.error("Status code is %s, detail is %s.", ret[2], ret[1])
211         raise CatalogException("Failed to register from sdc.")
212     return json.JSONDecoder().decode(ret[1])