serialize.py 5.0 KB

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