config.py 12 KB

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