1 # Copyright 2016-2017 ZTE Corporation.
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
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.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
22 from driver.pub.config.config import MSB_SERVICE_IP, MSB_SERVICE_PORT, AAI_BASE_URL, AAI_USER, AAI_PASSWORD
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'
29 logger = logging.getLogger(__name__)
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))
39 full_url = combine_url(base_url, resource)
40 headers = {'content-type': 'application/json', 'accept': 'application/json'}
42 headers['Authorization'] = 'Basic ' + ('%s:%s' % (user, passwd)).encode("base64")
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
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]
54 ret = [1, resp_body, resp_status]
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]
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]
73 logger.error(traceback.format_exc())
74 ret = [4, str(sys.exc_info()), resp_status]
76 logger.debug("[%s]ret=%s" % (callid, str(ret)))
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)
85 def combine_url(base_url, resource):
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
94 full_url = base_url + '/' + resource
97 def call_req_aai(base_url, user, passwd, auth_type, resource, method, content=''):
98 callid = str(uuid.uuid1())
99 logger.debug("[%s]call_req('%s','%s','%s',%s,'%s','%s','%s')" % (
100 callid, base_url, user, passwd, auth_type, resource, method, content))
104 full_url = combine_url(base_url, resource)
105 headers = {'content-type': 'application/json', 'accept': 'application/json',
106 'X-FromAppId': 'VFC-SVNFM-ZTE-DRIVER', 'X-TransactionId': str(uuid.uuid1())}
108 headers['Authorization'] = 'Basic ' + ('%s:%s' % (user, passwd)).encode("base64")
110 for retry_times in range(3):
111 http = httplib2.Http(ca_certs=ca_certs, disable_ssl_certificate_validation=(auth_type == rest_no_auth))
112 http.follow_all_redirects = True
114 resp, resp_content = http.request(full_url, method=method.upper(), body=content, headers=headers)
115 resp_status, resp_body = resp['status'], resp_content.decode('UTF-8')
116 logger.debug("[%s][%d]status=%s,resp_body=%s)" % (callid, retry_times, resp_status, resp_body))
117 if resp_status in status_ok_list:
118 ret = [0, resp_body, resp_status]
120 ret = [1, resp_body, resp_status]
122 except Exception as ex:
123 if 'httplib.ResponseNotReady' in str(sys.exc_info()):
124 logger.debug("retry_times=%d", retry_times)
125 logger.error(traceback.format_exc())
126 ret = [1, "Unable to connect to %s" % full_url, resp_status]
129 except urllib2.URLError as err:
130 ret = [2, str(err), resp_status]
131 except Exception as ex:
132 logger.error(traceback.format_exc())
133 logger.error("[%s]ret=%s" % (callid, str(sys.exc_info())))
134 res_info = str(sys.exc_info())
135 if 'httplib.ResponseNotReady' in res_info:
136 res_info = "The URL[%s] request failed or is not responding." % full_url
137 ret = [3, res_info, resp_status]
139 logger.error(traceback.format_exc())
140 ret = [4, str(sys.exc_info()), resp_status]
142 logger.debug("[%s]ret=%s" % (callid, str(ret)))
145 def call_aai(resource, method, data=''):
146 return call_req_aai(AAI_BASE_URL, AAI_USER, AAI_PASSWORD, rest_no_auth, resource, method, data)