dc0b822a54aff160ca455b97b6f0c54e3e64f282
[multicloud/framework.git] / multivimbroker / multivimbroker / pub / utils / restcall.py
1 # Copyright (c) 2017 Wind River Systems, Inc.
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 #       http://www.apache.org/licenses/LICENSE-2.0
7 #
8 # Unless required by applicable law or agreed to in writing, software
9 # distributed under the License is distributed on an "AS IS" BASIS,
10 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11
12 import sys
13 import traceback
14 import logging
15 import urllib2
16 import uuid
17 import httplib2
18
19
20 from multivimbroker.pub.config.config import MSB_SERVICE_IP, MSB_SERVICE_PORT
21
22 rest_no_auth, rest_oneway_auth, rest_bothway_auth = 0, 1, 2
23 HTTP_200_OK, HTTP_201_CREATED, HTTP_204_NO_CONTENT, HTTP_202_ACCEPTED = '200', '201', '204', '202'
24 status_ok_list = [HTTP_200_OK, HTTP_201_CREATED, HTTP_204_NO_CONTENT, HTTP_202_ACCEPTED]
25 HTTP_404_NOTFOUND, HTTP_403_FORBIDDEN, HTTP_401_UNAUTHORIZED, HTTP_400_BADREQUEST = '404', '403', '401', '400'
26
27 logger = logging.getLogger(__name__)
28
29
30 def call_req(base_url, user, passwd, auth_type, resource, method, content='',headers=None):
31     callid = str(uuid.uuid1())
32 #    logger.debug("[%s]call_req('%s','%s','%s',%s,'%s','%s','%s')" % (
33 #        callid, base_url, user, passwd, auth_type, resource, method, content))
34     ret = None
35     resp_status = ''
36     resp = ""
37     full_url = ""
38
39
40     try:
41         full_url = combine_url(base_url, resource)
42         if headers == None:
43             headers = {}
44             headers['content-type']='application/json'
45
46         if user:
47             headers['Authorization'] = 'Basic ' + ('%s:%s' % (user, passwd)).encode("base64")
48         ca_certs = None
49         for retry_times in range(3):
50             http = httplib2.Http(ca_certs=ca_certs, disable_ssl_certificate_validation=(auth_type == rest_no_auth))
51             http.follow_all_redirects = True
52             try:
53                 logger.debug("request=%s)" % full_url)
54                 resp, resp_content = http.request(full_url, method=method.upper(), body=content, headers=headers)
55                 resp_status, resp_body = resp['status'], resp_content.decode('UTF-8')
56
57                 if resp_status in status_ok_list:
58                     ret = [0, resp_body, resp_status, resp]
59                 else:
60                     ret = [1, resp_body, resp_status, resp]
61                 break
62             except Exception as ex:
63                 if 'httplib.ResponseNotReady' in str(sys.exc_info()):
64                     logger.error(traceback.format_exc())
65                     ret = [1, "Unable to connect to %s" % full_url, resp_status, resp]
66                     continue
67                 raise ex
68     except urllib2.URLError as err:
69         ret = [2, str(err), resp_status, resp]
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, resp]
77     except:
78         logger.error(traceback.format_exc())
79         ret = [4, str(sys.exc_info()), resp_status, resp]
80
81 #    logger.debug("[%s]ret=%s" % (callid, str(ret)))
82     return ret
83
84
85 def req_by_msb(resource, method, content='',headers=None):
86     base_url = "http://%s:%s/" % (MSB_SERVICE_IP, MSB_SERVICE_PORT)
87     return call_req(base_url, "", "", rest_no_auth, resource, method, content,headers)
88
89
90 def combine_url(base_url, resource):
91     full_url = None
92     if base_url.endswith('/') and resource.startswith('/'):
93         full_url = base_url[:-1] + resource
94     elif base_url.endswith('/') and not resource.startswith('/'):
95         full_url = base_url + resource
96     elif not base_url.endswith('/') and resource.startswith('/'):
97         full_url = base_url + resource
98     else:
99         full_url = base_url + '/' + resource
100     return full_url