docker_client.py 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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 ..const import HTTP_TIMEOUT
  9. from .errors import UserError
  10. from .utils import generate_user_agent
  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. skip_hostname_check = options.get('--skip-hostname-check', False)
  19. advanced_opts = any([ca_cert, cert, key, verify])
  20. if tls is True and not advanced_opts:
  21. return True
  22. elif advanced_opts: # --tls is a noop
  23. client_cert = None
  24. if cert or key:
  25. client_cert = (cert, key)
  26. return TLSConfig(
  27. client_cert=client_cert, verify=verify, ca_cert=ca_cert,
  28. assert_hostname=False if skip_hostname_check else None
  29. )
  30. return None
  31. def docker_client(environment, version=None, tls_config=None, host=None,
  32. tls_version=None):
  33. """
  34. Returns a docker-py client configured using environment variables
  35. according to the same logic as the official Docker client.
  36. """
  37. try:
  38. kwargs = kwargs_from_env(environment=environment, ssl_version=tls_version)
  39. except TLSParameterError:
  40. raise UserError(
  41. "TLS configuration is invalid - make sure your DOCKER_TLS_VERIFY "
  42. "and DOCKER_CERT_PATH are set correctly.\n"
  43. "You might need to run `eval \"$(docker-machine env default)\"`")
  44. if host:
  45. kwargs['base_url'] = host
  46. if tls_config:
  47. kwargs['tls'] = tls_config
  48. if version:
  49. kwargs['version'] = version
  50. timeout = environment.get('COMPOSE_HTTP_TIMEOUT')
  51. if timeout:
  52. kwargs['timeout'] = int(timeout)
  53. else:
  54. kwargs['timeout'] = HTTP_TIMEOUT
  55. kwargs['user_agent'] = generate_user_agent()
  56. return Client(**kwargs)