conftest.py 21 KB

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