1
0

interpolation.py 9.4 KB

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