docker_client.py 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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 ..const import IS_WINDOWS_PLATFORM
  10. from .errors import UserError
  11. from .utils import generate_user_agent
  12. from .utils import unquote_path
  13. log = logging.getLogger(__name__)
  14. def tls_config_from_options(options):
  15. tls = options.get('--tls', False)
  16. ca_cert = unquote_path(options.get('--tlscacert'))
  17. cert = unquote_path(options.get('--tlscert'))
  18. key = unquote_path(options.get('--tlskey'))
  19. verify = options.get('--tlsverify')
  20. skip_hostname_check = options.get('--skip-hostname-check', False)
  21. advanced_opts = any([ca_cert, cert, key, verify])
  22. if tls is True and not advanced_opts:
  23. return True
  24. elif advanced_opts: # --tls is a noop
  25. client_cert = None
  26. if cert or key:
  27. client_cert = (cert, key)
  28. return TLSConfig(
  29. client_cert=client_cert, verify=verify, ca_cert=ca_cert,
  30. assert_hostname=False if skip_hostname_check else None
  31. )
  32. return None
  33. def docker_client(environment, version=None, tls_config=None, host=None,
  34. tls_version=None):
  35. """
  36. Returns a docker-py client configured using environment variables
  37. according to the same logic as the official Docker client.
  38. """
  39. try:
  40. kwargs = kwargs_from_env(environment=environment, ssl_version=tls_version)
  41. except TLSParameterError:
  42. raise UserError(
  43. "TLS configuration is invalid - make sure your DOCKER_TLS_VERIFY "
  44. "and DOCKER_CERT_PATH are set correctly.\n"
  45. "You might need to run `eval \"$(docker-machine env default)\"`")
  46. if host:
  47. kwargs['base_url'] = host
  48. if tls_config:
  49. kwargs['tls'] = tls_config
  50. if version:
  51. kwargs['version'] = version
  52. timeout = environment.get('COMPOSE_HTTP_TIMEOUT')
  53. if timeout:
  54. kwargs['timeout'] = int(timeout)
  55. else:
  56. kwargs['timeout'] = HTTP_TIMEOUT
  57. kwargs['user_agent'] = generate_user_agent()
  58. if 'base_url' not in kwargs and IS_WINDOWS_PLATFORM:
  59. # docker-py 1.10 defaults to using npipes, but we don't want that
  60. # change in compose yet - use the default TCP connection instead.
  61. kwargs['base_url'] = 'tcp://127.0.0.1:2375'
  62. return Client(**kwargs)