docker_client.py 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. from __future__ import absolute_import
  2. from __future__ import unicode_literals
  3. import logging
  4. from docker import Client
  5. from docker.errors import TLSParameterError
  6. from docker.tls import TLSConfig
  7. from docker.utils import kwargs_from_env
  8. from requests.utils import urlparse
  9. from ..const import HTTP_TIMEOUT
  10. from .errors import UserError
  11. log = logging.getLogger(__name__)
  12. def tls_config_from_options(options):
  13. tls = options.get('--tls', False)
  14. ca_cert = options.get('--tlscacert')
  15. cert = options.get('--tlscert')
  16. key = options.get('--tlskey')
  17. verify = options.get('--tlsverify')
  18. host = options.get('--host')
  19. skip_hostname_check = options.get('--skip-hostname-check', False)
  20. if not skip_hostname_check:
  21. hostname = urlparse(host).hostname if host else None
  22. # If the protocol is omitted, urlparse fails to extract the hostname.
  23. # Make another attempt by appending a protocol.
  24. if not hostname and host:
  25. hostname = urlparse('tcp://{0}'.format(host)).hostname
  26. advanced_opts = any([ca_cert, cert, key, verify])
  27. if tls is True and not advanced_opts:
  28. return True
  29. elif advanced_opts: # --tls is a noop
  30. client_cert = None
  31. if cert or key:
  32. client_cert = (cert, key)
  33. assert_hostname = None
  34. if skip_hostname_check:
  35. assert_hostname = False
  36. elif hostname:
  37. assert_hostname = hostname
  38. return TLSConfig(
  39. client_cert=client_cert, verify=verify, ca_cert=ca_cert,
  40. assert_hostname=assert_hostname
  41. )
  42. return None
  43. def docker_client(environment, version=None, tls_config=None, host=None):
  44. """
  45. Returns a docker-py client configured using environment variables
  46. according to the same logic as the official Docker client.
  47. """
  48. if 'DOCKER_CLIENT_TIMEOUT' in environment:
  49. log.warn("The DOCKER_CLIENT_TIMEOUT environment variable is deprecated. "
  50. "Please use COMPOSE_HTTP_TIMEOUT instead.")
  51. try:
  52. kwargs = kwargs_from_env(assert_hostname=False, environment=environment)
  53. except TLSParameterError:
  54. raise UserError(
  55. "TLS configuration is invalid - make sure your DOCKER_TLS_VERIFY "
  56. "and DOCKER_CERT_PATH are set correctly.\n"
  57. "You might need to run `eval \"$(docker-machine env default)\"`")
  58. if host:
  59. kwargs['base_url'] = host
  60. if tls_config:
  61. kwargs['tls'] = tls_config
  62. if version:
  63. kwargs['version'] = version
  64. timeout = environment.get('COMPOSE_HTTP_TIMEOUT')
  65. if timeout:
  66. kwargs['timeout'] = int(timeout)
  67. else:
  68. kwargs['timeout'] = HTTP_TIMEOUT
  69. return Client(**kwargs)