conftest.py 19 KB

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