conftest.py 21 KB

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