bundle.py 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  1. from __future__ import absolute_import
  2. from __future__ import unicode_literals
  3. import json
  4. import logging
  5. import six
  6. from docker.utils import split_command
  7. from docker.utils.ports import split_port
  8. from .cli.errors import UserError
  9. from .config.serialize import denormalize_config
  10. from .network import get_network_defs_for_service
  11. from .service import format_environment
  12. from .service import NoSuchImageError
  13. from .service import parse_repository_tag
  14. log = logging.getLogger(__name__)
  15. SERVICE_KEYS = {
  16. 'working_dir': 'WorkingDir',
  17. 'user': 'User',
  18. 'labels': 'Labels',
  19. }
  20. IGNORED_KEYS = {'build'}
  21. SUPPORTED_KEYS = {
  22. 'image',
  23. 'ports',
  24. 'expose',
  25. 'networks',
  26. 'command',
  27. 'environment',
  28. 'entrypoint',
  29. } | set(SERVICE_KEYS)
  30. VERSION = '0.1'
  31. class NeedsPush(Exception):
  32. def __init__(self, image_name):
  33. self.image_name = image_name
  34. class NeedsPull(Exception):
  35. def __init__(self, image_name):
  36. self.image_name = image_name
  37. class MissingDigests(Exception):
  38. def __init__(self, needs_push, needs_pull):
  39. self.needs_push = needs_push
  40. self.needs_pull = needs_pull
  41. def serialize_bundle(config, image_digests):
  42. return json.dumps(to_bundle(config, image_digests), indent=2, sort_keys=True)
  43. def get_image_digests(project, allow_push=False):
  44. digests = {}
  45. needs_push = set()
  46. needs_pull = set()
  47. for service in project.services:
  48. try:
  49. digests[service.name] = get_image_digest(
  50. service,
  51. allow_push=allow_push,
  52. )
  53. except NeedsPush as e:
  54. needs_push.add(e.image_name)
  55. except NeedsPull as e:
  56. needs_pull.add(e.image_name)
  57. if needs_push or needs_pull:
  58. raise MissingDigests(needs_push, needs_pull)
  59. return digests
  60. def get_image_digest(service, allow_push=False):
  61. if 'image' not in service.options:
  62. raise UserError(
  63. "Service '{s.name}' doesn't define an image tag. An image name is "
  64. "required to generate a proper image digest for the bundle. Specify "
  65. "an image repo and tag with the 'image' option.".format(s=service))
  66. _, _, separator = parse_repository_tag(service.options['image'])
  67. # Compose file already uses a digest, no lookup required
  68. if separator == '@':
  69. return service.options['image']
  70. try:
  71. image = service.image()
  72. except NoSuchImageError:
  73. action = 'build' if 'build' in service.options else 'pull'
  74. raise UserError(
  75. "Image not found for service '{service}'. "
  76. "You might need to run `docker-compose {action} {service}`."
  77. .format(service=service.name, action=action))
  78. if image['RepoDigests']:
  79. # TODO: pick a digest based on the image tag if there are multiple
  80. # digests
  81. return image['RepoDigests'][0]
  82. if 'build' not in service.options:
  83. raise NeedsPull(service.image_name)
  84. if not allow_push:
  85. raise NeedsPush(service.image_name)
  86. return push_image(service)
  87. def push_image(service):
  88. try:
  89. digest = service.push()
  90. except:
  91. log.error(
  92. "Failed to push image for service '{s.name}'. Please use an "
  93. "image tag that can be pushed to a Docker "
  94. "registry.".format(s=service))
  95. raise
  96. if not digest:
  97. raise ValueError("Failed to get digest for %s" % service.name)
  98. repo, _, _ = parse_repository_tag(service.options['image'])
  99. identifier = '{repo}@{digest}'.format(repo=repo, digest=digest)
  100. # only do this if RepoDigests isn't already populated
  101. image = service.image()
  102. if not image['RepoDigests']:
  103. # Pull by digest so that image['RepoDigests'] is populated for next time
  104. # and we don't have to pull/push again
  105. service.client.pull(identifier)
  106. log.info("Stored digest for {}".format(service.image_name))
  107. return identifier
  108. def to_bundle(config, image_digests):
  109. if config.networks:
  110. log.warn("Unsupported top level key 'networks' - ignoring")
  111. if config.volumes:
  112. log.warn("Unsupported top level key 'volumes' - ignoring")
  113. config = denormalize_config(config)
  114. return {
  115. 'Version': VERSION,
  116. 'Services': {
  117. name: convert_service_to_bundle(
  118. name,
  119. service_dict,
  120. image_digests[name],
  121. )
  122. for name, service_dict in config['services'].items()
  123. },
  124. }
  125. def convert_service_to_bundle(name, service_dict, image_digest):
  126. container_config = {'Image': image_digest}
  127. for key, value in service_dict.items():
  128. if key in IGNORED_KEYS:
  129. continue
  130. if key not in SUPPORTED_KEYS:
  131. log.warn("Unsupported key '{}' in services.{} - ignoring".format(key, name))
  132. continue
  133. if key == 'environment':
  134. container_config['Env'] = format_environment({
  135. envkey: envvalue for envkey, envvalue in value.items()
  136. if envvalue
  137. })
  138. continue
  139. if key in SERVICE_KEYS:
  140. container_config[SERVICE_KEYS[key]] = value
  141. continue
  142. set_command_and_args(
  143. container_config,
  144. service_dict.get('entrypoint', []),
  145. service_dict.get('command', []))
  146. container_config['Networks'] = make_service_networks(name, service_dict)
  147. ports = make_port_specs(service_dict)
  148. if ports:
  149. container_config['Ports'] = ports
  150. return container_config
  151. # See https://github.com/docker/swarmkit/blob//agent/exec/container/container.go#L95
  152. def set_command_and_args(config, entrypoint, command):
  153. if isinstance(entrypoint, six.string_types):
  154. entrypoint = split_command(entrypoint)
  155. if isinstance(command, six.string_types):
  156. command = split_command(command)
  157. if entrypoint:
  158. config['Command'] = entrypoint + command
  159. return
  160. if command:
  161. config['Args'] = command
  162. def make_service_networks(name, service_dict):
  163. networks = []
  164. for network_name, network_def in get_network_defs_for_service(service_dict).items():
  165. for key in network_def.keys():
  166. log.warn(
  167. "Unsupported key '{}' in services.{}.networks.{} - ignoring"
  168. .format(key, name, network_name))
  169. networks.append(network_name)
  170. return networks
  171. def make_port_specs(service_dict):
  172. ports = []
  173. internal_ports = [
  174. internal_port
  175. for port_def in service_dict.get('ports', [])
  176. for internal_port in split_port(port_def)[0]
  177. ]
  178. internal_ports += service_dict.get('expose', [])
  179. for internal_port in internal_ports:
  180. spec = make_port_spec(internal_port)
  181. if spec not in ports:
  182. ports.append(spec)
  183. return ports
  184. def make_port_spec(value):
  185. components = six.text_type(value).partition('/')
  186. return {
  187. 'Protocol': components[2] or 'tcp',
  188. 'Port': int(components[0]),
  189. }