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