conftest.py 22 KB

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