serialize.py 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165
  1. from __future__ import absolute_import
  2. from __future__ import unicode_literals
  3. import six
  4. import yaml
  5. from compose.config import types
  6. from compose.const import COMPOSEFILE_V1 as V1
  7. from compose.const import COMPOSEFILE_V2_1 as V2_1
  8. from compose.const import COMPOSEFILE_V2_3 as V2_3
  9. from compose.const import COMPOSEFILE_V3_0 as V3_0
  10. from compose.const import COMPOSEFILE_V3_2 as V3_2
  11. from compose.const import COMPOSEFILE_V3_4 as V3_4
  12. from compose.const import COMPOSEFILE_V3_5 as V3_5
  13. def serialize_config_type(dumper, data):
  14. representer = dumper.represent_str if six.PY3 else dumper.represent_unicode
  15. return representer(data.repr())
  16. def serialize_dict_type(dumper, data):
  17. return dumper.represent_dict(data.repr())
  18. def serialize_string(dumper, data):
  19. """ Ensure boolean-like strings are quoted in the output and escape $ characters """
  20. representer = dumper.represent_str if six.PY3 else dumper.represent_unicode
  21. if isinstance(data, six.binary_type):
  22. data = data.decode('utf-8')
  23. data = data.replace('$', '$$')
  24. if data.lower() in ('y', 'n', 'yes', 'no', 'on', 'off', 'true', 'false'):
  25. # Empirically only y/n appears to be an issue, but this might change
  26. # depending on which PyYaml version is being used. Err on safe side.
  27. return dumper.represent_scalar('tag:yaml.org,2002:str', data, style='"')
  28. return representer(data)
  29. yaml.SafeDumper.add_representer(types.MountSpec, serialize_dict_type)
  30. yaml.SafeDumper.add_representer(types.VolumeFromSpec, serialize_config_type)
  31. yaml.SafeDumper.add_representer(types.VolumeSpec, serialize_config_type)
  32. yaml.SafeDumper.add_representer(types.SecurityOpt, serialize_config_type)
  33. yaml.SafeDumper.add_representer(types.ServiceSecret, serialize_dict_type)
  34. yaml.SafeDumper.add_representer(types.ServiceConfig, serialize_dict_type)
  35. yaml.SafeDumper.add_representer(types.ServicePort, serialize_dict_type)
  36. yaml.SafeDumper.add_representer(str, serialize_string)
  37. yaml.SafeDumper.add_representer(six.text_type, serialize_string)
  38. def denormalize_config(config, image_digests=None):
  39. result = {'version': str(V2_1) if config.version == V1 else str(config.version)}
  40. denormalized_services = [
  41. denormalize_service_dict(
  42. service_dict,
  43. config.version,
  44. image_digests[service_dict['name']] if image_digests else None)
  45. for service_dict in config.services
  46. ]
  47. result['services'] = {
  48. service_dict.pop('name'): service_dict
  49. for service_dict in denormalized_services
  50. }
  51. for key in ('networks', 'volumes', 'secrets', 'configs'):
  52. config_dict = getattr(config, key)
  53. if not config_dict:
  54. continue
  55. result[key] = config_dict.copy()
  56. for name, conf in result[key].items():
  57. if 'external_name' in conf:
  58. del conf['external_name']
  59. if 'name' in conf:
  60. if config.version < V2_1 or (
  61. config.version >= V3_0 and config.version < v3_introduced_name_key(key)):
  62. del conf['name']
  63. elif 'external' in conf:
  64. conf['external'] = True
  65. return result
  66. def v3_introduced_name_key(key):
  67. if key == 'volumes':
  68. return V3_4
  69. return V3_5
  70. def serialize_config(config, image_digests=None):
  71. return yaml.safe_dump(
  72. denormalize_config(config, image_digests),
  73. default_flow_style=False,
  74. indent=2,
  75. width=80,
  76. allow_unicode=True
  77. )
  78. def serialize_ns_time_value(value):
  79. result = (value, 'ns')
  80. table = [
  81. (1000., 'us'),
  82. (1000., 'ms'),
  83. (1000., 's'),
  84. (60., 'm'),
  85. (60., 'h')
  86. ]
  87. for stage in table:
  88. tmp = value / stage[0]
  89. if tmp == int(value / stage[0]):
  90. value = tmp
  91. result = (int(value), stage[1])
  92. else:
  93. break
  94. return '{0}{1}'.format(*result)
  95. def denormalize_service_dict(service_dict, version, image_digest=None):
  96. service_dict = service_dict.copy()
  97. if image_digest:
  98. service_dict['image'] = image_digest
  99. if 'restart' in service_dict:
  100. service_dict['restart'] = types.serialize_restart_spec(
  101. service_dict['restart']
  102. )
  103. if version == V1 and 'network_mode' not in service_dict:
  104. service_dict['network_mode'] = 'bridge'
  105. if 'depends_on' in service_dict and (version < V2_1 or version >= V3_0):
  106. service_dict['depends_on'] = sorted([
  107. svc for svc in service_dict['depends_on'].keys()
  108. ])
  109. if 'healthcheck' in service_dict:
  110. if 'interval' in service_dict['healthcheck']:
  111. service_dict['healthcheck']['interval'] = serialize_ns_time_value(
  112. service_dict['healthcheck']['interval']
  113. )
  114. if 'timeout' in service_dict['healthcheck']:
  115. service_dict['healthcheck']['timeout'] = serialize_ns_time_value(
  116. service_dict['healthcheck']['timeout']
  117. )
  118. if 'start_period' in service_dict['healthcheck']:
  119. service_dict['healthcheck']['start_period'] = serialize_ns_time_value(
  120. service_dict['healthcheck']['start_period']
  121. )
  122. if 'ports' in service_dict:
  123. service_dict['ports'] = [
  124. p.legacy_repr() if p.external_ip or version < V3_2 else p
  125. for p in service_dict['ports']
  126. ]
  127. if 'volumes' in service_dict and (version < V2_3 or (version > V3_0 and version < V3_2)):
  128. service_dict['volumes'] = [
  129. v.legacy_repr() if isinstance(v, types.MountSpec) else v for v in service_dict['volumes']
  130. ]
  131. return service_dict