interpolation.py 9.8 KB

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