config.py 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329
  1. import os
  2. import yaml
  3. import six
  4. DOCKER_CONFIG_KEYS = [
  5. 'cap_add',
  6. 'cap_drop',
  7. 'cpu_shares',
  8. 'command',
  9. 'detach',
  10. 'dns',
  11. 'dns_search',
  12. 'domainname',
  13. 'entrypoint',
  14. 'env_file',
  15. 'environment',
  16. 'hostname',
  17. 'image',
  18. 'links',
  19. 'mem_limit',
  20. 'net',
  21. 'ports',
  22. 'privileged',
  23. 'restart',
  24. 'stdin_open',
  25. 'tty',
  26. 'user',
  27. 'volumes',
  28. 'volumes_from',
  29. 'working_dir',
  30. ]
  31. ALLOWED_KEYS = DOCKER_CONFIG_KEYS + [
  32. 'build',
  33. 'expose',
  34. 'external_links',
  35. 'name',
  36. ]
  37. DOCKER_CONFIG_HINTS = {
  38. 'cpu_share' : 'cpu_shares',
  39. 'link' : 'links',
  40. 'port' : 'ports',
  41. 'privilege' : 'privileged',
  42. 'priviliged': 'privileged',
  43. 'privilige' : 'privileged',
  44. 'volume' : 'volumes',
  45. 'workdir' : 'working_dir',
  46. }
  47. def load(filename):
  48. working_dir = os.path.dirname(filename)
  49. return from_dictionary(load_yaml(filename), working_dir=working_dir, filename=filename)
  50. def from_dictionary(dictionary, working_dir=None, filename=None):
  51. service_dicts = []
  52. for service_name, service_dict in list(dictionary.items()):
  53. if not isinstance(service_dict, dict):
  54. raise ConfigurationError('Service "%s" doesn\'t have any configuration options. All top level keys in your docker-compose.yml must map to a dictionary of configuration options.' % service_name)
  55. loader = ServiceLoader(working_dir=working_dir, filename=filename)
  56. service_dict = loader.make_service_dict(service_name, service_dict)
  57. service_dicts.append(service_dict)
  58. return service_dicts
  59. def make_service_dict(name, service_dict, working_dir=None):
  60. return ServiceLoader(working_dir=working_dir).make_service_dict(name, service_dict)
  61. class ServiceLoader(object):
  62. def __init__(self, working_dir, filename=None, already_seen=None):
  63. self.working_dir = working_dir
  64. self.filename = filename
  65. self.already_seen = already_seen or []
  66. def make_service_dict(self, name, service_dict):
  67. if self.signature(name) in self.already_seen:
  68. raise CircularReference(self.already_seen)
  69. service_dict = service_dict.copy()
  70. service_dict['name'] = name
  71. service_dict = resolve_environment(service_dict, working_dir=self.working_dir)
  72. service_dict = self.resolve_extends(service_dict)
  73. return process_container_options(service_dict, working_dir=self.working_dir)
  74. def resolve_extends(self, service_dict):
  75. if 'extends' not in service_dict:
  76. return service_dict
  77. extends_options = process_extends_options(service_dict['name'], service_dict['extends'])
  78. if self.working_dir is None:
  79. raise Exception("No working_dir passed to ServiceLoader()")
  80. other_config_path = expand_path(self.working_dir, extends_options['file'])
  81. other_working_dir = os.path.dirname(other_config_path)
  82. other_already_seen = self.already_seen + [self.signature(service_dict['name'])]
  83. other_loader = ServiceLoader(
  84. working_dir=other_working_dir,
  85. filename=other_config_path,
  86. already_seen=other_already_seen,
  87. )
  88. other_config = load_yaml(other_config_path)
  89. other_service_dict = other_config[extends_options['service']]
  90. other_service_dict = other_loader.make_service_dict(
  91. service_dict['name'],
  92. other_service_dict,
  93. )
  94. validate_extended_service_dict(
  95. other_service_dict,
  96. filename=other_config_path,
  97. service=extends_options['service'],
  98. )
  99. return merge_service_dicts(other_service_dict, service_dict)
  100. def signature(self, name):
  101. return (self.filename, name)
  102. def process_extends_options(service_name, extends_options):
  103. error_prefix = "Invalid 'extends' configuration for %s:" % service_name
  104. if not isinstance(extends_options, dict):
  105. raise ConfigurationError("%s must be a dictionary" % error_prefix)
  106. if 'service' not in extends_options:
  107. raise ConfigurationError(
  108. "%s you need to specify a service, e.g. 'service: web'" % error_prefix
  109. )
  110. for k, _ in extends_options.items():
  111. if k not in ['file', 'service']:
  112. raise ConfigurationError(
  113. "%s unsupported configuration option '%s'" % (error_prefix, k)
  114. )
  115. return extends_options
  116. def validate_extended_service_dict(service_dict, filename, service):
  117. error_prefix = "Cannot extend service '%s' in %s:" % (service, filename)
  118. if 'links' in service_dict:
  119. raise ConfigurationError("%s services with 'links' cannot be extended" % error_prefix)
  120. if 'volumes_from' in service_dict:
  121. raise ConfigurationError("%s services with 'volumes_from' cannot be extended" % error_prefix)
  122. if 'net' in service_dict:
  123. if get_service_name_from_net(service_dict['net']) is not None:
  124. raise ConfigurationError("%s services with 'net: container' cannot be extended" % error_prefix)
  125. def process_container_options(service_dict, working_dir=None):
  126. for k in service_dict:
  127. if k not in ALLOWED_KEYS:
  128. msg = "Unsupported config option for %s service: '%s'" % (service_dict['name'], k)
  129. if k in DOCKER_CONFIG_HINTS:
  130. msg += " (did you mean '%s'?)" % DOCKER_CONFIG_HINTS[k]
  131. raise ConfigurationError(msg)
  132. return service_dict
  133. def merge_service_dicts(base, override):
  134. d = base.copy()
  135. if 'environment' in base or 'environment' in override:
  136. d['environment'] = merge_environment(
  137. base.get('environment'),
  138. override.get('environment'),
  139. )
  140. for k in ALLOWED_KEYS:
  141. if k not in ['environment']:
  142. if k in override:
  143. d[k] = override[k]
  144. return d
  145. def merge_environment(base, override):
  146. env = parse_environment(base)
  147. env.update(parse_environment(override))
  148. return env
  149. def parse_links(links):
  150. return dict(parse_link(l) for l in links)
  151. def parse_link(link):
  152. if ':' in link:
  153. source, alias = link.split(':', 1)
  154. return (alias, source)
  155. else:
  156. return (link, link)
  157. def get_env_files(options, working_dir=None):
  158. if 'env_file' not in options:
  159. return {}
  160. if working_dir is None:
  161. raise Exception("No working_dir passed to get_env_files()")
  162. env_files = options.get('env_file', [])
  163. if not isinstance(env_files, list):
  164. env_files = [env_files]
  165. return [expand_path(working_dir, path) for path in env_files]
  166. def resolve_environment(service_dict, working_dir=None):
  167. service_dict = service_dict.copy()
  168. if 'environment' not in service_dict and 'env_file' not in service_dict:
  169. return service_dict
  170. env = {}
  171. if 'env_file' in service_dict:
  172. for f in get_env_files(service_dict, working_dir=working_dir):
  173. env.update(env_vars_from_file(f))
  174. del service_dict['env_file']
  175. env.update(parse_environment(service_dict.get('environment')))
  176. env = dict(resolve_env_var(k, v) for k, v in six.iteritems(env))
  177. service_dict['environment'] = env
  178. return service_dict
  179. def parse_environment(environment):
  180. if not environment:
  181. return {}
  182. if isinstance(environment, list):
  183. return dict(split_env(e) for e in environment)
  184. if isinstance(environment, dict):
  185. return environment
  186. raise ConfigurationError(
  187. "environment \"%s\" must be a list or mapping," %
  188. environment
  189. )
  190. def split_env(env):
  191. if '=' in env:
  192. return env.split('=', 1)
  193. else:
  194. return env, None
  195. def resolve_env_var(key, val):
  196. if val is not None:
  197. return key, val
  198. elif key in os.environ:
  199. return key, os.environ[key]
  200. else:
  201. return key, ''
  202. def env_vars_from_file(filename):
  203. """
  204. Read in a line delimited file of environment variables.
  205. """
  206. if not os.path.exists(filename):
  207. raise ConfigurationError("Couldn't find env file: %s" % filename)
  208. env = {}
  209. for line in open(filename, 'r'):
  210. line = line.strip()
  211. if line and not line.startswith('#'):
  212. k, v = split_env(line)
  213. env[k] = v
  214. return env
  215. def expand_path(working_dir, path):
  216. return os.path.abspath(os.path.join(working_dir, path))
  217. def get_service_name_from_net(net_config):
  218. if not net_config:
  219. return
  220. if not net_config.startswith('container:'):
  221. return
  222. _, net_name = net_config.split(':', 1)
  223. return net_name
  224. def load_yaml(filename):
  225. try:
  226. with open(filename, 'r') as fh:
  227. return yaml.safe_load(fh)
  228. except IOError as e:
  229. raise ConfigurationError(six.text_type(e))
  230. class ConfigurationError(Exception):
  231. def __init__(self, msg):
  232. self.msg = msg
  233. def __str__(self):
  234. return self.msg
  235. class CircularReference(ConfigurationError):
  236. def __init__(self, trail):
  237. self.trail = trail
  238. @property
  239. def msg(self):
  240. lines = [
  241. "{} in {}".format(service_name, filename)
  242. for (filename, service_name) in self.trail
  243. ]
  244. return "Circular reference:\n {}".format("\n extends ".join(lines))