2
0

conftest.py 19 KB

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