serialize.py 5.4 KB

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