config.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394
  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. service_dict = service_dict.copy()
  133. if 'volumes' in service_dict:
  134. service_dict['volumes'] = resolve_host_paths(service_dict['volumes'], working_dir=working_dir)
  135. return service_dict
  136. def merge_service_dicts(base, override):
  137. d = base.copy()
  138. if 'environment' in base or 'environment' in override:
  139. d['environment'] = merge_environment(
  140. base.get('environment'),
  141. override.get('environment'),
  142. )
  143. if 'volumes' in base or 'volumes' in override:
  144. d['volumes'] = merge_volumes(
  145. base.get('volumes'),
  146. override.get('volumes'),
  147. )
  148. if 'image' in override and 'build' in d:
  149. del d['build']
  150. if 'build' in override and 'image' in d:
  151. del d['image']
  152. for k in ALLOWED_KEYS:
  153. if k not in ['environment', 'volumes']:
  154. if k in override:
  155. d[k] = override[k]
  156. return d
  157. def merge_environment(base, override):
  158. env = parse_environment(base)
  159. env.update(parse_environment(override))
  160. return env
  161. def parse_links(links):
  162. return dict(parse_link(l) for l in links)
  163. def parse_link(link):
  164. if ':' in link:
  165. source, alias = link.split(':', 1)
  166. return (alias, source)
  167. else:
  168. return (link, link)
  169. def get_env_files(options, working_dir=None):
  170. if 'env_file' not in options:
  171. return {}
  172. if working_dir is None:
  173. raise Exception("No working_dir passed to get_env_files()")
  174. env_files = options.get('env_file', [])
  175. if not isinstance(env_files, list):
  176. env_files = [env_files]
  177. return [expand_path(working_dir, path) for path in env_files]
  178. def resolve_environment(service_dict, working_dir=None):
  179. service_dict = service_dict.copy()
  180. if 'environment' not in service_dict and 'env_file' not in service_dict:
  181. return service_dict
  182. env = {}
  183. if 'env_file' in service_dict:
  184. for f in get_env_files(service_dict, working_dir=working_dir):
  185. env.update(env_vars_from_file(f))
  186. del service_dict['env_file']
  187. env.update(parse_environment(service_dict.get('environment')))
  188. env = dict(resolve_env_var(k, v) for k, v in six.iteritems(env))
  189. service_dict['environment'] = env
  190. return service_dict
  191. def parse_environment(environment):
  192. if not environment:
  193. return {}
  194. if isinstance(environment, list):
  195. return dict(split_env(e) for e in environment)
  196. if isinstance(environment, dict):
  197. return environment
  198. raise ConfigurationError(
  199. "environment \"%s\" must be a list or mapping," %
  200. environment
  201. )
  202. def split_env(env):
  203. if '=' in env:
  204. return env.split('=', 1)
  205. else:
  206. return env, None
  207. def resolve_env_var(key, val):
  208. if val is not None:
  209. return key, val
  210. elif key in os.environ:
  211. return key, os.environ[key]
  212. else:
  213. return key, ''
  214. def env_vars_from_file(filename):
  215. """
  216. Read in a line delimited file of environment variables.
  217. """
  218. if not os.path.exists(filename):
  219. raise ConfigurationError("Couldn't find env file: %s" % filename)
  220. env = {}
  221. for line in open(filename, 'r'):
  222. line = line.strip()
  223. if line and not line.startswith('#'):
  224. k, v = split_env(line)
  225. env[k] = v
  226. return env
  227. def resolve_host_paths(volumes, working_dir=None):
  228. if working_dir is None:
  229. raise Exception("No working_dir passed to resolve_host_paths()")
  230. return [resolve_host_path(v, working_dir) for v in volumes]
  231. def resolve_host_path(volume, working_dir):
  232. container_path, host_path = split_volume(volume)
  233. if host_path is not None:
  234. return "%s:%s" % (expand_path(working_dir, host_path), container_path)
  235. else:
  236. return container_path
  237. def merge_volumes(base, override):
  238. d = dict_from_volumes(base)
  239. d.update(dict_from_volumes(override))
  240. return volumes_from_dict(d)
  241. def dict_from_volumes(volumes):
  242. if volumes:
  243. return dict(split_volume(v) for v in volumes)
  244. else:
  245. return {}
  246. def volumes_from_dict(d):
  247. return [join_volume(v) for v in d.items()]
  248. def split_volume(string):
  249. if ':' in string:
  250. (host, container) = string.split(':', 1)
  251. return (container, host)
  252. else:
  253. return (string, None)
  254. def join_volume(pair):
  255. (container, host) = pair
  256. if host is None:
  257. return container
  258. else:
  259. return ":".join((host, container))
  260. def expand_path(working_dir, path):
  261. return os.path.abspath(os.path.join(working_dir, path))
  262. def get_service_name_from_net(net_config):
  263. if not net_config:
  264. return
  265. if not net_config.startswith('container:'):
  266. return
  267. _, net_name = net_config.split(':', 1)
  268. return net_name
  269. def load_yaml(filename):
  270. try:
  271. with open(filename, 'r') as fh:
  272. return yaml.safe_load(fh)
  273. except IOError as e:
  274. raise ConfigurationError(six.text_type(e))
  275. class ConfigurationError(Exception):
  276. def __init__(self, msg):
  277. self.msg = msg
  278. def __str__(self):
  279. return self.msg
  280. class CircularReference(ConfigurationError):
  281. def __init__(self, trail):
  282. self.trail = trail
  283. @property
  284. def msg(self):
  285. lines = [
  286. "{} in {}".format(service_name, filename)
  287. for (filename, service_name) in self.trail
  288. ]
  289. return "Circular reference:\n {}".format("\n extends ".join(lines))