poolmanager.py 17 KB

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