1. Remove the mandatory dependency on MSB
[modeling/etsicatalog.git] / catalog / pub / utils / restcall.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 base64
16 import logging
17 import sys
18 import traceback
19 import urllib
20 import uuid
21
22 import httplib2
23
24 from catalog.pub.config.config import MSB_BASE_URL
25
26 rest_no_auth, rest_oneway_auth, rest_bothway_auth = 0, 1, 2
27 HTTP_200_OK, HTTP_201_CREATED, HTTP_204_NO_CONTENT, HTTP_202_ACCEPTED = '200', '201', '204', '202'
28 status_ok_list = [HTTP_200_OK, HTTP_201_CREATED, HTTP_204_NO_CONTENT, HTTP_202_ACCEPTED]
29 HTTP_404_NOTFOUND, HTTP_403_FORBIDDEN, HTTP_401_UNAUTHORIZED, HTTP_400_BADREQUEST = '404', '403', '401', '400'
30
31 logger = logging.getLogger(__name__)
32
33
34 def call_req(base_url, user, passwd, auth_type, resource, method, content='', additional_headers={}):
35     callid = str(uuid.uuid1())
36     logger.debug("[%s]call_req('%s','%s','%s',%s,'%s','%s','%s')" % (
37         callid, base_url, user, passwd, auth_type, resource, method, content))
38     ret = None
39     resp_status = ''
40     try:
41         full_url = combine_url(base_url, resource)
42         headers = {'content-type': 'application/json', 'accept': 'application/json'}
43         if user:
44             headers['Authorization'] = 'Basic %s' % base64.b64encode(bytes('%s:%s' % (user, passwd), "utf-8")).decode()
45         ca_certs = None
46         if additional_headers:
47             headers.update(additional_headers)
48         for retry_times in range(3):
49             http = httplib2.Http(ca_certs=ca_certs, disable_ssl_certificate_validation=(auth_type == rest_no_auth))
50             http.follow_all_redirects = True
51             try:
52                 resp, resp_content = http.request(full_url, method=method.upper(), body=content, headers=headers)
53                 resp_status, resp_body = resp['status'], resp_content
54                 logger.debug("[%s][%d]status=%s)" % (callid, retry_times, resp_status))
55                 if headers['accept'] == 'application/json':
56                     resp_body = resp_content.decode('UTF-8')
57                     logger.debug("resp_body=%s", resp_body)
58                 if resp_status in status_ok_list:
59                     ret = [0, resp_body, resp_status]
60                 else:
61                     ret = [1, resp_body, resp_status]
62                 break
63             except Exception as ex:
64                 if 'httplib.ResponseNotReady' in str(sys.exc_info()):
65                     logger.debug("retry_times=%d", retry_times)
66                     logger.error(traceback.format_exc())
67                     ret = [1, "Unable to connect to %s" % full_url, resp_status]
68                     continue
69                 raise ex
70     except urllib.error.URLError as err:
71         ret = [2, str(err), resp_status]
72     except Exception:
73         logger.error(traceback.format_exc())
74         logger.error("[%s]ret=%s" % (callid, str(sys.exc_info())))
75         res_info = str(sys.exc_info())
76         if 'httplib.ResponseNotReady' in res_info:
77             res_info = "The URL[%s] request failed or is not responding." % full_url
78         ret = [3, res_info, resp_status]
79     except:
80         logger.error(traceback.format_exc())
81         ret = [4, str(sys.exc_info()), resp_status]
82
83     logger.debug("[%s]ret=%s" % (callid, str(ret)))
84     return ret
85
86
87 def req_by_msb(resource, method, content=''):
88     return call_req(MSB_BASE_URL, "", "", rest_no_auth, resource, method, content)
89
90
91 def upload_by_msb(resource, method, file_data={}):
92     headers = {'Content-Type': 'application/octet-stream'}
93     full_url = "%s/%s" % (MSB_BASE_URL, resource)
94     http = httplib2.Http()
95     resp, resp_content = http.request(full_url, method=method.upper(), body=file_data, headers=headers)
96     resp_status, resp_body = resp['status'], resp_content.decode('UTF-8')
97     if resp_status not in status_ok_list:
98         logger.error("Status code is %s, detail is %s.", resp_status, resp_body)
99         return [1, "Failed to upload file.", resp_status]
100     logger.debug("resp_body=%s", resp_body)
101     return [0, resp_body, resp_status]
102
103
104 def combine_url(base_url, resource):
105     full_url = None
106     if base_url.endswith('/') and resource.startswith('/'):
107         full_url = base_url[:-1] + resource
108     elif base_url.endswith('/') and not resource.startswith('/'):
109         full_url = base_url + resource
110     elif not base_url.endswith('/') and resource.startswith('/'):
111         full_url = base_url + resource
112     else:
113         full_url = base_url + '/' + resource
114     return full_url