2013-10-04 15:46:41 +02:00
|
|
|
import time
|
2017-08-16 21:39:32 -06:00
|
|
|
import ssl
|
2013-10-04 15:46:41 +02:00
|
|
|
import urllib3
|
2014-11-11 03:20:16 +01:00
|
|
|
from urllib3.exceptions import ReadTimeoutError, SSLError as UrllibSSLError
|
2015-01-29 23:46:01 +01:00
|
|
|
import warnings
|
2013-10-04 15:46:41 +02:00
|
|
|
|
2018-03-04 15:09:40 -08:00
|
|
|
# sentinal value for `verify_certs`.
|
|
|
|
|
# This is used to detect if a user is passing in a value for `verify_certs`
|
|
|
|
|
# so we can raise a warning if using SSL kwargs AND SSLContext.
|
|
|
|
|
VERIFY_CERTS_DEFAULT = None
|
|
|
|
|
|
2016-10-17 14:16:56 +02:00
|
|
|
CA_CERTS = None
|
|
|
|
|
|
|
|
|
|
try:
|
|
|
|
|
import certifi
|
|
|
|
|
CA_CERTS = certifi.where()
|
|
|
|
|
except ImportError:
|
|
|
|
|
pass
|
|
|
|
|
|
2013-10-04 15:46:41 +02:00
|
|
|
from .base import Connection
|
2014-11-11 03:20:16 +01:00
|
|
|
from ..exceptions import ConnectionError, ImproperlyConfigured, ConnectionTimeout, SSLError
|
2014-02-21 16:53:56 +01:00
|
|
|
from ..compat import urlencode
|
2013-10-04 15:46:41 +02:00
|
|
|
|
2017-08-16 21:39:32 -06:00
|
|
|
|
|
|
|
|
def create_ssl_context(**kwargs):
|
|
|
|
|
"""
|
|
|
|
|
A helper function around creating an SSL context
|
|
|
|
|
|
|
|
|
|
https://docs.python.org/3/library/ssl.html#context-creation
|
|
|
|
|
|
|
|
|
|
Accepts kwargs in the same manner as `create_default_context`.
|
|
|
|
|
"""
|
|
|
|
|
ctx = ssl.create_default_context(**kwargs)
|
|
|
|
|
return ctx
|
|
|
|
|
|
|
|
|
|
|
2013-10-04 15:46:41 +02:00
|
|
|
class Urllib3HttpConnection(Connection):
|
|
|
|
|
"""
|
|
|
|
|
Default connection class using the `urllib3` library and the http protocol.
|
|
|
|
|
|
2015-11-19 11:10:07 -06:00
|
|
|
:arg host: hostname of the node (default: localhost)
|
|
|
|
|
:arg port: port to use (integer, default: 9200)
|
|
|
|
|
:arg url_prefix: optional url prefix for elasticsearch
|
|
|
|
|
:arg timeout: default timeout in seconds (float, default: 10)
|
2013-10-04 15:46:41 +02:00
|
|
|
:arg http_auth: optional http auth information as either ':' separated
|
|
|
|
|
string or a tuple
|
|
|
|
|
:arg use_ssl: use ssl for the connection if `True`
|
2014-11-11 03:20:16 +01:00
|
|
|
:arg verify_certs: whether to verify SSL certificates
|
2018-03-04 15:09:40 -08:00
|
|
|
:arg ca_certs: optional path to CA bundle.
|
|
|
|
|
See https://urllib3.readthedocs.io/en/latest/security.html#using-certifi-with-urllib3
|
2014-11-11 03:20:16 +01:00
|
|
|
for instructions how to get default set
|
2014-11-14 15:31:49 +01:00
|
|
|
:arg client_cert: path to the file containing the private key and the
|
2016-01-26 12:41:55 -07:00
|
|
|
certificate, or cert only if using client_key
|
|
|
|
|
:arg client_key: path to the file containing the private key if using
|
|
|
|
|
separate cert and key files (client_cert will contain only the cert)
|
2015-07-06 18:08:56 +02:00
|
|
|
:arg ssl_version: version of the SSL protocol to use. Choices are:
|
|
|
|
|
SSLv23 (default) SSLv2 SSLv3 TLSv1 (see ``PROTOCOL_*`` constants in the
|
|
|
|
|
``ssl`` module for exact options for your environment).
|
2015-11-03 18:43:00 -05:00
|
|
|
:arg ssl_assert_hostname: use hostname verification if not `False`
|
|
|
|
|
:arg ssl_assert_fingerprint: verify the supplied certificate fingerprint if not `None`
|
2016-10-17 17:25:50 +02:00
|
|
|
:arg maxsize: the number of connections which will be kept open to this
|
|
|
|
|
host. See https://urllib3.readthedocs.io/en/1.4/pools.html#api for more
|
|
|
|
|
information.
|
2016-07-12 18:13:11 +02:00
|
|
|
:arg headers: any custom http headers to be add to requests
|
2013-10-04 15:46:41 +02:00
|
|
|
"""
|
2014-11-11 03:20:16 +01:00
|
|
|
def __init__(self, host='localhost', port=9200, http_auth=None,
|
2018-03-04 15:09:40 -08:00
|
|
|
use_ssl=False, verify_certs=VERIFY_CERTS_DEFAULT, ca_certs=None, client_cert=None,
|
2016-01-26 12:41:55 -07:00
|
|
|
client_key=None, ssl_version=None, ssl_assert_hostname=None,
|
2017-08-16 21:39:32 -06:00
|
|
|
ssl_assert_fingerprint=None, maxsize=10, headers=None, ssl_context=None, **kwargs):
|
2014-11-11 03:20:16 +01:00
|
|
|
|
2016-06-20 14:08:36 +03:00
|
|
|
super(Urllib3HttpConnection, self).__init__(host=host, port=port, use_ssl=use_ssl, **kwargs)
|
2016-12-27 16:49:56 +01:00
|
|
|
self.headers = urllib3.make_headers(keep_alive=True)
|
2013-10-04 15:46:41 +02:00
|
|
|
if http_auth is not None:
|
|
|
|
|
if isinstance(http_auth, (tuple, list)):
|
|
|
|
|
http_auth = ':'.join(http_auth)
|
2015-06-22 20:39:58 +02:00
|
|
|
self.headers.update(urllib3.make_headers(basic_auth=http_auth))
|
2013-10-04 15:46:41 +02:00
|
|
|
|
2016-12-27 16:49:56 +01:00
|
|
|
# update headers in lowercase to allow overriding of auth headers
|
|
|
|
|
if headers:
|
|
|
|
|
for k in headers:
|
|
|
|
|
self.headers[k.lower()] = headers[k]
|
|
|
|
|
|
2017-02-08 20:47:57 +01:00
|
|
|
self.headers.setdefault('content-type', 'application/json')
|
2013-10-04 15:46:41 +02:00
|
|
|
pool_class = urllib3.HTTPConnectionPool
|
2014-11-11 03:20:16 +01:00
|
|
|
kw = {}
|
2017-08-16 21:39:32 -06:00
|
|
|
|
|
|
|
|
# if providing an SSL context, raise error if any other SSL related flag is used
|
2018-03-04 15:09:40 -08:00
|
|
|
if ssl_context and ( (verify_certs is not VERIFY_CERTS_DEFAULT) or ca_certs
|
|
|
|
|
or client_cert or client_key or ssl_version):
|
|
|
|
|
warnings.warn("When using `ssl_context`, all other SSL related kwargs are ignored")
|
2017-08-16 21:39:32 -06:00
|
|
|
|
|
|
|
|
# if ssl_context provided use SSL by default
|
2018-03-04 15:09:40 -08:00
|
|
|
if ssl_context and self.use_ssl:
|
2013-10-04 15:46:41 +02:00
|
|
|
pool_class = urllib3.HTTPSConnectionPool
|
2018-03-04 15:09:40 -08:00
|
|
|
kw.update({
|
|
|
|
|
'assert_fingerprint': ssl_assert_fingerprint,
|
|
|
|
|
'ssl_context': ssl_context,
|
|
|
|
|
})
|
|
|
|
|
self.pool = pool_class(host, port=port, timeout=self.timeout, maxsize=maxsize, **kw)
|
2017-08-16 21:39:32 -06:00
|
|
|
|
2018-03-04 15:09:40 -08:00
|
|
|
elif self.use_ssl:
|
|
|
|
|
pool_class = urllib3.HTTPSConnectionPool
|
2015-11-03 18:43:00 -05:00
|
|
|
kw.update({
|
|
|
|
|
'ssl_version': ssl_version,
|
|
|
|
|
'assert_hostname': ssl_assert_hostname,
|
|
|
|
|
'assert_fingerprint': ssl_assert_fingerprint,
|
|
|
|
|
})
|
2018-03-04 15:09:40 -08:00
|
|
|
|
|
|
|
|
# If `verify_certs` is sentinal value, default `verify_certs` to `True`
|
|
|
|
|
if verify_certs is VERIFY_CERTS_DEFAULT:
|
|
|
|
|
verify_certs = True
|
|
|
|
|
|
|
|
|
|
ca_certs = CA_CERTS if ca_certs is None else ca_certs
|
|
|
|
|
if verify_certs:
|
|
|
|
|
if not ca_certs:
|
|
|
|
|
raise ImproperlyConfigured("Root certificates are missing for certificate "
|
|
|
|
|
"validation. Either pass them in using the ca_certs parameter or "
|
|
|
|
|
"install certifi to use it automatically.")
|
|
|
|
|
|
|
|
|
|
kw.update({
|
|
|
|
|
'cert_reqs': 'CERT_REQUIRED',
|
|
|
|
|
'ca_certs': ca_certs,
|
|
|
|
|
'cert_file': client_cert,
|
|
|
|
|
'key_file': client_key,
|
|
|
|
|
})
|
|
|
|
|
else:
|
|
|
|
|
warnings.warn(
|
|
|
|
|
'Connecting to %s using SSL with verify_certs=False is insecure.' % host)
|
|
|
|
|
|
2014-11-11 03:20:16 +01:00
|
|
|
self.pool = pool_class(host, port=port, timeout=self.timeout, maxsize=maxsize, **kw)
|
2013-10-04 15:46:41 +02:00
|
|
|
|
2018-03-04 15:09:40 -08:00
|
|
|
|
2017-07-12 22:34:17 -04:00
|
|
|
def perform_request(self, method, url, params=None, body=None, timeout=None, ignore=(), headers=None):
|
2013-10-04 15:46:41 +02:00
|
|
|
url = self.url_prefix + url
|
|
|
|
|
if params:
|
2014-11-10 23:52:26 +01:00
|
|
|
url = '%s?%s' % (url, urlencode(params))
|
2013-10-04 15:46:41 +02:00
|
|
|
full_url = self.host + url
|
|
|
|
|
|
|
|
|
|
start = time.time()
|
|
|
|
|
try:
|
|
|
|
|
kw = {}
|
|
|
|
|
if timeout:
|
|
|
|
|
kw['timeout'] = timeout
|
2014-10-03 17:32:11 +02:00
|
|
|
|
2015-02-26 14:14:33 -08:00
|
|
|
# in python2 we need to make sure the url and method are not
|
|
|
|
|
# unicode. Otherwise the body will be decoded into unicode too and
|
|
|
|
|
# that will fail (#133, #201).
|
2014-10-01 17:31:38 +02:00
|
|
|
if not isinstance(url, str):
|
|
|
|
|
url = url.encode('utf-8')
|
2015-02-26 14:14:33 -08:00
|
|
|
if not isinstance(method, str):
|
|
|
|
|
method = method.encode('utf-8')
|
2014-10-03 17:32:11 +02:00
|
|
|
|
2018-01-01 15:42:46 +01:00
|
|
|
request_headers = self.headers
|
2017-08-07 23:25:34 -04:00
|
|
|
if headers:
|
2018-01-01 15:42:46 +01:00
|
|
|
request_headers = request_headers.copy()
|
|
|
|
|
request_headers.update(headers)
|
|
|
|
|
response = self.pool.urlopen(method, url, body, retries=False, headers=request_headers, **kw)
|
2013-10-04 15:46:41 +02:00
|
|
|
duration = time.time() - start
|
|
|
|
|
raw_data = response.data.decode('utf-8')
|
|
|
|
|
except Exception as e:
|
2016-10-19 15:12:44 +02:00
|
|
|
self.log_request_fail(method, full_url, url, body, time.time() - start, exception=e)
|
2016-12-15 16:46:05 +11:00
|
|
|
if isinstance(e, UrllibSSLError):
|
|
|
|
|
raise SSLError('N/A', str(e), e)
|
|
|
|
|
if isinstance(e, ReadTimeoutError):
|
|
|
|
|
raise ConnectionTimeout('TIMEOUT', str(e), e)
|
2013-10-04 15:46:41 +02:00
|
|
|
raise ConnectionError('N/A', str(e), e)
|
|
|
|
|
|
2016-12-15 16:46:05 +11:00
|
|
|
# raise errors based on http status codes, let the client handle those if needed
|
2013-10-04 15:46:41 +02:00
|
|
|
if not (200 <= response.status < 300) and response.status not in ignore:
|
2016-10-19 15:12:44 +02:00
|
|
|
self.log_request_fail(method, full_url, url, body, duration, response.status, raw_data)
|
2013-10-04 15:46:41 +02:00
|
|
|
self._raise_error(response.status, raw_data)
|
|
|
|
|
|
|
|
|
|
self.log_request_success(method, full_url, url, body, response.status,
|
|
|
|
|
raw_data, duration)
|
|
|
|
|
|
2013-12-13 19:36:21 +01:00
|
|
|
return response.status, response.getheaders(), raw_data
|
2013-10-04 15:46:41 +02:00
|
|
|
|
2016-03-03 19:31:31 -05:00
|
|
|
def close(self):
|
|
|
|
|
"""
|
|
|
|
|
Explicitly closes connection
|
|
|
|
|
"""
|
|
|
|
|
self.pool.close()
|