serialize.py 5.2 KB

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