b25b389ddff57f51f845095476c43028cbf1499f
[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 = '200', '201'
24 HTTP_204_NO_CONTENT, HTTP_202_ACCEPTED = '204', '202'
25 status_ok_list = [HTTP_200_OK, HTTP_201_CREATED,
26                   HTTP_204_NO_CONTENT, HTTP_202_ACCEPTED]
27 HTTP_404_NOTFOUND, HTTP_403_FORBIDDEN = '404', '403'
28 HTTP_401_UNAUTHORIZED, HTTP_400_BADREQUEST = '401', '400'
29
30 logger = logging.getLogger(__name__)
31
32
33 def call_req(base_url, user, passwd, auth_type, resource, method,
34              content='', headers=None):
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     resp = ""
41     full_url = ""
42
43     try:
44         full_url = combine_url(base_url, resource)
45         if headers is None:
46             headers = {}
47             headers['content-type'] = 'application/json'
48
49         if user:
50             headers['Authorization'] = 'Basic ' + \
51                 ('%s:%s' % (user, passwd)).encode("base64")
52         ca_certs = None
53         for retry_times in range(3):
54             http = httplib2.Http(
55                 ca_certs=ca_certs,
56                 disable_ssl_certificate_validation=(
57                     auth_type == rest_no_auth))
58             http.follow_all_redirects = True
59             try:
60                 logger.debug("request=%s)" % full_url)
61                 resp, resp_content = http.request(
62                     full_url, method=method.upper(),
63                     body=content, headers=headers)
64                 resp_status, resp_body = resp['status'], resp_content.decode(
65                     'UTF-8')
66
67                 if resp_status in status_ok_list:
68                     ret = [0, resp_body, resp_status, resp]
69                 else:
70                     ret = [1, resp_body, resp_status, resp]
71                 break
72             except Exception as ex:
73                 if 'httplib.ResponseNotReady' in str(sys.exc_info()):
74                     logger.error(traceback.format_exc())
75                     ret = [1, "Unable to connect to %s" %
76                            full_url, resp_status, resp]
77                     continue
78                 raise ex
79     except urllib2.URLError as err:
80         ret = [2, str(err), resp_status, resp]
81     except Exception as ex:
82         logger.error(traceback.format_exc())
83         logger.error("[%s]ret=%s" % (callid, str(sys.exc_info())))
84         res_info = str(sys.exc_info())
85         if 'httplib.ResponseNotReady' in res_info:
86             res_info = "The URL[%s] request \
87             failed or is not responding." % full_url
88         ret = [3, res_info, resp_status, resp]
89     except:
90         logger.error(traceback.format_exc())
91         ret = [4, str(sys.exc_info()), resp_status, resp]
92
93 #    logger.debug("[%s]ret=%s" % (callid, str(ret)))
94     return ret
95
96
97 def req_by_msb(resource, method, content='', headers=None):
98     base_url = "http://%s:%s/" % (MSB_SERVICE_IP, MSB_SERVICE_PORT)
99     return call_req(base_url, "", "",
100                     rest_no_auth, resource, method, content, headers)
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