conftest.py 16 KB

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