interpolation.py 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  1. import logging
  2. import re
  3. from string import Template
  4. from .errors import ConfigurationError
  5. from compose.const import COMPOSEFILE_V1 as V1
  6. from compose.utils import parse_bytes
  7. from compose.utils import parse_nanoseconds_int
  8. log = logging.getLogger(__name__)
  9. class Interpolator:
  10. def __init__(self, templater, mapping):
  11. self.templater = templater
  12. self.mapping = mapping
  13. def interpolate(self, string):
  14. try:
  15. return self.templater(string).substitute(self.mapping)
  16. except ValueError:
  17. raise InvalidInterpolation(string)
  18. def interpolate_environment_variables(version, config, section, environment):
  19. if version == V1:
  20. interpolator = Interpolator(Template, environment)
  21. else:
  22. interpolator = Interpolator(TemplateWithDefaults, environment)
  23. def process_item(name, config_dict):
  24. return {
  25. key: interpolate_value(name, key, val, section, interpolator)
  26. for key, val in (config_dict or {}).items()
  27. }
  28. return {
  29. name: process_item(name, config_dict or {})
  30. for name, config_dict in config.items()
  31. }
  32. def get_config_path(config_key, section, name):
  33. return '{}/{}/{}'.format(section, name, config_key)
  34. def interpolate_value(name, config_key, value, section, interpolator):
  35. try:
  36. return recursive_interpolate(value, interpolator, get_config_path(config_key, section, name))
  37. except InvalidInterpolation as e:
  38. raise ConfigurationError(
  39. 'Invalid interpolation format for "{config_key}" option '
  40. 'in {section} "{name}": "{string}"'.format(
  41. config_key=config_key,
  42. name=name,
  43. section=section,
  44. string=e.string))
  45. except UnsetRequiredSubstitution as e:
  46. raise ConfigurationError(
  47. 'Missing mandatory value for "{config_key}" option interpolating {value} '
  48. 'in {section} "{name}": {err}'.format(config_key=config_key,
  49. value=value,
  50. name=name,
  51. section=section,
  52. err=e.err)
  53. )
  54. def recursive_interpolate(obj, interpolator, config_path):
  55. def append(config_path, key):
  56. return '{}/{}'.format(config_path, key)
  57. if isinstance(obj, str):
  58. return converter.convert(config_path, interpolator.interpolate(obj))
  59. if isinstance(obj, dict):
  60. return {
  61. key: recursive_interpolate(val, interpolator, append(config_path, key))
  62. for key, val in obj.items()
  63. }
  64. if isinstance(obj, list):
  65. return [recursive_interpolate(val, interpolator, config_path) for val in obj]
  66. return converter.convert(config_path, obj)
  67. class TemplateWithDefaults(Template):
  68. pattern = r"""
  69. {delim}(?:
  70. (?P<escaped>{delim}) |
  71. (?P<named>{id}) |
  72. {{(?P<braced>{bid})}} |
  73. (?P<invalid>)
  74. )
  75. """.format(
  76. delim=re.escape('$'),
  77. id=r'[_a-z][_a-z0-9]*',
  78. bid=r'[_a-z][_a-z0-9]*(?:(?P<sep>:?[-?])[^}]*)?',
  79. )
  80. @staticmethod
  81. def process_braced_group(braced, sep, mapping):
  82. if ':-' == sep:
  83. var, _, default = braced.partition(':-')
  84. return mapping.get(var) or default
  85. elif '-' == sep:
  86. var, _, default = braced.partition('-')
  87. return mapping.get(var, default)
  88. elif ':?' == sep:
  89. var, _, err = braced.partition(':?')
  90. result = mapping.get(var)
  91. if not result:
  92. err = err or var
  93. raise UnsetRequiredSubstitution(err)
  94. return result
  95. elif '?' == sep:
  96. var, _, err = braced.partition('?')
  97. if var in mapping:
  98. return mapping.get(var)
  99. err = err or var
  100. raise UnsetRequiredSubstitution(err)
  101. # Modified from python2.7/string.py
  102. def substitute(self, mapping):
  103. # Helper function for .sub()
  104. def convert(mo):
  105. named = mo.group('named') or mo.group('braced')
  106. braced = mo.group('braced')
  107. if braced is not None:
  108. sep = mo.group('sep')
  109. if sep:
  110. return self.process_braced_group(braced, sep, mapping)
  111. if named is not None:
  112. val = mapping[named]
  113. if isinstance(val, bytes):
  114. val = val.decode('utf-8')
  115. return '{}'.format(val)
  116. if mo.group('escaped') is not None:
  117. return self.delimiter
  118. if mo.group('invalid') is not None:
  119. self._invalid(mo)
  120. raise ValueError('Unrecognized named group in pattern',
  121. self.pattern)
  122. return self.pattern.sub(convert, self.template)
  123. class InvalidInterpolation(Exception):
  124. def __init__(self, string):
  125. self.string = string
  126. class UnsetRequiredSubstitution(Exception):
  127. def __init__(self, custom_err_msg):
  128. self.err = custom_err_msg
  129. PATH_JOKER = '[^/]+'
  130. FULL_JOKER = '.+'
  131. def re_path(*args):
  132. return re.compile('^{}$'.format('/'.join(args)))
  133. def re_path_basic(section, name):
  134. return re_path(section, PATH_JOKER, name)
  135. def service_path(*args):
  136. return re_path('service', PATH_JOKER, *args)
  137. def to_boolean(s):
  138. if not isinstance(s, str):
  139. return s
  140. s = s.lower()
  141. if s in ['y', 'yes', 'true', 'on']:
  142. return True
  143. elif s in ['n', 'no', 'false', 'off']:
  144. return False
  145. raise ValueError('"{}" is not a valid boolean value'.format(s))
  146. def to_int(s):
  147. if not isinstance(s, str):
  148. return s
  149. # We must be able to handle octal representation for `mode` values notably
  150. if re.match('^0[0-9]+$', s.strip()):
  151. s = '0o' + s[1:]
  152. try:
  153. return int(s, base=0)
  154. except ValueError:
  155. raise ValueError('"{}" is not a valid integer'.format(s))
  156. def to_float(s):
  157. if not isinstance(s, str):
  158. return s
  159. try:
  160. return float(s)
  161. except ValueError:
  162. raise ValueError('"{}" is not a valid float'.format(s))
  163. def to_str(o):
  164. if isinstance(o, (bool, float, int)):
  165. return '{}'.format(o)
  166. return o
  167. def bytes_to_int(s):
  168. v = parse_bytes(s)
  169. if v is None:
  170. raise ValueError('"{}" is not a valid byte value'.format(s))
  171. return v
  172. def to_microseconds(v):
  173. if not isinstance(v, str):
  174. return v
  175. return int(parse_nanoseconds_int(v) / 1000)
  176. class ConversionMap:
  177. map = {
  178. service_path('blkio_config', 'weight'): to_int,
  179. service_path('blkio_config', 'weight_device', 'weight'): to_int,
  180. service_path('build', 'labels', FULL_JOKER): to_str,
  181. service_path('cpus'): to_float,
  182. service_path('cpu_count'): to_int,
  183. service_path('cpu_quota'): to_microseconds,
  184. service_path('cpu_period'): to_microseconds,
  185. service_path('cpu_rt_period'): to_microseconds,
  186. service_path('cpu_rt_runtime'): to_microseconds,
  187. service_path('configs', 'mode'): to_int,
  188. service_path('secrets', 'mode'): to_int,
  189. service_path('healthcheck', 'retries'): to_int,
  190. service_path('healthcheck', 'disable'): to_boolean,
  191. service_path('deploy', 'labels', PATH_JOKER): to_str,
  192. service_path('deploy', 'replicas'): to_int,
  193. service_path('deploy', 'placement', 'max_replicas_per_node'): to_int,
  194. service_path('deploy', 'resources', 'limits', "cpus"): to_float,
  195. service_path('deploy', 'update_config', 'parallelism'): to_int,
  196. service_path('deploy', 'update_config', 'max_failure_ratio'): to_float,
  197. service_path('deploy', 'rollback_config', 'parallelism'): to_int,
  198. service_path('deploy', 'rollback_config', 'max_failure_ratio'): to_float,
  199. service_path('deploy', 'restart_policy', 'max_attempts'): to_int,
  200. service_path('mem_swappiness'): to_int,
  201. service_path('labels', FULL_JOKER): to_str,
  202. service_path('oom_kill_disable'): to_boolean,
  203. service_path('oom_score_adj'): to_int,
  204. service_path('ports', 'target'): to_int,
  205. service_path('ports', 'published'): to_int,
  206. service_path('scale'): to_int,
  207. service_path('ulimits', PATH_JOKER): to_int,
  208. service_path('ulimits', PATH_JOKER, 'soft'): to_int,
  209. service_path('ulimits', PATH_JOKER, 'hard'): to_int,
  210. service_path('privileged'): to_boolean,
  211. service_path('read_only'): to_boolean,
  212. service_path('stdin_open'): to_boolean,
  213. service_path('tty'): to_boolean,
  214. service_path('volumes', 'read_only'): to_boolean,
  215. service_path('volumes', 'volume', 'nocopy'): to_boolean,
  216. service_path('volumes', 'tmpfs', 'size'): bytes_to_int,
  217. re_path_basic('network', 'attachable'): to_boolean,
  218. re_path_basic('network', 'external'): to_boolean,
  219. re_path_basic('network', 'internal'): to_boolean,
  220. re_path('network', PATH_JOKER, 'labels', FULL_JOKER): to_str,
  221. re_path_basic('volume', 'external'): to_boolean,
  222. re_path('volume', PATH_JOKER, 'labels', FULL_JOKER): to_str,
  223. re_path_basic('secret', 'external'): to_boolean,
  224. re_path('secret', PATH_JOKER, 'labels', FULL_JOKER): to_str,
  225. re_path_basic('config', 'external'): to_boolean,
  226. re_path('config', PATH_JOKER, 'labels', FULL_JOKER): to_str,
  227. }
  228. def convert(self, path, value):
  229. for rexp in self.map.keys():
  230. if rexp.match(path):
  231. try:
  232. return self.map[rexp](value)
  233. except ValueError as e:
  234. raise ConfigurationError(
  235. 'Error while attempting to convert {} to appropriate type: {}'.format(
  236. path.replace('/', '.'), e
  237. )
  238. )
  239. return value
  240. converter = ConversionMap()