Enable the usage of msb https endpints
[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_PROTOCOL
30 from multivimbroker.pub.config.config import MSB_SERVICE_IP, MSB_SERVICE_PORT
31
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'
39
40 logger = logging.getLogger(__name__)
41
42
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))
48     ret = None
49     resp = ""
50     full_url = ""
51
52     try:
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]
59         else:
60             ret = [1, resp.read(), resp.code, resp]
61     except urllib.error.URLError as err:
62         ret = [2, str(err), 500, resp]
63     except Exception:
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]
68     return ret
69
70
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))
76     ret = None
77     resp_status = '500'
78     resp = ""
79     full_url = ""
80
81     try:
82         full_url = combine_url(base_url, resource)
83         if headers is None:
84             headers = {}
85             headers['content-type'] = 'application/json'
86
87         if user:
88             headers['Authorization'] = 'Basic ' + \
89                 base64.b64encode(('%s:%s' % (user, passwd)).encode()).decode()
90 #                ('%s:%s' % (user, passwd)).encode("base64")
91         ca_certs = None
92         for retry_times in range(3):
93             http = httplib2.Http(
94                 ca_certs=ca_certs,
95                 disable_ssl_certificate_validation=(
96                     auth_type == rest_no_auth))
97             http.follow_all_redirects = True
98             try:
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
105
106                 if resp_status in status_ok_list:
107                     ret = [0, resp_body, resp_status, resp]
108                 else:
109                     ret = [1, resp_body, resp_status, resp]
110                 break
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]
116                     continue
117                 raise ex
118     except urllib.error.URLError as err:
119         ret = [2, str(err), resp_status, resp]
120     except Exception:
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]
128
129 #    logger.debug("[%s]ret=%s" % (callid, str(ret)))
130     return ret
131
132
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)
138
139
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)
145
146
147 def get_res_from_aai(resource, content=''):
148     headers = {
149         'X-FromAppId': 'MultiCloud',
150         'X-TransactionId': '9001',
151         'content-type': 'application/json',
152         'accept': 'application/json'
153     }
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)
157
158
159 def combine_url(base_url, resource):
160     full_url = None
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
167     else:
168         full_url = base_url + '/' + resource
169     return full_url