HC Test: revert to using restconf over http
[csit.git] / resources / libraries / python / HTTPRequest.py
1 # Copyright (c) 2016 Cisco and/or its affiliates.
2 # Licensed under the Apache License, Version 2.0 (the "License");
3 # you may not use this file except in compliance with the License.
4 # You may obtain a copy of the License at:
5 #
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 # See the License for the specific language governing permissions and
12 # limitations under the License.
13
14 """Implementation of HTTP requests GET, PUT, POST and DELETE used in
15 communication with Honeycomb.
16
17 The HTTP requests are implemented in the class HTTPRequest which uses
18 requests.request.
19 """
20
21 from ipaddress import IPv6Address, AddressValueError
22 from enum import IntEnum, unique
23
24 from robot.api.deco import keyword
25 from robot.api import logger
26 from robot.libraries.BuiltIn import BuiltIn
27
28 from requests import request, RequestException, Timeout, TooManyRedirects, \
29     HTTPError, ConnectionError
30 from requests.auth import HTTPBasicAuth
31
32
33 @unique
34 class HTTPCodes(IntEnum):
35     """HTTP status codes"""
36     OK = 200
37     ACCEPTED = 201
38     UNAUTHORIZED = 401
39     FORBIDDEN = 403
40     NOT_FOUND = 404
41     CONFLICT = 409
42     INTERNAL_SERVER_ERROR = 500
43     SERVICE_UNAVAILABLE = 503
44
45
46 class HTTPRequestError(Exception):
47     """Exception raised by HTTPRequest objects.
48
49     When raising this exception, put this information to the message in this
50     order:
51     - short description of the encountered problem,
52     - relevant messages if there are any collected, e.g., from caught
53       exception,
54     - relevant data if there are any collected.
55     The logging is performed on two levels: 1. error - short description of the
56     problem; 2. debug - detailed information.
57     """
58
59     def __init__(self, msg, details='', enable_logging=True):
60         """Sets the exception message and enables / disables logging.
61
62         It is not wanted to log errors when using these keywords together
63         with keywords like "Wait until keyword succeeds". So you can disable
64         logging by setting enable_logging to False.
65
66         :param msg: Message to be displayed and logged.
67         :param enable_logging: When True, logging is enabled, otherwise
68         logging is disabled.
69         :type msg: str
70         :type enable_logging: bool
71         """
72         super(HTTPRequestError, self).__init__()
73         self._msg = "{0}: {1}".format(self.__class__.__name__, msg)
74         self._details = details
75         if enable_logging:
76             logger.error(self._msg)
77             logger.debug(self._details)
78
79     def __repr__(self):
80         return repr(self._msg)
81
82     def __str__(self):
83         return str(self._msg)
84
85
86 class HTTPRequest(object):
87     """A class implementing HTTP requests GET, PUT, POST and DELETE used in
88     communication with Honeycomb.
89
90     The communication with Honeycomb and processing of all exceptions is done in
91     the method _http_request which uses requests.request to send requests and
92     receive responses. The received status code and content of response are
93     logged on the debug level.
94     All possible exceptions raised by requests.request are also processed there.
95
96     The other methods (get, put, post and delete) use _http_request to send
97     corresponding request.
98
99     These methods must not be used as keywords in tests. Use keywords
100     implemented in the module HoneycombAPIKeywords instead.
101     """
102
103     def __init__(self):
104         pass
105
106     @staticmethod
107     def create_full_url(ip_addr, port, path):
108         """Creates full url including host, port, and path to data.
109
110         :param ip_addr: Server IP.
111         :param port: Communication port.
112         :param path: Path to data.
113         :type ip_addr: str
114         :type port: str or int
115         :type path: str
116         :return: Full url.
117         :rtype: str
118         """
119
120         try:
121             IPv6Address(unicode(ip_addr))
122             # IPv6 address must be in brackets
123             ip_addr = "[{0}]".format(ip_addr)
124         except (AttributeError, AddressValueError):
125             pass
126
127         return "http://{ip}:{port}{path}".format(ip=ip_addr, port=port,
128                                                  path=path)
129
130     @staticmethod
131     def _http_request(method, node, path, enable_logging=True, **kwargs):
132         """Sends specified HTTP request and returns status code and response
133         content.
134
135         :param method: The method to be performed on the resource identified by
136         the given request URI.
137         :param node: Honeycomb node.
138         :param path: URL path, e.g. /index.html.
139         :param enable_logging: Used to suppress errors when checking Honeycomb
140         state during suite setup and teardown.
141         :param kwargs: Named parameters accepted by request.request:
142             params -- (optional) Dictionary or bytes to be sent in the query
143             string for the Request.
144             data -- (optional) Dictionary, bytes, or file-like object to
145             send in the body of the Request.
146             json -- (optional) json data to send in the body of the Request.
147             headers -- (optional) Dictionary of HTTP Headers to send with
148             the Request.
149             cookies -- (optional) Dict or CookieJar object to send with the
150             Request.
151             files -- (optional) Dictionary of 'name': file-like-objects
152             (or {'name': ('filename', fileobj)}) for multipart encoding upload.
153             timeout (float or tuple) -- (optional) How long to wait for the
154             server to send data before giving up, as a float, or a (connect
155             timeout, read timeout) tuple.
156             allow_redirects (bool) -- (optional) Boolean. Set to True if POST/
157             PUT/DELETE redirect following is allowed.
158             proxies -- (optional) Dictionary mapping protocol to the URL of
159             the proxy.
160             verify -- (optional) whether the SSL cert will be verified.
161             A CA_BUNDLE path can also be provided. Defaults to True.
162             stream -- (optional) if False, the response content will be
163             immediately downloaded.
164             cert -- (optional) if String, path to ssl client cert file (.pem).
165             If Tuple, ('cert', 'key') pair.
166         :type method: str
167         :type node: dict
168         :type path: str
169         :type enable_logging: bool
170         :type kwargs: dict
171         :return: Status code and content of response.
172         :rtype: tuple
173         :raises HTTPRequestError: If
174         1. it is not possible to connect,
175         2. invalid HTTP response comes from server,
176         3. request exceeded the configured number of maximum re-directions,
177         4. request timed out,
178         5. there is any other unexpected HTTP request exception.
179         """
180         timeout = kwargs["timeout"]
181
182         if BuiltIn().get_variable_value("${use_odl_client}"):
183             # TODO: node["honeycomb"]["odl_port"]
184             port = 8181
185             odl_url_part = "/network-topology:network-topology/topology/" \
186                            "topology-netconf/node/vpp/yang-ext:mount"
187         else:
188             port = node["honeycomb"]["port"]
189             odl_url_part = ""
190
191         try:
192             path = path.format(odl_url_part=odl_url_part)
193         except KeyError:
194             pass
195
196         url = HTTPRequest.create_full_url(node['host'],
197                                           port,
198                                           path)
199         try:
200             auth = HTTPBasicAuth(node['honeycomb']['user'],
201                                  node['honeycomb']['passwd'])
202             rsp = request(method, url, auth=auth, verify=False, **kwargs)
203
204             logger.debug("Status code: {0}".format(rsp.status_code))
205             logger.debug("Response: {0}".format(rsp.content))
206
207             return rsp.status_code, rsp.content
208
209         except ConnectionError as err:
210             # Switching the logging on / off is needed only for
211             # "requests.ConnectionError"
212             raise HTTPRequestError("Not possible to connect to {0}:{1}.".
213                                    format(node['host'],
214                                           node['honeycomb']['port']),
215                                    repr(err), enable_logging=enable_logging)
216         except HTTPError as err:
217             raise HTTPRequestError("Invalid HTTP response from {0}.".
218                                    format(node['host']), repr(err))
219         except TooManyRedirects as err:
220             raise HTTPRequestError("Request exceeded the configured number "
221                                    "of maximum re-directions.", repr(err))
222         except Timeout as err:
223             raise HTTPRequestError("Request timed out. Timeout is set to {0}.".
224                                    format(timeout), repr(err))
225         except RequestException as err:
226             raise HTTPRequestError("Unexpected HTTP request exception.",
227                                    repr(err))
228
229     @staticmethod
230     @keyword(name="HTTP Get")
231     def get(node, path, headers=None, timeout=10, enable_logging=True):
232         """Sends a GET request and returns the response and status code.
233
234         :param node: Honeycomb node.
235         :param path: URL path, e.g. /index.html.
236         :param headers: Dictionary of HTTP Headers to send with the Request.
237         :param timeout: How long to wait for the server to send data before
238         giving up, as a float, or a (connect timeout, read timeout) tuple.
239         :param enable_logging: Used to suppress errors when checking Honeycomb
240         state during suite setup and teardown. When True, logging is enabled,
241         otherwise logging is disabled.
242         :type node: dict
243         :type path: str
244         :type headers: dict
245         :type timeout: float or tuple
246         :type enable_logging: bool
247         :return: Status code and content of response.
248         :rtype: tuple
249         """
250
251         return HTTPRequest._http_request('GET', node, path,
252                                          enable_logging=enable_logging,
253                                          headers=headers, timeout=timeout)
254
255     @staticmethod
256     @keyword(name="HTTP Put")
257     def put(node, path, headers=None, payload=None, json=None, timeout=10):
258         """Sends a PUT request and returns the response and status code.
259
260         :param node: Honeycomb node.
261         :param path: URL path, e.g. /index.html.
262         :param headers: Dictionary of HTTP Headers to send with the Request.
263         :param payload: Dictionary, bytes, or file-like object to send in
264         the body of the Request.
265         :param json: JSON formatted string to send in the body of the Request.
266         :param timeout: How long to wait for the server to send data before
267         giving up, as a float, or a (connect timeout, read timeout) tuple.
268         :type node: dict
269         :type path: str
270         :type headers: dict
271         :type payload: dict, bytes, or file-like object
272         :type json: str
273         :type timeout: float or tuple
274         :return: Status code and content of response.
275         :rtype: tuple
276         """
277         return HTTPRequest._http_request('PUT', node, path, headers=headers,
278                                          data=payload, json=json,
279                                          timeout=timeout)
280
281     @staticmethod
282     @keyword(name="HTTP Post")
283     def post(node, path, headers=None, payload=None, json=None, timeout=10,
284              enable_logging=True):
285         """Sends a POST request and returns the response and status code.
286
287         :param node: Honeycomb node.
288         :param path: URL path, e.g. /index.html.
289         :param headers: Dictionary of HTTP Headers to send with the Request.
290         :param payload: Dictionary, bytes, or file-like object to send in
291         the body of the Request.
292         :param json: JSON formatted string to send in the body of the Request.
293         :param timeout: How long to wait for the server to send data before
294         giving up, as a float, or a (connect timeout, read timeout) tuple.
295         :param enable_logging: Used to suppress errors when checking ODL
296         state during suite setup and teardown. When True, logging is enabled,
297         otherwise logging is disabled.
298         :type node: dict
299         :type path: str
300         :type headers: dict
301         :type payload: dict, bytes, or file-like object
302         :type json: str
303         :type timeout: float or tuple
304         :type enable_logging: bool
305         :return: Status code and content of response.
306         :rtype: tuple
307         """
308         return HTTPRequest._http_request('POST', node, path,
309                                          enable_logging=enable_logging,
310                                          headers=headers, data=payload,
311                                          json=json, timeout=timeout)
312
313     @staticmethod
314     @keyword(name="HTTP Delete")
315     def delete(node, path, timeout=10):
316         """Sends a DELETE request and returns the response and status code.
317
318         :param node: Honeycomb node.
319         :param path: URL path, e.g. /index.html.
320         :param timeout: How long to wait for the server to send data before
321         giving up, as a float, or a (connect timeout, read timeout) tuple.
322         :type node: dict
323         :type path: str
324         :type timeout: float or tuple
325         :return: Status code and content of response.
326         :rtype: tuple
327         """
328         return HTTPRequest._http_request('DELETE', node, path, timeout=timeout)