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_PROTOCOL
30 from multivimbroker.pub.config.config import MSB_SERVICE_IP, MSB_SERVICE_PORT
32 rest_no_auth, rest_oneway_auth, rest_bothway_auth = 0, 1, 2
33 HTTP_200_OK, HTTP_201_CREATED = '200', '201'
34 HTTP_204_NO_CONTENT, HTTP_202_ACCEPTED = '204', '202'
35 status_ok_list = [HTTP_200_OK, HTTP_201_CREATED,
36 HTTP_204_NO_CONTENT, HTTP_202_ACCEPTED]
37 HTTP_404_NOTFOUND, HTTP_403_FORBIDDEN = '404', '403'
38 HTTP_401_UNAUTHORIZED, HTTP_400_BADREQUEST = '401', '400'
40 logger = logging.getLogger(__name__)
43 def call_multipart_req(base_url, user, passwd, auth_type, resource, method,
44 content, headers=None):
45 callid = str(uuid.uuid1())
46 # logger.debug("[%s]call_req('%s','%s','%s',%s,'%s','%s','%s')" % (
47 # callid, base_url, user, passwd, auth_type, resource, method, content))
53 full_url = combine_url(base_url, resource)
54 logger.debug("request=%s)" % full_url)
55 requestObj = urllib.request.Request(full_url, content, headers)
56 resp = urllib.request.urlopen(requestObj)
57 if resp.code in status_ok_list:
58 ret = [0, resp.read(), resp.code, resp]
60 ret = [1, resp.read(), resp.code, resp]
61 except urllib.error.URLError as err:
62 ret = [2, str(err), 500, resp]
64 logger.error(traceback.format_exc())
65 logger.error("[%s]ret=%s" % (callid, str(sys.exc_info())))
66 res_info = str(sys.exc_info())
67 ret = [3, res_info, 500, resp]
71 def call_req(base_url, user, passwd, auth_type, resource, method,
72 content='', headers=None):
73 callid = str(uuid.uuid1())
74 # logger.debug("[%s]call_req('%s','%s','%s',%s,'%s','%s','%s')" % (
75 # callid, base_url, user, passwd, auth_type, resource, method, content))
82 full_url = combine_url(base_url, resource)
85 headers['content-type'] = 'application/json'
88 headers['Authorization'] = 'Basic ' + \
89 base64.b64encode(('%s:%s' % (user, passwd)).encode()).decode()
90 # ('%s:%s' % (user, passwd)).encode("base64")
92 for retry_times in range(3):
95 disable_ssl_certificate_validation=(
96 auth_type == rest_no_auth))
97 http.follow_all_redirects = True
99 logger.debug("request=%s)" % full_url)
100 resp, resp_content = http.request(
101 full_url, method=method.upper(),
102 body=content, headers=headers)
103 resp_status, resp_body = resp['status'], codecs.decode(
104 resp_content, 'UTF-8') if resp_content else None
106 if resp_status in status_ok_list:
107 ret = [0, resp_body, resp_status, resp]
109 ret = [1, resp_body, resp_status, resp]
111 except Exception as ex:
112 if 'httplib.ResponseNotReady' in str(sys.exc_info()):
113 logger.error(traceback.format_exc())
114 ret = [1, "Unable to connect to %s" %
115 full_url, resp_status, resp]
118 except urllib.error.URLError as err:
119 ret = [2, str(err), resp_status, resp]
121 logger.error(traceback.format_exc())
122 logger.error("[%s]ret=%s" % (callid, str(sys.exc_info())))
123 res_info = str(sys.exc_info())
124 if 'httplib.ResponseNotReady' in res_info:
125 res_info = "The URL[%s] request \
126 failed or is not responding." % full_url
127 ret = [3, res_info, resp_status, resp]
129 # logger.debug("[%s]ret=%s" % (callid, str(ret)))
133 def req_by_msb(resource, method, content='', headers=None):
134 base_url = "%s://%s:%s/" % (
135 MSB_SERVICE_PROTOCOL, MSB_SERVICE_IP, MSB_SERVICE_PORT)
136 return call_req(base_url, "", "",
137 rest_no_auth, resource, method, content, headers)
140 def req_by_msb_multipart(resource, method, content, headers=None):
141 base_url = "%s://%s:%s/" % (
142 MSB_SERVICE_PROTOCOL, MSB_SERVICE_IP, MSB_SERVICE_PORT)
143 return call_multipart_req(base_url, "", "",
144 rest_no_auth, resource, method, content, headers)
147 def get_res_from_aai(resource, content=''):
149 'X-FromAppId': 'MultiCloud',
150 'X-TransactionId': '9001',
151 'content-type': 'application/json',
152 'accept': 'application/json'
154 base_url = "%s/%s" % (AAI_SERVICE_URL, AAI_SCHEMA_VERSION)
155 return call_req(base_url, AAI_USERNAME, AAI_PASSWORD, rest_no_auth,
156 resource, "GET", content, headers)
159 def combine_url(base_url, resource):
161 if base_url.endswith('/') and resource.startswith('/'):
162 full_url = base_url[:-1] + resource
163 elif base_url.endswith('/') and not resource.startswith('/'):
164 full_url = base_url + resource
165 elif not base_url.endswith('/') and resource.startswith('/'):
166 full_url = base_url + resource
168 full_url = base_url + '/' + resource