update from python2 to python3
[vfc/gvnfm/vnfmgr.git] / mgr / mgr / 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 sys
17 import traceback
18 import logging
19 import urllib.request
20 import urllib.parse
21 import urllib.error
22 import uuid
23 import httplib2
24
25 from mgr.pub.config.config import MSB_BASE_URL
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=''):
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_status = ''
41     try:
42         full_url = combine_url(base_url, resource)
43         headers = {'content-type': 'application/json', 'accept': 'application/json'}
44         if user:
45             headers['Authorization'] = 'Basic %s' % base64.b64encode(bytes('%s:%s' % (user, passwd), "utf-8")).decode()
46         ca_certs = None
47         for retry_times in range(3):
48             http = httplib2.Http(ca_certs=ca_certs, disable_ssl_certificate_validation=(auth_type == rest_no_auth))
49             http.follow_all_redirects = True
50             try:
51                 resp, resp_content = http.request(full_url, method=method.upper(), body=content, headers=headers)
52                 resp_status, resp_body = resp['status'], resp_content.decode('UTF-8')
53                 logger.debug("[%s][%d]status=%s,resp_body=%s)" % (callid, retry_times, resp_status, resp_body))
54                 if resp_status in status_ok_list:
55                     ret = [0, resp_body, resp_status]
56                 else:
57                     ret = [1, resp_body, resp_status]
58                 break
59             except Exception as ex:
60                 if 'httplib.ResponseNotReady' in str(sys.exc_info()):
61                     logger.debug("retry_times=%d", retry_times)
62                     logger.error(traceback.format_exc())
63                     ret = [1, "Unable to connect to %s" % full_url, resp_status]
64                     continue
65                 raise ex
66     except urllib.error.URLError as err:
67         ret = [2, str(err), resp_status]
68     except Exception as ex:
69         logger.error(traceback.format_exc())
70         logger.error("[%s]ret=%s" % (callid, str(sys.exc_info())))
71         res_info = str(sys.exc_info())
72         if 'httplib.ResponseNotReady' in res_info:
73             res_info = "The URL[%s] request failed or is not responding." % full_url
74         ret = [3, res_info, resp_status]
75         logger.debug(ex)
76
77     logger.debug("[%s]ret=%s" % (callid, str(ret)))
78     return ret
79
80
81 def req_by_msb(resource, method, content=''):
82     base_url = MSB_BASE_URL
83     return call_req(base_url, "", "", rest_no_auth, resource, method, content)
84
85
86 def combine_url(base_url, resource):
87     full_url = None
88     if base_url.endswith('/') and resource.startswith('/'):
89         full_url = base_url[:-1] + resource
90     elif base_url.endswith('/') and not resource.startswith('/'):
91         full_url = base_url + resource
92     elif not base_url.endswith('/') and resource.startswith('/'):
93         full_url = base_url + resource
94     else:
95         full_url = base_url + '/' + resource
96     return full_url