Don't write information to resmanagement
[vfc/nfvo/lcm.git] / lcm / pub / utils / restcall.py
1 # Copyright 2016 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 base64
16 import sys
17 import traceback
18 import logging
19 import urllib.request
20 import urllib.error
21 import urllib.parse
22 import uuid
23 import httplib2
24 import requests
25
26 from lcm.pub.config.config import MSB_BASE_URL
27
28 rest_no_auth, rest_oneway_auth, rest_bothway_auth = 0, 1, 2
29 HTTP_200_OK, HTTP_201_CREATED, HTTP_204_NO_CONTENT, HTTP_202_ACCEPTED = '200', '201', '204', '202'
30 status_ok_list = [HTTP_200_OK, HTTP_201_CREATED, HTTP_204_NO_CONTENT, HTTP_202_ACCEPTED]
31 HTTP_404_NOTFOUND, HTTP_403_FORBIDDEN, HTTP_401_UNAUTHORIZED, HTTP_400_BADREQUEST = '404', '403', '401', '400'
32
33 logger = logging.getLogger(__name__)
34
35
36 def call_req(base_url, user, passwd, auth_type, resource, method, content='', additional_headers={}):
37     callid = str(uuid.uuid1())
38     logger.debug("[%s]call_req('%s','%s','%s',%s,'%s','%s','%s')" % (
39         callid, base_url, user, passwd, auth_type, resource, method, content))
40     ret = None
41     resp_Location = ''
42     resp_status = ''
43     try:
44         full_url = combine_url(base_url, resource)
45         headers = {'content-type': 'application/json', 'accept': 'application/json'}
46         if user:
47             headers['Authorization'] = 'Basic %s' % base64.b64encode(bytes('%s:%s' % (user, passwd), "utf-8")).decode()
48         ca_certs = None
49         if additional_headers:
50             headers.update(additional_headers)
51         for retry_times in range(3):
52             http = httplib2.Http(ca_certs=ca_certs, disable_ssl_certificate_validation=(auth_type == rest_no_auth))
53             http.follow_all_redirects = True
54             try:
55                 resp, resp_content = http.request(full_url, method=method.upper(), body=content, headers=headers)
56                 resp_status, resp_body = resp['status'], resp_content
57                 resp_Location = resp.get('Location', "")
58                 logger.debug("[%s][%d]status=%s)" % (callid, retry_times, resp_status))
59                 if headers['accept'] == 'application/json':
60                     resp_body = resp_content.decode('UTF-8')
61                     logger.debug("resp_body=%s", resp_body)
62                 if resp_status in status_ok_list:
63                     ret = [0, resp_body, resp_status, resp_Location]
64                 else:
65                     ret = [1, resp_body, resp_status, resp_Location]
66                 break
67             except Exception as ex:
68                 if 'httplib.ResponseNotReady' in str(sys.exc_info()):
69                     logger.debug("retry_times=%d", retry_times)
70                     logger.error(traceback.format_exc())
71                     ret = [1, "Unable to connect to %s" % full_url, resp_status, resp_Location]
72                     continue
73                 raise ex
74     except urllib.error.URLError as err:
75         ret = [2, str(err), resp_status, resp_Location]
76     except Exception:
77         logger.error(traceback.format_exc())
78         logger.error("[%s]ret=%s" % (callid, str(sys.exc_info())))
79         res_info = str(sys.exc_info())
80         if 'httplib.ResponseNotReady' in res_info:
81             res_info = "The URL[%s] request failed or is not responding." % full_url
82         ret = [3, res_info, resp_status, resp_Location]
83     except:
84         logger.error(traceback.format_exc())
85         ret = [4, str(sys.exc_info()), resp_status, resp_Location]
86
87     logger.debug("[%s]ret=%s" % (callid, str(ret)))
88     return ret
89
90
91 def req_by_msb(resource, method, content=''):
92     logger.debug("resource: %s, method: %s, content: %s" % (resource, method, content))
93     base_url = MSB_BASE_URL
94     return call_req(base_url, "", "", rest_no_auth, resource, method, content)
95
96
97 def upload_by_msb(resource, method, file_data):
98     headers = {'accept': 'application/json'}
99     full_url = "%s/%s" % (MSB_BASE_URL, resource)
100     r = requests.post(full_url, files=file_data, headers=headers)
101     resp_status, resp_body = str(r.status_code), r.text
102     if resp_status not in status_ok_list:
103         logger.error("Status code is %s, detail is %s.", resp_status, resp_body)
104         return [1, "Failed to upload file.", resp_status]
105     logger.debug("resp_body=%s", resp_body)
106     return [0, resp_body, resp_status]
107
108
109 def combine_url(base_url, resource):
110     full_url = None
111     if base_url.endswith('/') and resource.startswith('/'):
112         full_url = base_url[:-1] + resource
113     elif base_url.endswith('/') and not resource.startswith('/'):
114         full_url = base_url + resource
115     elif not base_url.endswith('/') and resource.startswith('/'):
116         full_url = base_url + resource
117     else:
118         full_url = base_url + '/' + resource
119     return full_url