interpolation.py 9.1 KB

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