conftest.py 14 KB

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