conftest.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554
  1. import contextlib
  2. import logging
  3. import os
  4. import re
  5. import shlex
  6. import socket
  7. import subprocess
  8. import time
  9. from typing import List
  10. import backoff
  11. import docker
  12. import pytest
  13. import requests
  14. from _pytest._code.code import ReprExceptionInfo
  15. from distutils.version import LooseVersion
  16. from docker.models.containers import Container
  17. from requests.packages.urllib3.util.connection import HAS_IPV6
  18. logging.basicConfig(level=logging.INFO)
  19. logging.getLogger('backoff').setLevel(logging.INFO)
  20. logging.getLogger('DNS').setLevel(logging.DEBUG)
  21. logging.getLogger('requests.packages.urllib3.connectionpool').setLevel(logging.WARN)
  22. CA_ROOT_CERTIFICATE = os.path.join(os.path.dirname(__file__), 'certs/ca-root.crt')
  23. PYTEST_RUNNING_IN_CONTAINER = os.environ.get('PYTEST_RUNNING_IN_CONTAINER') == "1"
  24. FORCE_CONTAINER_IPV6 = False # ugly global state to consider containers' IPv6 address instead of IPv4
  25. DOCKER_COMPOSE = os.environ.get('DOCKER_COMPOSE', 'docker compose')
  26. docker_client = docker.from_env()
  27. # Name of pytest container to reference if it's being used for running tests
  28. test_container = 'nginx-proxy-pytest'
  29. ###############################################################################
  30. #
  31. # utilities
  32. #
  33. ###############################################################################
  34. @contextlib.contextmanager
  35. def ipv6(force_ipv6=True):
  36. """
  37. Meant to be used as a context manager to force IPv6 sockets:
  38. with ipv6():
  39. nginxproxy.get("http://something.nginx-proxy.example") # force use of IPv6
  40. with ipv6(False):
  41. nginxproxy.get("http://something.nginx-proxy.example") # legacy behavior
  42. """
  43. global FORCE_CONTAINER_IPV6
  44. FORCE_CONTAINER_IPV6 = force_ipv6
  45. yield
  46. FORCE_CONTAINER_IPV6 = False
  47. class requests_for_docker(object):
  48. """
  49. Proxy for calling methods of the requests module.
  50. When a HTTP response failed due to HTTP Error 404 or 502, retry a few times.
  51. Provides method `get_conf` to extract the nginx-proxy configuration content.
  52. """
  53. def __init__(self):
  54. self.session = requests.Session()
  55. if os.path.isfile(CA_ROOT_CERTIFICATE):
  56. self.session.verify = CA_ROOT_CERTIFICATE
  57. @staticmethod
  58. def get_nginx_proxy_containers() -> List[Container]:
  59. """
  60. Return list of containers
  61. """
  62. nginx_proxy_containers = docker_client.containers.list(filters={"ancestor": "nginxproxy/nginx-proxy:test"})
  63. if len(nginx_proxy_containers) > 1:
  64. pytest.fail("Too many running nginxproxy/nginx-proxy:test containers", pytrace=False)
  65. elif len(nginx_proxy_containers) == 0:
  66. pytest.fail("No running nginxproxy/nginx-proxy:test container", pytrace=False)
  67. return nginx_proxy_containers
  68. def get_conf(self):
  69. """
  70. Return the nginx config file
  71. """
  72. nginx_proxy_containers = self.get_nginx_proxy_containers()
  73. return get_nginx_conf_from_container(nginx_proxy_containers[0])
  74. def get_ip(self) -> str:
  75. """
  76. Return the nginx container ip address
  77. """
  78. nginx_proxy_containers = self.get_nginx_proxy_containers()
  79. return container_ip(nginx_proxy_containers[0])
  80. def get(self, *args, **kwargs):
  81. with ipv6(kwargs.pop('ipv6', False)):
  82. @backoff.on_predicate(backoff.constant, lambda r: r.status_code in (404, 502), interval=.3, max_tries=30, jitter=None)
  83. def _get(*args, **kwargs):
  84. return self.session.get(*args, **kwargs)
  85. return _get(*args, **kwargs)
  86. def post(self, *args, **kwargs):
  87. with ipv6(kwargs.pop('ipv6', False)):
  88. @backoff.on_predicate(backoff.constant, lambda r: r.status_code in (404, 502), interval=.3, max_tries=30, jitter=None)
  89. def _post(*args, **kwargs):
  90. return self.session.post(*args, **kwargs)
  91. return _post(*args, **kwargs)
  92. def put(self, *args, **kwargs):
  93. with ipv6(kwargs.pop('ipv6', False)):
  94. @backoff.on_predicate(backoff.constant, lambda r: r.status_code in (404, 502), interval=.3, max_tries=30, jitter=None)
  95. def _put(*args, **kwargs):
  96. return self.session.put(*args, **kwargs)
  97. return _put(*args, **kwargs)
  98. def head(self, *args, **kwargs):
  99. with ipv6(kwargs.pop('ipv6', False)):
  100. @backoff.on_predicate(backoff.constant, lambda r: r.status_code in (404, 502), interval=.3, max_tries=30, jitter=None)
  101. def _head(*args, **kwargs):
  102. return self.session.head(*args, **kwargs)
  103. return _head(*args, **kwargs)
  104. def delete(self, *args, **kwargs):
  105. with ipv6(kwargs.pop('ipv6', False)):
  106. @backoff.on_predicate(backoff.constant, lambda r: r.status_code in (404, 502), interval=.3, max_tries=30, jitter=None)
  107. def _delete(*args, **kwargs):
  108. return self.session.delete(*args, **kwargs)
  109. return _delete(*args, **kwargs)
  110. def options(self, *args, **kwargs):
  111. with ipv6(kwargs.pop('ipv6', False)):
  112. @backoff.on_predicate(backoff.constant, lambda r: r.status_code in (404, 502), interval=.3, max_tries=30, jitter=None)
  113. def _options(*args, **kwargs):
  114. return self.session.options(*args, **kwargs)
  115. return _options(*args, **kwargs)
  116. def __getattr__(self, name):
  117. return getattr(requests, name)
  118. def container_ip(container: Container):
  119. """
  120. return the IP address of a container.
  121. If the global FORCE_CONTAINER_IPV6 flag is set, return the IPv6 address
  122. """
  123. global FORCE_CONTAINER_IPV6
  124. if FORCE_CONTAINER_IPV6:
  125. if not HAS_IPV6:
  126. pytest.skip("This system does not support IPv6")
  127. ip = container_ipv6(container)
  128. if ip == '':
  129. pytest.skip(f"Container {container.name} has no IPv6 address")
  130. else:
  131. return ip
  132. else:
  133. net_info = container.attrs["NetworkSettings"]["Networks"]
  134. if "bridge" in net_info:
  135. return net_info["bridge"]["IPAddress"]
  136. # container is running in host network mode
  137. if "host" in net_info:
  138. return "127.0.0.1"
  139. # not default bridge network, fallback on first network defined
  140. network_name = list(net_info.keys())[0]
  141. return net_info[network_name]["IPAddress"]
  142. def container_ipv6(container):
  143. """
  144. return the IPv6 address of a container.
  145. """
  146. net_info = container.attrs["NetworkSettings"]["Networks"]
  147. if "bridge" in net_info:
  148. return net_info["bridge"]["GlobalIPv6Address"]
  149. # container is running in host network mode
  150. if "host" in net_info:
  151. return "::1"
  152. # not default bridge network, fallback on first network defined
  153. network_name = list(net_info.keys())[0]
  154. return net_info[network_name]["GlobalIPv6Address"]
  155. def nginx_proxy_dns_resolver(domain_name):
  156. """
  157. if "nginx-proxy" if found in host, return the ip address of the docker container
  158. issued from the docker image nginxproxy/nginx-proxy:test.
  159. :return: IP or None
  160. """
  161. log = logging.getLogger('DNS')
  162. log.debug(f"nginx_proxy_dns_resolver({domain_name!r})")
  163. if 'nginx-proxy' in domain_name:
  164. nginxproxy_containers = docker_client.containers.list(filters={"status": "running", "ancestor": "nginxproxy/nginx-proxy:test"})
  165. if len(nginxproxy_containers) == 0:
  166. log.warn(f"no container found from image nginxproxy/nginx-proxy:test while resolving {domain_name!r}")
  167. exited_nginxproxy_containers = docker_client.containers.list(filters={"status": "exited", "ancestor": "nginxproxy/nginx-proxy:test"})
  168. if len(exited_nginxproxy_containers) > 0:
  169. exited_nginxproxy_container_logs = exited_nginxproxy_containers[0].logs()
  170. log.warn(f"nginxproxy/nginx-proxy:test container might have exited unexpectedly. Container logs: " + "\n" + exited_nginxproxy_container_logs.decode())
  171. return
  172. nginxproxy_container = nginxproxy_containers[0]
  173. ip = container_ip(nginxproxy_container)
  174. log.info(f"resolving domain name {domain_name!r} as IP address {ip} of nginx-proxy container {nginxproxy_container.name}")
  175. return ip
  176. def docker_container_dns_resolver(domain_name):
  177. """
  178. if domain name is of the form "XXX.container.docker" or "anything.XXX.container.docker", return the ip address of the docker container
  179. named XXX.
  180. :return: IP or None
  181. """
  182. log = logging.getLogger('DNS')
  183. log.debug(f"docker_container_dns_resolver({domain_name!r})")
  184. match = re.search(r'(^|.+\.)(?P<container>[^.]+)\.container\.docker$', domain_name)
  185. if not match:
  186. log.debug(f"{domain_name!r} does not match")
  187. return
  188. container_name = match.group('container')
  189. log.debug(f"looking for container {container_name!r}")
  190. try:
  191. container = docker_client.containers.get(container_name)
  192. except docker.errors.NotFound:
  193. log.warn(f"container named {container_name!r} not found while resolving {domain_name!r}")
  194. return
  195. log.debug(f"container {container.name!r} found ({container.short_id})")
  196. ip = container_ip(container)
  197. log.info(f"resolving domain name {domain_name!r} as IP address {ip} of container {container.name}")
  198. return ip
  199. def monkey_patch_urllib_dns_resolver():
  200. """
  201. Alter the behavior of the urllib DNS resolver so that any domain name
  202. containing substring 'nginx-proxy' will resolve to the IP address
  203. of the container created from image 'nginxproxy/nginx-proxy:test'.
  204. """
  205. prv_getaddrinfo = socket.getaddrinfo
  206. dns_cache = {}
  207. def new_getaddrinfo(*args):
  208. logging.getLogger('DNS').debug(f"resolving domain name {repr(args)}")
  209. _args = list(args)
  210. # Fail early when querying IP directly and it is forced ipv6 when not supported,
  211. # Otherwise a pytest container not using the host network fails to pass `test_raw-ip-vhost`.
  212. if FORCE_CONTAINER_IPV6 and not HAS_IPV6:
  213. pytest.skip("This system does not support IPv6")
  214. # custom DNS resolvers
  215. ip = nginx_proxy_dns_resolver(args[0])
  216. if ip is None:
  217. ip = docker_container_dns_resolver(args[0])
  218. if ip is not None:
  219. _args[0] = ip
  220. # call on original DNS resolver, with eventually the original host changed to the wanted IP address
  221. try:
  222. return dns_cache[tuple(_args)]
  223. except KeyError:
  224. res = prv_getaddrinfo(*_args)
  225. dns_cache[tuple(_args)] = res
  226. return res
  227. socket.getaddrinfo = new_getaddrinfo
  228. return prv_getaddrinfo
  229. def restore_urllib_dns_resolver(getaddrinfo_func):
  230. socket.getaddrinfo = getaddrinfo_func
  231. def remove_all_containers():
  232. for container in docker_client.containers.list(all=True):
  233. if PYTEST_RUNNING_IN_CONTAINER and container.name == test_container:
  234. continue # pytest is running within a Docker container, so we do not want to remove that particular container
  235. logging.info(f"removing container {container.name}")
  236. container.remove(v=True, force=True)
  237. def get_nginx_conf_from_container(container):
  238. """
  239. return the nginx /etc/nginx/conf.d/default.conf file content from a container
  240. """
  241. import tarfile
  242. from io import BytesIO
  243. strm_generator, stat = container.get_archive('/etc/nginx/conf.d/default.conf')
  244. strm_fileobj = BytesIO(b"".join(strm_generator))
  245. with tarfile.open(fileobj=strm_fileobj) as tf:
  246. conffile = tf.extractfile('default.conf')
  247. return conffile.read()
  248. def docker_compose_up(compose_file='docker-compose.yml'):
  249. logging.info(f'{DOCKER_COMPOSE} -f {compose_file} up -d')
  250. try:
  251. subprocess.check_output(shlex.split(f'{DOCKER_COMPOSE} -f {compose_file} up -d'), stderr=subprocess.STDOUT)
  252. except subprocess.CalledProcessError as e:
  253. pytest.fail(f"Error while runninng '{DOCKER_COMPOSE} -f {compose_file} up -d':\n{e.output}", pytrace=False)
  254. def docker_compose_down(compose_file='docker-compose.yml'):
  255. logging.info(f'{DOCKER_COMPOSE} -f {compose_file} down -v')
  256. try:
  257. subprocess.check_output(shlex.split(f'{DOCKER_COMPOSE} -f {compose_file} down -v'), stderr=subprocess.STDOUT)
  258. except subprocess.CalledProcessError as e:
  259. pytest.fail(f"Error while runninng '{DOCKER_COMPOSE} -f {compose_file} down -v':\n{e.output}", pytrace=False)
  260. def wait_for_nginxproxy_to_be_ready():
  261. """
  262. If one (and only one) container started from image nginxproxy/nginx-proxy:test is found,
  263. wait for its log to contain substring "Watching docker events"
  264. """
  265. containers = docker_client.containers.list(filters={"ancestor": "nginxproxy/nginx-proxy:test"})
  266. if len(containers) != 1:
  267. return
  268. container = containers[0]
  269. for line in container.logs(stream=True):
  270. if b"Watching docker events" in line:
  271. logging.debug("nginx-proxy ready")
  272. break
  273. @pytest.fixture
  274. def docker_compose_file(request):
  275. """Fixture naming the docker compose file to consider.
  276. If a YAML file exists with the same name as the test module (with the `.py` extension replaced
  277. with `.yml` or `.yaml`), use that. Otherwise, use `docker-compose.yml` in the same directory
  278. as the test module.
  279. Tests can override this fixture to specify a custom location.
  280. """
  281. test_module_dir = os.path.dirname(request.module.__file__)
  282. yml_file = os.path.join(test_module_dir, request.module.__name__ + '.yml')
  283. yaml_file = os.path.join(test_module_dir, request.module.__name__ + '.yaml')
  284. default_file = os.path.join(test_module_dir, 'docker-compose.yml')
  285. if os.path.isfile(yml_file):
  286. docker_compose_file = yml_file
  287. elif os.path.isfile(yaml_file):
  288. docker_compose_file = yaml_file
  289. else:
  290. docker_compose_file = default_file
  291. if not os.path.isfile(docker_compose_file):
  292. logging.error("Could not find any docker compose file named either '{0}.yml', '{0}.yaml' or 'docker-compose.yml'".format(request.module.__name__))
  293. logging.debug(f"using docker compose file {docker_compose_file}")
  294. return docker_compose_file
  295. def connect_to_network(network):
  296. """
  297. If we are running from a container, connect our container to the given network
  298. :return: the name of the network we were connected to, or None
  299. """
  300. if PYTEST_RUNNING_IN_CONTAINER:
  301. try:
  302. my_container = docker_client.containers.get(test_container)
  303. except docker.errors.NotFound:
  304. logging.warn(f"container {test_container} not found")
  305. return
  306. # figure out our container networks
  307. my_networks = list(my_container.attrs["NetworkSettings"]["Networks"].keys())
  308. # If the pytest container is using host networking, it cannot connect to container networks (not required with host network)
  309. if 'host' in my_networks:
  310. return None
  311. # Make sure our container is connected to the nginx-proxy's network,
  312. # but avoid connecting to `none` network (not valid) with `test_server-down` tests
  313. if network.name not in my_networks and network.name != 'none':
  314. logging.info(f"Connecting to docker network: {network.name}")
  315. network.connect(my_container)
  316. return network
  317. def disconnect_from_network(network=None):
  318. """
  319. If we are running from a container, disconnect our container from the given network.
  320. :param network: name of a docker network to disconnect from
  321. """
  322. if PYTEST_RUNNING_IN_CONTAINER and network is not None:
  323. try:
  324. my_container = docker_client.containers.get(test_container)
  325. except docker.errors.NotFound:
  326. logging.warn(f"container {test_container} not found")
  327. return
  328. # figure out our container networks
  329. my_networks_names = list(my_container.attrs["NetworkSettings"]["Networks"].keys())
  330. # disconnect our container from the given network
  331. if network.name in my_networks_names:
  332. logging.info(f"Disconnecting from network {network.name}")
  333. network.disconnect(my_container)
  334. def connect_to_all_networks():
  335. """
  336. If we are running from a container, connect our container to all current docker networks.
  337. :return: a list of networks we connected to
  338. """
  339. if not PYTEST_RUNNING_IN_CONTAINER:
  340. return []
  341. else:
  342. # find the list of docker networks
  343. networks = [network for network in docker_client.networks.list(greedy=True) if len(network.containers) > 0 and network.name != 'bridge']
  344. return [connect_to_network(network) for network in networks]
  345. class DockerComposer(contextlib.AbstractContextManager):
  346. def __init__(self):
  347. self._docker_compose_file = None
  348. def __exit__(self, *exc_info):
  349. self._down()
  350. def _down(self):
  351. if self._docker_compose_file is None:
  352. return
  353. for network in self._networks:
  354. disconnect_from_network(network)
  355. docker_compose_down(self._docker_compose_file)
  356. self._docker_compose_file = None
  357. def compose(self, docker_compose_file):
  358. if docker_compose_file == self._docker_compose_file:
  359. return
  360. self._down()
  361. if docker_compose_file is None:
  362. return
  363. remove_all_containers()
  364. docker_compose_up(docker_compose_file)
  365. self._networks = connect_to_all_networks()
  366. wait_for_nginxproxy_to_be_ready()
  367. time.sleep(3) # give time to containers to be ready
  368. self._docker_compose_file = docker_compose_file
  369. ###############################################################################
  370. #
  371. # Py.test fixtures
  372. #
  373. ###############################################################################
  374. @pytest.fixture(scope="module")
  375. def docker_composer():
  376. with DockerComposer() as d:
  377. yield d
  378. @pytest.fixture
  379. def ca_root_certificate():
  380. return CA_ROOT_CERTIFICATE
  381. @pytest.fixture
  382. def monkey_patched_dns():
  383. original_dns_resolver = monkey_patch_urllib_dns_resolver()
  384. yield
  385. restore_urllib_dns_resolver(original_dns_resolver)
  386. @pytest.fixture
  387. def docker_compose(monkey_patched_dns, docker_composer, docker_compose_file):
  388. """Ensures containers described in a docker compose file are started.
  389. A custom docker compose file name can be specified by overriding the `docker_compose_file`
  390. fixture.
  391. Also, in the case where pytest is running from a docker container, this fixture makes sure
  392. our container will be attached to all the docker networks.
  393. """
  394. docker_composer.compose(docker_compose_file)
  395. yield docker_client
  396. @pytest.fixture()
  397. def nginxproxy():
  398. """
  399. Provides the `nginxproxy` object that can be used in the same way the requests module is:
  400. r = nginxproxy.get("http://foo.com")
  401. The difference is that in case an HTTP requests has status code 404 or 502 (which mostly
  402. indicates that nginx has just reloaded), we retry up to 30 times the query.
  403. Also, the nginxproxy methods accept an additional keyword parameter: `ipv6` which forces requests
  404. made against containers to use the containers IPv6 address when set to `True`. If IPv6 is not
  405. supported by the system or docker, that particular test will be skipped.
  406. """
  407. yield requests_for_docker()
  408. ###############################################################################
  409. #
  410. # Py.test hooks
  411. #
  412. ###############################################################################
  413. # pytest hook to display additionnal stuff in test report
  414. def pytest_runtest_logreport(report):
  415. if report.failed:
  416. if isinstance(report.longrepr, ReprExceptionInfo):
  417. test_containers = docker_client.containers.list(all=True, filters={"ancestor": "nginxproxy/nginx-proxy:test"})
  418. for container in test_containers:
  419. report.longrepr.addsection('nginx-proxy logs', container.logs())
  420. report.longrepr.addsection('nginx-proxy conf', get_nginx_conf_from_container(container))
  421. # Py.test `incremental` marker, see http://stackoverflow.com/a/12579625/107049
  422. def pytest_runtest_makereport(item, call):
  423. if "incremental" in item.keywords:
  424. if call.excinfo is not None:
  425. parent = item.parent
  426. parent._previousfailed = item
  427. def pytest_runtest_setup(item):
  428. previousfailed = getattr(item.parent, "_previousfailed", None)
  429. if previousfailed is not None:
  430. pytest.xfail(f"previous test failed ({previousfailed.name})")
  431. ###############################################################################
  432. #
  433. # Check requirements
  434. #
  435. ###############################################################################
  436. try:
  437. docker_client.images.get('nginxproxy/nginx-proxy:test')
  438. except docker.errors.ImageNotFound:
  439. pytest.exit("The docker image 'nginxproxy/nginx-proxy:test' is missing")
  440. if LooseVersion(docker.__version__) < LooseVersion("5.0.0"):
  441. pytest.exit("This test suite is meant to work with the python docker module v5.0.0 or later")