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