d06818214e015380890b7de1f7d3b62379a6f7e3
[multicloud/framework.git] / multivimbroker / multivimbroker / pub / utils / restcall.py
1 # Copyright (c) 2017 Wind River Systems, Inc.
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at:
6 #       http://www.apache.org/licenses/LICENSE-2.0
7 #
8 # Unless required by applicable law or agreed to in writing, software
9 # distributed under the License is distributed on an "AS IS" BASIS,
10 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11
12 import sys
13 import traceback
14 import logging
15 import urllib2
16 import uuid
17 import httplib2
18
19 from multivimbroker.pub.config.config import AAI_SCHEMA_VERSION
20 from multivimbroker.pub.config.config import AAI_SERVICE_URL
21 from multivimbroker.pub.config.config import AAI_USERNAME
22 from multivimbroker.pub.config.config import AAI_PASSWORD
23 from multivimbroker.pub.config.config import MSB_SERVICE_IP, MSB_SERVICE_PORT
24
25 rest_no_auth, rest_oneway_auth, rest_bothway_auth = 0, 1, 2
26 HTTP_200_OK, HTTP_201_CREATED = '200', '201'
27 HTTP_204_NO_CONTENT, HTTP_202_ACCEPTED = '204', '202'
28 status_ok_list = [HTTP_200_OK, HTTP_201_CREATED,
29                   HTTP_204_NO_CONTENT, HTTP_202_ACCEPTED]
30 HTTP_404_NOTFOUND, HTTP_403_FORBIDDEN = '404', '403'
31 HTTP_401_UNAUTHORIZED, HTTP_400_BADREQUEST = '401', '400'
32
33 logger = logging.getLogger(__name__)
34
35
36 def call_req(base_url, user, passwd, auth_type, resource, method,
37              content='', headers=None):
38     callid = str(uuid.uuid1())
39 #    logger.debug("[%s]call_req('%s','%s','%s',%s,'%s','%s','%s')" % (
40 #    callid, base_url, user, passwd, auth_type, resource, method, content))
41     ret = None
42     resp_status = ''
43     resp = ""
44     full_url = ""
45
46     try:
47         full_url = combine_url(base_url, resource)
48         if headers is None:
49             headers = {}
50             headers['content-type'] = 'application/json'
51
52         if user:
53             headers['Authorization'] = 'Basic ' + \
54                 ('%s:%s' % (user, passwd)).encode("base64")
55         ca_certs = None
56         for retry_times in range(3):
57             http = httplib2.Http(
58                 ca_certs=ca_certs,
59                 disable_ssl_certificate_validation=(
60                     auth_type == rest_no_auth))
61             http.follow_all_redirects = True
62             try:
63                 logger.debug("request=%s)" % full_url)
64                 resp, resp_content = http.request(
65                     full_url, method=method.upper(),
66                     body=content, headers=headers)
67                 resp_status, resp_body = resp['status'], resp_content.decode(
68                     'UTF-8')
69
70                 if resp_status in status_ok_list:
71                     ret = [0, resp_body, resp_status, resp]
72                 else:
73                     ret = [1, resp_body, resp_status, resp]
74                 break
75             except Exception as ex:
76                 if 'httplib.ResponseNotReady' in str(sys.exc_info()):
77                     logger.error(traceback.format_exc())
78                     ret = [1, "Unable to connect to %s" %
79                            full_url, resp_status, resp]
80                     continue
81                 raise ex
82     except urllib2.URLError as err:
83         ret = [2, str(err), resp_status, resp]
84     except Exception:
85         logger.error(traceback.format_exc())
86         logger.error("[%s]ret=%s" % (callid, str(sys.exc_info())))
87         res_info = str(sys.exc_info())
88         if 'httplib.ResponseNotReady' in res_info:
89             res_info = "The URL[%s] request \
90             failed or is not responding." % full_url
91         ret = [3, res_info, resp_status, resp]
92
93 #    logger.debug("[%s]ret=%s" % (callid, str(ret)))
94     return ret
95
96
97 def req_by_msb(resource, method, content='', headers=None):
98     base_url = "http://%s:%s/" % (MSB_SERVICE_IP, MSB_SERVICE_PORT)
99     return call_req(base_url, "", "",
100                     rest_no_auth, resource, method, content, headers)
101
102
103 def get_res_from_aai(resource, content=''):
104     headers = {
105         'X-FromAppId': 'MultiCloud',
106         'X-TransactionId': '9001',
107         'content-type': 'application/json',
108         'accept': 'application/json'
109     }
110     base_url = "%s/%s" % (AAI_SERVICE_URL, AAI_SCHEMA_VERSION)
111     return call_req(base_url, AAI_USERNAME, AAI_PASSWORD, rest_no_auth,
112                     resource, "GET", content, headers)
113
114
115 def combine_url(base_url, resource):
116     full_url = None
117     if base_url.endswith('/') and resource.startswith('/'):
118         full_url = base_url[:-1] + resource
119     elif base_url.endswith('/') and not resource.startswith('/'):
120         full_url = base_url + resource
121     elif not base_url.endswith('/') and resource.startswith('/'):
122         full_url = base_url + resource
123     else:
124         full_url = base_url + '/' + resource
125     return full_url