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