498db8d9ca63001bd8afbe8e320a2b24f68dbd91
[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     resource = "/sdc/v1/catalog/{assetType}"
66     resource = resource.format(assetType=asset_type)
67     ret = call_sdc(resource, "GET")
68     if ret[0] != 0:
69         logger.error("Status code is %s, detail is %s.", ret[2], ret[1])
70         raise CatalogException("Failed to query artifacts(%s) from sdc." % asset_type)
71     return json.JSONDecoder().decode(ret[1])
72
73
74 def get_artifact(asset_type, csar_id):
75     artifacts = get_artifacts(asset_type)
76     for artifact in artifacts:
77         if artifact["uuid"] == csar_id:
78             if asset_type == ASSETTYPE_SERVICES and \
79                     artifact.get("distributionStatus", None) != DISTRIBUTED:
80                 raise CatalogException("The artifact (%s,%s) is not distributed from sdc." % (asset_type, csar_id))
81             else:
82                 return artifact
83     raise CatalogException("Failed to query artifact(%s,%s) from sdc." % (asset_type, csar_id))
84
85
86 def get_asset(asset_type, uuid):
87     resource = "/sdc/v1/catalog/{assetType}/{uuid}/metadata".format(assetType=asset_type, uuid=uuid)
88     ret = call_sdc(resource, "GET")
89     if ret[0] != 0:
90         logger.error("Status code is %s, detail is %s.", ret[2], ret[1])
91         raise CatalogException("Failed to get asset(%s, %s) from sdc." % (asset_type, uuid))
92     asset = json.JSONDecoder().decode(ret[1])
93     if len(asset) == 0:
94         raise CatalogException("Failed to get asset(%s, %s) from sdc." % (asset_type, uuid))
95     if asset.get("distributionStatus", None) != DISTRIBUTED:
96         raise CatalogException("The asset (%s,%s) is not distributed from sdc." % (asset_type, uuid))
97     else:
98         return asset
99
100
101 def delete_artifact(asset_type, asset_id, artifact_id):
102     resource = "/sdc/v1/catalog/{assetType}/{uuid}/artifacts/{artifactUUID}"
103     resource = resource.format(assetType=asset_type, uuid=asset_id, artifactUUID=artifact_id)
104     ret = call_sdc(resource, "DELETE")
105     if ret[0] != 0:
106         logger.error("Status code is %s, detail is %s.", ret[2], ret[1])
107         raise CatalogException("Failed to delete artifacts(%s) from sdc." % artifact_id)
108     return json.JSONDecoder().decode(ret[1])
109
110
111 def download_artifacts(download_url, local_path, file_name):
112     additional_headers = {
113         'X-ECOMP-InstanceID': 'VFC',
114         'accept': 'application/octet-stream'
115     }
116     ret = restcall.call_req(base_url=SDC_BASE_URL,
117                             user=SDC_USER,
118                             passwd=SDC_PASSWD,
119                             auth_type=restcall.rest_no_auth,
120                             resource=download_url,
121                             method="GET",
122                             additional_headers=additional_headers)
123     if ret[0] != 0:
124         logger.error("Status code is %s, detail is %s.", ret[2], ret[1])
125         raise CatalogException("Failed to download %s from sdc." % download_url)
126     fileutil.make_dirs(local_path)
127     local_file_name = os.path.join(local_path, file_name)
128     local_file = open(local_file_name, 'wb')
129     local_file.write(ret[1])
130     local_file.close()
131     return local_file_name
132
133
134 def create_consumer(name, salt, password):
135     req_data = {
136         'consumerName': name,
137         'consumerSalt': salt,
138         'consumerPassword': password
139     }
140     req_data = json.JSONEncoder().encode(req_data)
141     resource = '/sdc2/rest/v1/consumers'
142     headers = {'USER_ID': 'jh0003'}
143     ret = restcall.call_req(base_url=SDC_BASE_URL,
144                             user="",
145                             passwd="",
146                             auth_type=restcall.rest_no_auth,
147                             resource=resource,
148                             method="POST",
149                             content=req_data,
150                             additional_headers=headers)
151     if ret[0] != 0:
152         logger.error("Status code is %s, detail is %s.", ret[2], ret[1])
153         raise CatalogException("Failed to create consumer from sdc.")
154
155
156 def register_for_topics(key):
157     req_data = {
158         'apiPublicKey': key,
159         'distrEnvName': 'AUTO',
160         'isConsumerToSdcDistrStatusTopic': False,
161         'distEnvEndPoints': []
162     }
163     req_data = json.JSONEncoder().encode(req_data)
164     url = '/sdc/v1/registerForDistribution'
165     ret = call_sdc(url, 'POST', req_data)
166     if ret[0] != 0:
167         logger.error("Status code is %s, detail is %s.", ret[2], ret[1])
168         raise CatalogException("Failed to register from sdc.")
169     return json.JSONDecoder().decode(ret[1])