70708244e97a0b4f960a558dff52a270e8be8181
[multicloud/framework.git] / multivimbroker / multivimbroker / pub / utils / restcall.py
1 # Copyright (c) 2017 Wind River Systems, Inc.
2 # Copyright (c) 2017-2018 VMware, Inc.
3 #
4 # Licensed under the Apache License, Version 2.0 (the "License");
5 # you may not use this file except in compliance with the License.
6 # You may obtain a copy of the License at:
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
13 import sys
14 import traceback
15 import logging
16 # import urllib2
17 import urllib.request
18 import urllib.parse
19 import urllib.error
20 import uuid
21 import httplib2
22 import base64
23 import codecs
24
25 from multivimbroker.pub.config.config import AAI_SCHEMA_VERSION
26 from multivimbroker.pub.config.config import AAI_SERVICE_URL
27 from multivimbroker.pub.config.config import AAI_USERNAME
28 from multivimbroker.pub.config.config import AAI_PASSWORD
29 from multivimbroker.pub.config.config import MSB_SERVICE_IP, MSB_SERVICE_PORT
30
31 rest_no_auth, rest_oneway_auth, rest_bothway_auth = 0, 1, 2
32 HTTP_200_OK, HTTP_201_CREATED = '200', '201'
33 HTTP_204_NO_CONTENT, HTTP_202_ACCEPTED = '204', '202'
34 status_ok_list = [HTTP_200_OK, HTTP_201_CREATED,
35                   HTTP_204_NO_CONTENT, HTTP_202_ACCEPTED]
36 HTTP_404_NOTFOUND, HTTP_403_FORBIDDEN = '404', '403'
37 HTTP_401_UNAUTHORIZED, HTTP_400_BADREQUEST = '401', '400'
38
39 logger = logging.getLogger(__name__)
40
41
42 def call_multipart_req(base_url, user, passwd, auth_type, resource, method,
43                        content, headers=None):
44     callid = str(uuid.uuid1())
45 #    logger.debug("[%s]call_req('%s','%s','%s',%s,'%s','%s','%s')" % (
46 #    callid, base_url, user, passwd, auth_type, resource, method, content))
47     ret = None
48     resp = ""
49     full_url = ""
50
51     try:
52         full_url = combine_url(base_url, resource)
53         logger.debug("request=%s)" % full_url)
54         requestObj = urllib.request.Request(full_url, content, headers)
55         resp = urllib.request.urlopen(requestObj)
56         if resp.code in status_ok_list:
57             ret = [0, resp.read(), resp.code, resp]
58         else:
59             ret = [1, resp.read(), resp.code, resp]
60     except urllib.error.URLError as err:
61         ret = [2, str(err), 500, resp]
62     except Exception:
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         ret = [3, res_info, 500, resp]
67     return ret
68
69
70 def call_req(base_url, user, passwd, auth_type, resource, method,
71              content='', headers=None):
72     callid = str(uuid.uuid1())
73 #    logger.debug("[%s]call_req('%s','%s','%s',%s,'%s','%s','%s')" % (
74 #    callid, base_url, user, passwd, auth_type, resource, method, content))
75     ret = None
76     resp_status = '500'
77     resp = ""
78     full_url = ""
79
80     try:
81         full_url = combine_url(base_url, resource)
82         if headers is None:
83             headers = {}
84             headers['content-type'] = 'application/json'
85
86         if user:
87             headers['Authorization'] = 'Basic ' + \
88                 base64.b64encode(('%s:%s' % (user, passwd)).encode()).decode()
89 #                ('%s:%s' % (user, passwd)).encode("base64")
90         ca_certs = None
91         for retry_times in range(3):
92             http = httplib2.Http(
93                 ca_certs=ca_certs,
94                 disable_ssl_certificate_validation=(
95                     auth_type == rest_no_auth))
96             http.follow_all_redirects = True
97             try:
98                 logger.debug("request=%s)" % full_url)
99                 resp, resp_content = http.request(
100                     full_url, method=method.upper(),
101                     body=content, headers=headers)
102                 resp_status, resp_body = resp['status'], codecs.decode(
103                     resp_content, 'UTF-8') if resp_content else None
104
105                 if resp_status in status_ok_list:
106                     ret = [0, resp_body, resp_status, resp]
107                 else:
108                     ret = [1, resp_body, resp_status, resp]
109                 break
110             except Exception as ex:
111                 if 'httplib.ResponseNotReady' in str(sys.exc_info()):
112                     logger.error(traceback.format_exc())
113                     ret = [1, "Unable to connect to %s" %
114                            full_url, resp_status, resp]
115                     continue
116                 raise ex
117     except urllib.error.URLError as err:
118         ret = [2, str(err), resp_status, resp]
119     except Exception:
120         logger.error(traceback.format_exc())
121         logger.error("[%s]ret=%s" % (callid, str(sys.exc_info())))
122         res_info = str(sys.exc_info())
123         if 'httplib.ResponseNotReady' in res_info:
124             res_info = "The URL[%s] request \
125             failed or is not responding." % full_url
126         ret = [3, res_info, resp_status, resp]
127
128 #    logger.debug("[%s]ret=%s" % (callid, str(ret)))
129     return ret
130
131
132 def req_by_msb(resource, method, content='', headers=None):
133     base_url = "http://%s:%s/" % (MSB_SERVICE_IP, MSB_SERVICE_PORT)
134     return call_req(base_url, "", "",
135                     rest_no_auth, resource, method, content, headers)
136
137
138 def req_by_msb_multipart(resource, method, content, headers=None):
139     base_url = "http://%s:%s/" % (MSB_SERVICE_IP, MSB_SERVICE_PORT)
140     return call_multipart_req(base_url, "", "",
141                               rest_no_auth, resource, method, content, headers)
142
143
144 def get_res_from_aai(resource, content=''):
145     headers = {
146         'X-FromAppId': 'MultiCloud',
147         'X-TransactionId': '9001',
148         'content-type': 'application/json',
149         'accept': 'application/json'
150     }
151     base_url = "%s/%s" % (AAI_SERVICE_URL, AAI_SCHEMA_VERSION)
152     return call_req(base_url, AAI_USERNAME, AAI_PASSWORD, rest_no_auth,
153                     resource, "GET", content, headers)
154
155
156 def combine_url(base_url, resource):
157     full_url = None
158     if base_url.endswith('/') and resource.startswith('/'):
159         full_url = base_url[:-1] + resource
160     elif base_url.endswith('/') and not resource.startswith('/'):
161         full_url = base_url + resource
162     elif not base_url.endswith('/') and resource.startswith('/'):
163         full_url = base_url + resource
164     else:
165         full_url = base_url + '/' + resource
166     return full_url