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.
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
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'
38 logger = logging.getLogger(__name__)
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))
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]
58 ret = [1, resp.read(), resp.code, resp]
59 except urllib.error.URLError as err:
60 ret = [2, str(err), 500, resp]
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]
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))
80 full_url = combine_url(base_url, resource)
83 headers['content-type'] = 'application/json'
86 headers['Authorization'] = 'Basic ' + \
87 base64.b64encode(('%s:%s' % (user, passwd)).encode()).decode()
88 # ('%s:%s' % (user, passwd)).encode("base64")
90 for retry_times in range(3):
93 disable_ssl_certificate_validation=(
94 auth_type == rest_no_auth))
95 http.follow_all_redirects = True
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
103 if resp_status in status_ok_list:
104 ret = [0, resp_body, resp_status, resp]
106 ret = [1, resp_body, resp_status, resp]
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]
115 except urllib.error.URLError as err:
116 ret = [2, str(err), resp_status, resp]
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]
126 # logger.debug("[%s]ret=%s" % (callid, str(ret)))
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)
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)
142 def get_res_from_aai(resource, content=''):
144 'X-FromAppId': 'MultiCloud',
145 'X-TransactionId': '9001',
146 'content-type': 'application/json',
147 'accept': 'application/json'
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)
154 def combine_url(base_url, resource):
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
163 full_url = base_url + '/' + resource