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