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