1
0

migrate-compose-file-v1-to-v2.py 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173
  1. #!/usr/bin/env python
  2. """
  3. Migrate a Compose file from the V1 format in Compose 1.5 to the V2 format
  4. supported by Compose 1.6+
  5. """
  6. from __future__ import absolute_import
  7. from __future__ import unicode_literals
  8. import argparse
  9. import logging
  10. import sys
  11. import ruamel.yaml
  12. from compose.config.types import VolumeSpec
  13. log = logging.getLogger('migrate')
  14. def migrate(content):
  15. data = ruamel.yaml.load(content, ruamel.yaml.RoundTripLoader)
  16. service_names = data.keys()
  17. for name, service in data.items():
  18. warn_for_links(name, service)
  19. warn_for_external_links(name, service)
  20. rewrite_net(service, service_names)
  21. rewrite_build(service)
  22. rewrite_logging(service)
  23. rewrite_volumes_from(service, service_names)
  24. services = {name: data.pop(name) for name in data.keys()}
  25. data['version'] = "2"
  26. data['services'] = services
  27. create_volumes_section(data)
  28. return data
  29. def warn_for_links(name, service):
  30. links = service.get('links')
  31. if links:
  32. example_service = links[0].partition(':')[0]
  33. log.warn(
  34. "Service {name} has links, which no longer create environment "
  35. "variables such as {example_service_upper}_PORT. "
  36. "If you are using those in your application code, you should "
  37. "instead connect directly to the hostname, e.g. "
  38. "'{example_service}'."
  39. .format(name=name, example_service=example_service,
  40. example_service_upper=example_service.upper()))
  41. def warn_for_external_links(name, service):
  42. external_links = service.get('external_links')
  43. if external_links:
  44. log.warn(
  45. "Service {name} has external_links: {ext}, which now work "
  46. "slightly differently. In particular, two containers must be "
  47. "connected to at least one network in common in order to "
  48. "communicate, even if explicitly linked together.\n\n"
  49. "Either connect the external container to your app's default "
  50. "network, or connect both the external container and your "
  51. "service's containers to a pre-existing network. See "
  52. "https://docs.docker.com/compose/networking/ "
  53. "for more on how to do this."
  54. .format(name=name, ext=external_links))
  55. def rewrite_net(service, service_names):
  56. if 'net' in service:
  57. network_mode = service.pop('net')
  58. # "container:<service name>" is now "service:<service name>"
  59. if network_mode.startswith('container:'):
  60. name = network_mode.partition(':')[2]
  61. if name in service_names:
  62. network_mode = 'service:{}'.format(name)
  63. service['network_mode'] = network_mode
  64. def rewrite_build(service):
  65. if 'dockerfile' in service:
  66. service['build'] = {
  67. 'context': service.pop('build'),
  68. 'dockerfile': service.pop('dockerfile'),
  69. }
  70. def rewrite_logging(service):
  71. if 'log_driver' in service:
  72. service['logging'] = {'driver': service.pop('log_driver')}
  73. if 'log_opt' in service:
  74. service['logging']['options'] = service.pop('log_opt')
  75. def rewrite_volumes_from(service, service_names):
  76. for idx, volume_from in enumerate(service.get('volumes_from', [])):
  77. if volume_from.split(':', 1)[0] not in service_names:
  78. service['volumes_from'][idx] = 'container:%s' % volume_from
  79. def create_volumes_section(data):
  80. named_volumes = get_named_volumes(data['services'])
  81. if named_volumes:
  82. log.warn(
  83. "Named volumes ({names}) must be explicitly declared. Creating a "
  84. "'volumes' section with declarations.\n\n"
  85. "For backwards-compatibility, they've been declared as external. "
  86. "If you don't mind the volume names being prefixed with the "
  87. "project name, you can remove the 'external' option from each one."
  88. .format(names=', '.join(list(named_volumes))))
  89. data['volumes'] = named_volumes
  90. def get_named_volumes(services):
  91. volume_specs = [
  92. VolumeSpec.parse(volume)
  93. for service in services.values()
  94. for volume in service.get('volumes', [])
  95. ]
  96. names = {
  97. spec.external
  98. for spec in volume_specs
  99. if spec.is_named_volume
  100. }
  101. return {name: {'external': True} for name in names}
  102. def write(stream, new_format, indent, width):
  103. ruamel.yaml.dump(
  104. new_format,
  105. stream,
  106. Dumper=ruamel.yaml.RoundTripDumper,
  107. indent=indent,
  108. width=width)
  109. def parse_opts(args):
  110. parser = argparse.ArgumentParser()
  111. parser.add_argument("filename", help="Compose file filename.")
  112. parser.add_argument("-i", "--in-place", action='store_true')
  113. parser.add_argument(
  114. "--indent", type=int, default=2,
  115. help="Number of spaces used to indent the output yaml.")
  116. parser.add_argument(
  117. "--width", type=int, default=80,
  118. help="Number of spaces used as the output width.")
  119. return parser.parse_args()
  120. def main(args):
  121. logging.basicConfig(format='\033[33m%(levelname)s:\033[37m %(message)s\033[0m\n')
  122. opts = parse_opts(args)
  123. with open(opts.filename, 'r') as fh:
  124. new_format = migrate(fh.read())
  125. if opts.in_place:
  126. output = open(opts.filename, 'w')
  127. else:
  128. output = sys.stdout
  129. write(output, new_format, opts.indent, opts.width)
  130. if __name__ == "__main__":
  131. main(sys.argv)