serialize.py 4.3 KB

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