conftest.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334
  1. from __future__ import print_function
  2. import json
  3. import logging
  4. import os
  5. import shlex
  6. import socket
  7. import subprocess
  8. import time
  9. import backoff
  10. import docker
  11. import pytest
  12. import requests
  13. logging.basicConfig(level=logging.INFO)
  14. logging.getLogger('backoff').setLevel(logging.INFO)
  15. logging.getLogger('patched DNS').setLevel(logging.INFO)
  16. CA_ROOT_CERTIFICATE = os.path.join(os.path.dirname(__file__), 'certs/ca-root.crt')
  17. I_AM_RUNNING_INSIDE_A_DOCKER_CONTAINER = os.path.isfile("/.dockerenv")
  18. ###############################################################################
  19. #
  20. # utilities
  21. #
  22. ###############################################################################
  23. class requests_retry_on_error_502(object):
  24. """
  25. Proxy for calling methods of the requests module.
  26. When a HTTP response failed due to HTTP Error 404 or 502, retry up to 30 times.
  27. """
  28. def __init__(self):
  29. self.session = requests.Session()
  30. if os.path.isfile(CA_ROOT_CERTIFICATE):
  31. self.session.verify = CA_ROOT_CERTIFICATE
  32. def get_conf(self):
  33. """
  34. Return the nginx config file
  35. """
  36. docker_client = docker.from_env()
  37. nginx_proxy_containers = docker_client.containers(filters={"ancestor": "jwilder/nginx-proxy:test"})
  38. if len(nginx_proxy_containers) > 1:
  39. pytest.failed("Too many running jwilder/nginx-proxy:test containers")
  40. elif len(nginx_proxy_containers) == 0:
  41. pytest.failed("No running jwilder/nginx-proxy:test container")
  42. return get_nginx_conf_from_container(nginx_proxy_containers[0]['Id'])
  43. def get(self, *args, **kwargs):
  44. @backoff.on_predicate(backoff.constant, lambda r: r.status_code in (404, 502), interval=.3, max_tries=30, jitter=None)
  45. def _get(*args, **kwargs):
  46. return self.session.get(*args, **kwargs)
  47. return _get(*args, **kwargs)
  48. def post(self, *args, **kwargs):
  49. @backoff.on_predicate(backoff.constant, lambda r: r.status_code in (404, 502), interval=.3, max_tries=30, jitter=None)
  50. def _post(*args, **kwargs):
  51. return self.session.post(*args, **kwargs)
  52. return _post(*args, **kwargs)
  53. def put(self, *args, **kwargs):
  54. @backoff.on_predicate(backoff.constant, lambda r: r.status_code in (404, 502), interval=.3, max_tries=30, jitter=None)
  55. def _put(*args, **kwargs):
  56. return self.session.put(*args, **kwargs)
  57. return _put(*args, **kwargs)
  58. def head(self, *args, **kwargs):
  59. @backoff.on_predicate(backoff.constant, lambda r: r.status_code in (404, 502), interval=.3, max_tries=30, jitter=None)
  60. def _head(*args, **kwargs):
  61. return self.session.head(*args, **kwargs)
  62. return _head(*args, **kwargs)
  63. def delete(self, *args, **kwargs):
  64. @backoff.on_predicate(backoff.constant, lambda r: r.status_code in (404, 502), interval=.3, max_tries=30, jitter=None)
  65. def _delete(*args, **kwargs):
  66. return self.session.delete(*args, **kwargs)
  67. return _delete(*args, **kwargs)
  68. def options(self, *args, **kwargs):
  69. @backoff.on_predicate(backoff.constant, lambda r: r.status_code in (404, 502), interval=.3, max_tries=30, jitter=None)
  70. def _options(*args, **kwargs):
  71. return self.session.options(*args, **kwargs)
  72. return _options(*args, **kwargs)
  73. def __getattr__(self, name):
  74. return getattr(requests, name)
  75. def monkey_patch_urllib_dns_resolver():
  76. """
  77. Alter the behavior of the urllib DNS resolver so that any domain name
  78. containing substring 'nginx-proxy' will resolve to the IP address
  79. of the container created from image 'jwilder/nginx-proxy:test'.
  80. """
  81. log = logging.getLogger("patched DNS")
  82. prv_getaddrinfo = socket.getaddrinfo
  83. dns_cache = {}
  84. def new_getaddrinfo(*args):
  85. log.debug("resolving domain name %s" % repr(args))
  86. if 'nginx-proxy' in args[0]:
  87. docker_client = docker.from_env()
  88. net_info = docker_client.containers(filters={"status": "running", "ancestor": "jwilder/nginx-proxy:test"})[0]["NetworkSettings"]["Networks"]
  89. if "bridge" in net_info:
  90. ip = net_info["bridge"]["IPAddress"]
  91. else:
  92. # not default bridge network, fallback on first network defined
  93. network_name = net_info.keys()[0]
  94. ip = net_info[network_name]["IPAddress"]
  95. log.info("resolving domain name %r as IP address is %s" % (args[0], ip))
  96. return [
  97. (socket.AF_INET, socket.SOCK_STREAM, 6, '', (ip, args[1])),
  98. (socket.AF_INET, socket.SOCK_DGRAM, 17, '', (ip, args[1])),
  99. (socket.AF_INET, socket.SOCK_RAW, 0, '', (ip, args[1]))
  100. ]
  101. try:
  102. return dns_cache[args]
  103. except KeyError:
  104. res = prv_getaddrinfo(*args)
  105. dns_cache[args] = res
  106. return res
  107. socket.getaddrinfo = new_getaddrinfo
  108. return prv_getaddrinfo
  109. def restore_urllib_dns_resolver(getaddrinfo_func):
  110. socket.getaddrinfo = getaddrinfo_func
  111. def remove_all_containers():
  112. docker_client = docker.from_env()
  113. for info in docker_client.containers(all=True):
  114. if I_AM_RUNNING_INSIDE_A_DOCKER_CONTAINER and info['Id'].startswith(socket.gethostname()):
  115. continue # pytest is running within a Docker container, so we do not want to remove that particular container
  116. logging.info("removing container %s" % info["Id"])
  117. docker_client.remove_container(info["Id"], v=True, force=True)
  118. def get_nginx_conf_from_container(container_id):
  119. """
  120. return the nginx /etc/nginx/conf.d/default.conf file content from a container
  121. """
  122. import tarfile
  123. from cStringIO import StringIO
  124. docker_client = docker.from_env()
  125. strm, stat = docker_client.get_archive(container_id, '/etc/nginx/conf.d/default.conf')
  126. with tarfile.open(fileobj=StringIO(strm.read())) as tf:
  127. conffile = tf.extractfile('default.conf')
  128. return conffile.read()
  129. def docker_compose_up(compose_file='docker-compose.yml'):
  130. logging.info('docker-compose -f %s up -d' % compose_file)
  131. try:
  132. subprocess.check_output(shlex.split('docker-compose -f %s up -d' % compose_file))
  133. except subprocess.CalledProcessError, e:
  134. logging.error("Error while runninng 'docker-compose -f %s up -d':\n%s" % (compose_file, e.output))
  135. raise
  136. def docker_compose_down(compose_file='docker-compose.yml'):
  137. logging.info('docker-compose -f %s down' % compose_file)
  138. try:
  139. subprocess.check_output(shlex.split('docker-compose -f %s down' % compose_file))
  140. except subprocess.CalledProcessError, e:
  141. logging.error("Error while runninng 'docker-compose -f %s down':\n%s" % (compose_file, e.output))
  142. raise
  143. def wait_for_nginxproxy_to_be_ready():
  144. """
  145. If a one (and only one) container started from image jwilder/nginx-proxy:test is found,
  146. wait for its log to contain substring "Watching docker events"
  147. """
  148. docker_client = docker.from_env()
  149. containers = docker_client.containers(filters={"ancestor": "jwilder/nginx-proxy:test"})
  150. if len(containers) != 1:
  151. return
  152. container = containers[0]
  153. for line in docker_client.logs(container['Id'], stream=True):
  154. if "Watching docker events" in line:
  155. logging.debug("nginx-proxy ready")
  156. break
  157. def find_docker_compose_file(request):
  158. """
  159. helper for fixture functions to figure out the name of the docker-compose file to consider.
  160. - if the test module provides a `docker_compose_file` variable, take that
  161. - else, if a yaml file exists with the same name as the test module (but for the `.yml` extension), use that
  162. - otherwise use `docker-compose.yml`.
  163. """
  164. test_module_dir = os.path.dirname(request.module.__file__)
  165. yml_file = os.path.join(test_module_dir, request.module.__name__ + '.yml')
  166. yaml_file = os.path.join(test_module_dir, request.module.__name__ + '.yaml')
  167. default_file = os.path.join(test_module_dir, 'docker-compose.yml')
  168. docker_compose_file_module_variable = getattr(request.module, "docker_compose_file", None)
  169. if docker_compose_file_module_variable is not None:
  170. docker_compose_file = os.path.join( test_module_dir, docker_compose_file_module_variable)
  171. if not os.path.isfile(docker_compose_file):
  172. raise ValueError("docker compose file %r could not be found. Check your test module `docker_compose_file` variable value." % docker_compose_file)
  173. else:
  174. if os.path.isfile(yml_file):
  175. docker_compose_file = yml_file
  176. elif os.path.isfile(yaml_file):
  177. docker_compose_file = yaml_file
  178. else:
  179. docker_compose_file = default_file
  180. if not os.path.isfile(docker_compose_file):
  181. logging.error("Could not find any docker-compose file named either '{0}.yml', '{0}.yaml' or 'docker-compose.yml'".format(request.module.__name__))
  182. logging.debug("using docker compose file %s" % docker_compose_file)
  183. return docker_compose_file
  184. def check_sut_image():
  185. """
  186. Return True if jwilder/nginx-proxy:test image exists
  187. """
  188. docker_client = docker.from_env()
  189. return any(map(lambda x: "jwilder/nginx-proxy:test" in x.get('RepoTags'), docker_client.images()))
  190. def connect_to_nginxproxy_network():
  191. """
  192. If we are running from a container, connect our container to the first network on the nginx-proxy
  193. container.
  194. :return: the name of the network we were connected to, or None
  195. """
  196. if I_AM_RUNNING_INSIDE_A_DOCKER_CONTAINER:
  197. docker_client = docker.from_env()
  198. # find the jwilder/nginx-proxy:test container
  199. nginx_proxy_containers = docker_client.containers(filters={"ancestor": "jwilder/nginx-proxy:test"})
  200. if len(nginx_proxy_containers) > 1:
  201. pytest.failed("Too many running jwilder/nginx-proxy:test containers")
  202. elif len(nginx_proxy_containers) == 0:
  203. pytest.failed("No running jwilder/nginx-proxy:test container")
  204. # figure out the nginx-proxy container first network (we assume it has only one)
  205. nproxy_network = nginx_proxy_containers[0]["NetworkSettings"]["Networks"].keys()[0]
  206. # figure out our container networks
  207. my_container_info = filter(lambda x: x['Id'].startswith(socket.gethostname()), docker_client.containers())[0]
  208. my_networks = my_container_info["NetworkSettings"]["Networks"].keys()
  209. # make sure our container is connected to the nginx-proxy's network
  210. if nproxy_network not in my_networks:
  211. logging.info("Connecting to the nginx-proxy container's network: %s" % nproxy_network)
  212. docker_client.connect_container_to_network(my_container_info['Id'], nproxy_network)
  213. return nproxy_network
  214. def disconnect_from_network(network=None):
  215. """
  216. If we are running from a container, disconnect our container from the given network.
  217. :param network: name of a docker network to disconnect from
  218. """
  219. if I_AM_RUNNING_INSIDE_A_DOCKER_CONTAINER and network is not None:
  220. docker_client = docker.from_env()
  221. # figure out our container networks
  222. my_container_info = filter(lambda x: x['Id'].startswith(socket.gethostname()), docker_client.containers())[0]
  223. my_networks = my_container_info["NetworkSettings"]["Networks"].keys()
  224. # disconnect our container from the given network
  225. if network in my_networks:
  226. logging.info("Disconnecting from network %s" % network)
  227. docker_client.disconnect_container_from_network(my_container_info['Id'], network)
  228. ###############################################################################
  229. #
  230. # Py.test fixtures
  231. #
  232. ###############################################################################
  233. @pytest.yield_fixture(scope="module")
  234. def docker_compose(request):
  235. """
  236. pytest fixture providing containers described in a docker compose file. After the tests, remove the created containers
  237. A custom docker compose file name can be defined in a variable named `docker_compose_file`.
  238. """
  239. docker_compose_file = find_docker_compose_file(request)
  240. original_dns_resolver = monkey_patch_urllib_dns_resolver()
  241. if not check_sut_image():
  242. pytest.exit("The docker image 'jwilder/nginx-proxy:test' is missing")
  243. remove_all_containers()
  244. docker_compose_up(docker_compose_file)
  245. wait_for_nginxproxy_to_be_ready()
  246. time.sleep(3)
  247. yield
  248. docker_compose_down(docker_compose_file)
  249. restore_urllib_dns_resolver(original_dns_resolver)
  250. @pytest.yield_fixture()
  251. def nginxproxy():
  252. """
  253. Provides the `nginxproxy` object that can be used in the same way the requests module is:
  254. r = nginxproxy.get("http://foo.com")
  255. The difference is that in case an HTTP requests has status code 404 or 502 (which mostly
  256. indicates that nginx has just reloaded), we retry up to 30 times the query
  257. Also, in the case where pytest is running from a docker container, this fixture makes sure
  258. that container will be attached to the jwilder/nginx-proxy:test container's network which
  259. is under test.
  260. """
  261. network = connect_to_nginxproxy_network()
  262. yield requests_retry_on_error_502()
  263. disconnect_from_network(network)
  264. ###############################################################################
  265. #
  266. # Py.test hooks
  267. #
  268. ###############################################################################
  269. # pytest hook to display additionnal stuff in test report
  270. def pytest_runtest_logreport(report):
  271. if report.failed:
  272. docker_client = docker.from_env()
  273. test_containers = docker_client.containers(all=True, filters={"ancestor": "jwilder/nginx-proxy:test"})
  274. for container in test_containers:
  275. report.longrepr.addsection('nginx-proxy logs', docker_client.logs(container['Id']))
  276. report.longrepr.addsection('nginx-proxy conf', get_nginx_conf_from_container(container['Id']))