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