2
0

conftest.py 18 KB

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