1 # Copyright (c) 2017 Wind River Systems, Inc.
2 # Copyright (c) 2017-2018 VMware, Inc.
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
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.
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
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'
39 logger = logging.getLogger(__name__)
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))
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]
59 ret = [1, resp.read(), resp.code, resp]
60 except urllib.error.URLError as err:
61 ret = [2, str(err), 500, resp]
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]
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))
81 full_url = combine_url(base_url, resource)
84 headers['content-type'] = 'application/json'
87 headers['Authorization'] = 'Basic ' + \
88 base64.b64encode(('%s:%s' % (user, passwd)).encode()).decode()
89 # ('%s:%s' % (user, passwd)).encode("base64")
91 for retry_times in range(3):
94 disable_ssl_certificate_validation=(
95 auth_type == rest_no_auth))
96 http.follow_all_redirects = True
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
105 if resp_status in status_ok_list:
106 ret = [0, resp_body, resp_status, resp]
108 ret = [1, resp_body, resp_status, resp]
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]
117 except urllib.error.URLError as err:
118 ret = [2, str(err), resp_status, resp]
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]
128 # logger.debug("[%s]ret=%s" % (callid, str(ret)))
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)
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)
144 def get_res_from_aai(resource, content=''):
146 'X-FromAppId': 'MultiCloud',
147 'X-TransactionId': '9001',
148 'content-type': 'application/json',
149 'accept': 'application/json'
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)
156 def combine_url(base_url, resource):
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
165 full_url = base_url + '/' + resource