Setup micro-service of multivim broker
[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                 resp, resp_content = http.request(full_url, method=method.upper(), body=content, headers=headers)
46                 resp_status, resp_body = resp['status'], resp_content.decode('UTF-8')
47                 logger.debug("[%s][%d]status=%s,resp_body=%s)" % (callid, retry_times, resp_status, resp_body))
48                 if resp_status in status_ok_list:
49                     ret = [0, resp_body, resp_status]
50                 else:
51                     ret = [1, resp_body, resp_status]
52                 break
53             except Exception as ex:
54                 if 'httplib.ResponseNotReady' in str(sys.exc_info()):
55                     logger.debug("retry_times=%d", retry_times)
56                     logger.error(traceback.format_exc())
57                     ret = [1, "Unable to connect to %s" % full_url, resp_status]
58                     continue
59                 raise ex
60     except urllib2.URLError as err:
61         ret = [2, str(err), resp_status]
62     except Exception as ex:
63         logger.error(traceback.format_exc())
64         logger.error("[%s]ret=%s" % (callid, str(sys.exc_info())))
65         res_info = str(sys.exc_info())
66         if 'httplib.ResponseNotReady' in res_info:
67             res_info = "The URL[%s] request failed or is not responding." % full_url
68         ret = [3, res_info, resp_status]
69     except:
70         logger.error(traceback.format_exc())
71         ret = [4, str(sys.exc_info()), resp_status]
72
73     logger.debug("[%s]ret=%s" % (callid, str(ret)))
74     return ret
75
76
77 def req_by_msb(resource, method, content=''):
78     base_url = "http://%s:%s/" % (MSB_SERVICE_IP, MSB_SERVICE_PORT)
79     return call_req(base_url, "", "", rest_no_auth, resource, method, content)
80
81
82 def combine_url(base_url, resource):
83     full_url = None
84     if base_url.endswith('/') and resource.startswith('/'):
85         full_url = base_url[:-1] + resource
86     elif base_url.endswith('/') and not resource.startswith('/'):
87         full_url = base_url + resource
88     elif not base_url.endswith('/') and resource.startswith('/'):
89         full_url = base_url + resource
90     else:
91         full_url = base_url + '/' + resource
92     return full_url