poolmanager.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456
  1. from __future__ import absolute_import
  2. import collections
  3. import functools
  4. import logging
  5. from ._collections import RecentlyUsedContainer
  6. from .connectionpool import HTTPConnectionPool, HTTPSConnectionPool
  7. from .connectionpool import port_by_scheme
  8. from .exceptions import LocationValueError, MaxRetryError, ProxySchemeUnknown
  9. from .packages import six
  10. from .packages.six.moves.urllib.parse import urljoin
  11. from .request import RequestMethods
  12. from .util.url import parse_url
  13. from .util.retry import Retry
  14. __all__ = ['PoolManager', 'ProxyManager', 'proxy_from_url']
  15. log = logging.getLogger(__name__)
  16. SSL_KEYWORDS = ('key_file', 'cert_file', 'cert_reqs', 'ca_certs',
  17. 'ssl_version', 'ca_cert_dir', 'ssl_context',
  18. 'key_password')
  19. # All known keyword arguments that could be provided to the pool manager, its
  20. # pools, or the underlying connections. This is used to construct a pool key.
  21. _key_fields = (
  22. 'key_scheme', # str
  23. 'key_host', # str
  24. 'key_port', # int
  25. 'key_timeout', # int or float or Timeout
  26. 'key_retries', # int or Retry
  27. 'key_strict', # bool
  28. 'key_block', # bool
  29. 'key_source_address', # str
  30. 'key_key_file', # str
  31. 'key_key_password', # str
  32. 'key_cert_file', # str
  33. 'key_cert_reqs', # str
  34. 'key_ca_certs', # str
  35. 'key_ssl_version', # str
  36. 'key_ca_cert_dir', # str
  37. 'key_ssl_context', # instance of ssl.SSLContext or urllib3.util.ssl_.SSLContext
  38. 'key_maxsize', # int
  39. 'key_headers', # dict
  40. 'key__proxy', # parsed proxy url
  41. 'key__proxy_headers', # dict
  42. 'key_socket_options', # list of (level (int), optname (int), value (int or str)) tuples
  43. 'key__socks_options', # dict
  44. 'key_assert_hostname', # bool or string
  45. 'key_assert_fingerprint', # str
  46. 'key_server_hostname', # str
  47. )
  48. #: The namedtuple class used to construct keys for the connection pool.
  49. #: All custom key schemes should include the fields in this key at a minimum.
  50. PoolKey = collections.namedtuple('PoolKey', _key_fields)
  51. def _default_key_normalizer(key_class, request_context):
  52. """
  53. Create a pool key out of a request context dictionary.
  54. According to RFC 3986, both the scheme and host are case-insensitive.
  55. Therefore, this function normalizes both before constructing the pool
  56. key for an HTTPS request. If you wish to change this behaviour, provide
  57. alternate callables to ``key_fn_by_scheme``.
  58. :param key_class:
  59. The class to use when constructing the key. This should be a namedtuple
  60. with the ``scheme`` and ``host`` keys at a minimum.
  61. :type key_class: namedtuple
  62. :param request_context:
  63. A dictionary-like object that contain the context for a request.
  64. :type request_context: dict
  65. :return: A namedtuple that can be used as a connection pool key.
  66. :rtype: PoolKey
  67. """
  68. # Since we mutate the dictionary, make a copy first
  69. context = request_context.copy()
  70. context['scheme'] = context['scheme'].lower()
  71. context['host'] = context['host'].lower()
  72. # These are both dictionaries and need to be transformed into frozensets
  73. for key in ('headers', '_proxy_headers', '_socks_options'):
  74. if key in context and context[key] is not None:
  75. context[key] = frozenset(context[key].items())
  76. # The socket_options key may be a list and needs to be transformed into a
  77. # tuple.
  78. socket_opts = context.get('socket_options')
  79. if socket_opts is not None:
  80. context['socket_options'] = tuple(socket_opts)
  81. # Map the kwargs to the names in the namedtuple - this is necessary since
  82. # namedtuples can't have fields starting with '_'.
  83. for key in list(context.keys()):
  84. context['key_' + key] = context.pop(key)
  85. # Default to ``None`` for keys missing from the context
  86. for field in key_class._fields:
  87. if field not in context:
  88. context[field] = None
  89. return key_class(**context)
  90. #: A dictionary that maps a scheme to a callable that creates a pool key.
  91. #: This can be used to alter the way pool keys are constructed, if desired.
  92. #: Each PoolManager makes a copy of this dictionary so they can be configured
  93. #: globally here, or individually on the instance.
  94. key_fn_by_scheme = {
  95. 'http': functools.partial(_default_key_normalizer, PoolKey),
  96. 'https': functools.partial(_default_key_normalizer, PoolKey),
  97. }
  98. pool_classes_by_scheme = {
  99. 'http': HTTPConnectionPool,
  100. 'https': HTTPSConnectionPool,
  101. }
  102. class PoolManager(RequestMethods):
  103. """
  104. Allows for arbitrary requests while transparently keeping track of
  105. necessary connection pools for you.
  106. :param num_pools:
  107. Number of connection pools to cache before discarding the least
  108. recently used pool.
  109. :param headers:
  110. Headers to include with all requests, unless other headers are given
  111. explicitly.
  112. :param \\**connection_pool_kw:
  113. Additional parameters are used to create fresh
  114. :class:`urllib3.connectionpool.ConnectionPool` instances.
  115. Example::
  116. >>> manager = PoolManager(num_pools=2)
  117. >>> r = manager.request('GET', 'http://google.com/')
  118. >>> r = manager.request('GET', 'http://google.com/mail')
  119. >>> r = manager.request('GET', 'http://yahoo.com/')
  120. >>> len(manager.pools)
  121. 2
  122. """
  123. proxy = None
  124. def __init__(self, num_pools=10, headers=None, **connection_pool_kw):
  125. RequestMethods.__init__(self, headers)
  126. self.connection_pool_kw = connection_pool_kw
  127. self.pools = RecentlyUsedContainer(num_pools,
  128. dispose_func=lambda p: p.close())
  129. # Locally set the pool classes and keys so other PoolManagers can
  130. # override them.
  131. self.pool_classes_by_scheme = pool_classes_by_scheme
  132. self.key_fn_by_scheme = key_fn_by_scheme.copy()
  133. def __enter__(self):
  134. return self
  135. def __exit__(self, exc_type, exc_val, exc_tb):
  136. self.clear()
  137. # Return False to re-raise any potential exceptions
  138. return False
  139. def _new_pool(self, scheme, host, port, request_context=None):
  140. """
  141. Create a new :class:`ConnectionPool` based on host, port, scheme, and
  142. any additional pool keyword arguments.
  143. If ``request_context`` is provided, it is provided as keyword arguments
  144. to the pool class used. This method is used to actually create the
  145. connection pools handed out by :meth:`connection_from_url` and
  146. companion methods. It is intended to be overridden for customization.
  147. """
  148. pool_cls = self.pool_classes_by_scheme[scheme]
  149. if request_context is None:
  150. request_context = self.connection_pool_kw.copy()
  151. # Although the context has everything necessary to create the pool,
  152. # this function has historically only used the scheme, host, and port
  153. # in the positional args. When an API change is acceptable these can
  154. # be removed.
  155. for key in ('scheme', 'host', 'port'):
  156. request_context.pop(key, None)
  157. if scheme == 'http':
  158. for kw in SSL_KEYWORDS:
  159. request_context.pop(kw, None)
  160. return pool_cls(host, port, **request_context)
  161. def clear(self):
  162. """
  163. Empty our store of pools and direct them all to close.
  164. This will not affect in-flight connections, but they will not be
  165. re-used after completion.
  166. """
  167. self.pools.clear()
  168. def connection_from_host(self, host, port=None, scheme='http', pool_kwargs=None):
  169. """
  170. Get a :class:`ConnectionPool` based on the host, port, and scheme.
  171. If ``port`` isn't given, it will be derived from the ``scheme`` using
  172. ``urllib3.connectionpool.port_by_scheme``. If ``pool_kwargs`` is
  173. provided, it is merged with the instance's ``connection_pool_kw``
  174. variable and used to create the new connection pool, if one is
  175. needed.
  176. """
  177. if not host:
  178. raise LocationValueError("No host specified.")
  179. request_context = self._merge_pool_kwargs(pool_kwargs)
  180. request_context['scheme'] = scheme or 'http'
  181. if not port:
  182. port = port_by_scheme.get(request_context['scheme'].lower(), 80)
  183. request_context['port'] = port
  184. request_context['host'] = host
  185. return self.connection_from_context(request_context)
  186. def connection_from_context(self, request_context):
  187. """
  188. Get a :class:`ConnectionPool` based on the request context.
  189. ``request_context`` must at least contain the ``scheme`` key and its
  190. value must be a key in ``key_fn_by_scheme`` instance variable.
  191. """
  192. scheme = request_context['scheme'].lower()
  193. pool_key_constructor = self.key_fn_by_scheme[scheme]
  194. pool_key = pool_key_constructor(request_context)
  195. return self.connection_from_pool_key(pool_key, request_context=request_context)
  196. def connection_from_pool_key(self, pool_key, request_context=None):
  197. """
  198. Get a :class:`ConnectionPool` based on the provided pool key.
  199. ``pool_key`` should be a namedtuple that only contains immutable
  200. objects. At a minimum it must have the ``scheme``, ``host``, and
  201. ``port`` fields.
  202. """
  203. with self.pools.lock:
  204. # If the scheme, host, or port doesn't match existing open
  205. # connections, open a new ConnectionPool.
  206. pool = self.pools.get(pool_key)
  207. if pool:
  208. return pool
  209. # Make a fresh ConnectionPool of the desired type
  210. scheme = request_context['scheme']
  211. host = request_context['host']
  212. port = request_context['port']
  213. pool = self._new_pool(scheme, host, port, request_context=request_context)
  214. self.pools[pool_key] = pool
  215. return pool
  216. def connection_from_url(self, url, pool_kwargs=None):
  217. """
  218. Similar to :func:`urllib3.connectionpool.connection_from_url`.
  219. If ``pool_kwargs`` is not provided and a new pool needs to be
  220. constructed, ``self.connection_pool_kw`` is used to initialize
  221. the :class:`urllib3.connectionpool.ConnectionPool`. If ``pool_kwargs``
  222. is provided, it is used instead. Note that if a new pool does not
  223. need to be created for the request, the provided ``pool_kwargs`` are
  224. not used.
  225. """
  226. u = parse_url(url)
  227. return self.connection_from_host(u.host, port=u.port, scheme=u.scheme,
  228. pool_kwargs=pool_kwargs)
  229. def _merge_pool_kwargs(self, override):
  230. """
  231. Merge a dictionary of override values for self.connection_pool_kw.
  232. This does not modify self.connection_pool_kw and returns a new dict.
  233. Any keys in the override dictionary with a value of ``None`` are
  234. removed from the merged dictionary.
  235. """
  236. base_pool_kwargs = self.connection_pool_kw.copy()
  237. if override:
  238. for key, value in override.items():
  239. if value is None:
  240. try:
  241. del base_pool_kwargs[key]
  242. except KeyError:
  243. pass
  244. else:
  245. base_pool_kwargs[key] = value
  246. return base_pool_kwargs
  247. def urlopen(self, method, url, redirect=True, **kw):
  248. """
  249. Same as :meth:`urllib3.connectionpool.HTTPConnectionPool.urlopen`
  250. with custom cross-host redirect logic and only sends the request-uri
  251. portion of the ``url``.
  252. The given ``url`` parameter must be absolute, such that an appropriate
  253. :class:`urllib3.connectionpool.ConnectionPool` can be chosen for it.
  254. """
  255. u = parse_url(url)
  256. conn = self.connection_from_host(u.host, port=u.port, scheme=u.scheme)
  257. kw['assert_same_host'] = False
  258. kw['redirect'] = False
  259. if 'headers' not in kw:
  260. kw['headers'] = self.headers.copy()
  261. if self.proxy is not None and u.scheme == "http":
  262. response = conn.urlopen(method, url, **kw)
  263. else:
  264. response = conn.urlopen(method, u.request_uri, **kw)
  265. redirect_location = redirect and response.get_redirect_location()
  266. if not redirect_location:
  267. return response
  268. # Support relative URLs for redirecting.
  269. redirect_location = urljoin(url, redirect_location)
  270. # RFC 7231, Section 6.4.4
  271. if response.status == 303:
  272. method = 'GET'
  273. retries = kw.get('retries')
  274. if not isinstance(retries, Retry):
  275. retries = Retry.from_int(retries, redirect=redirect)
  276. # Strip headers marked as unsafe to forward to the redirected location.
  277. # Check remove_headers_on_redirect to avoid a potential network call within
  278. # conn.is_same_host() which may use socket.gethostbyname() in the future.
  279. if (retries.remove_headers_on_redirect
  280. and not conn.is_same_host(redirect_location)):
  281. headers = list(six.iterkeys(kw['headers']))
  282. for header in headers:
  283. if header.lower() in retries.remove_headers_on_redirect:
  284. kw['headers'].pop(header, None)
  285. try:
  286. retries = retries.increment(method, url, response=response, _pool=conn)
  287. except MaxRetryError:
  288. if retries.raise_on_redirect:
  289. raise
  290. return response
  291. kw['retries'] = retries
  292. kw['redirect'] = redirect
  293. log.info("Redirecting %s -> %s", url, redirect_location)
  294. return self.urlopen(method, redirect_location, **kw)
  295. class ProxyManager(PoolManager):
  296. """
  297. Behaves just like :class:`PoolManager`, but sends all requests through
  298. the defined proxy, using the CONNECT method for HTTPS URLs.
  299. :param proxy_url:
  300. The URL of the proxy to be used.
  301. :param proxy_headers:
  302. A dictionary containing headers that will be sent to the proxy. In case
  303. of HTTP they are being sent with each request, while in the
  304. HTTPS/CONNECT case they are sent only once. Could be used for proxy
  305. authentication.
  306. Example:
  307. >>> proxy = urllib3.ProxyManager('http://localhost:3128/')
  308. >>> r1 = proxy.request('GET', 'http://google.com/')
  309. >>> r2 = proxy.request('GET', 'http://httpbin.org/')
  310. >>> len(proxy.pools)
  311. 1
  312. >>> r3 = proxy.request('GET', 'https://httpbin.org/')
  313. >>> r4 = proxy.request('GET', 'https://twitter.com/')
  314. >>> len(proxy.pools)
  315. 3
  316. """
  317. def __init__(self, proxy_url, num_pools=10, headers=None,
  318. proxy_headers=None, **connection_pool_kw):
  319. if isinstance(proxy_url, HTTPConnectionPool):
  320. proxy_url = '%s://%s:%i' % (proxy_url.scheme, proxy_url.host,
  321. proxy_url.port)
  322. proxy = parse_url(proxy_url)
  323. if not proxy.port:
  324. port = port_by_scheme.get(proxy.scheme, 80)
  325. proxy = proxy._replace(port=port)
  326. if proxy.scheme not in ("http", "https"):
  327. raise ProxySchemeUnknown(proxy.scheme)
  328. self.proxy = proxy
  329. self.proxy_headers = proxy_headers or {}
  330. connection_pool_kw['_proxy'] = self.proxy
  331. connection_pool_kw['_proxy_headers'] = self.proxy_headers
  332. super(ProxyManager, self).__init__(
  333. num_pools, headers, **connection_pool_kw)
  334. def connection_from_host(self, host, port=None, scheme='http', pool_kwargs=None):
  335. if scheme == "https":
  336. return super(ProxyManager, self).connection_from_host(
  337. host, port, scheme, pool_kwargs=pool_kwargs)
  338. return super(ProxyManager, self).connection_from_host(
  339. self.proxy.host, self.proxy.port, self.proxy.scheme, pool_kwargs=pool_kwargs)
  340. def _set_proxy_headers(self, url, headers=None):
  341. """
  342. Sets headers needed by proxies: specifically, the Accept and Host
  343. headers. Only sets headers not provided by the user.
  344. """
  345. headers_ = {'Accept': '*/*'}
  346. netloc = parse_url(url).netloc
  347. if netloc:
  348. headers_['Host'] = netloc
  349. if headers:
  350. headers_.update(headers)
  351. return headers_
  352. def urlopen(self, method, url, redirect=True, **kw):
  353. "Same as HTTP(S)ConnectionPool.urlopen, ``url`` must be absolute."
  354. u = parse_url(url)
  355. if u.scheme == "http":
  356. # For proxied HTTPS requests, httplib sets the necessary headers
  357. # on the CONNECT to the proxy. For HTTP, we'll definitely
  358. # need to set 'Host' at the very least.
  359. headers = kw.get('headers', self.headers)
  360. kw['headers'] = self._set_proxy_headers(url, headers)
  361. return super(ProxyManager, self).urlopen(method, url, redirect=redirect, **kw)
  362. def proxy_from_url(url, **kw):
  363. return ProxyManager(proxy_url=url, **kw)