config.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437
  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. 'extra_hosts',
  17. 'hostname',
  18. 'image',
  19. 'links',
  20. 'mem_limit',
  21. 'net',
  22. 'pid',
  23. 'ports',
  24. 'privileged',
  25. 'restart',
  26. 'stdin_open',
  27. 'tty',
  28. 'user',
  29. 'volumes',
  30. 'volumes_from',
  31. 'working_dir',
  32. ]
  33. ALLOWED_KEYS = DOCKER_CONFIG_KEYS + [
  34. 'build',
  35. 'expose',
  36. 'external_links',
  37. 'name',
  38. ]
  39. DOCKER_CONFIG_HINTS = {
  40. 'cpu_share': 'cpu_shares',
  41. 'add_host': 'extra_hosts',
  42. 'hosts': 'extra_hosts',
  43. 'extra_host': 'extra_hosts',
  44. 'link': 'links',
  45. 'port': 'ports',
  46. 'privilege': 'privileged',
  47. 'priviliged': 'privileged',
  48. 'privilige': 'privileged',
  49. 'volume': 'volumes',
  50. 'workdir': 'working_dir',
  51. }
  52. def load(filename):
  53. working_dir = os.path.dirname(filename)
  54. return from_dictionary(load_yaml(filename), working_dir=working_dir, filename=filename)
  55. def from_dictionary(dictionary, working_dir=None, filename=None):
  56. service_dicts = []
  57. for service_name, service_dict in list(dictionary.items()):
  58. if not isinstance(service_dict, dict):
  59. 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)
  60. loader = ServiceLoader(working_dir=working_dir, filename=filename)
  61. service_dict = loader.make_service_dict(service_name, service_dict)
  62. service_dicts.append(service_dict)
  63. return service_dicts
  64. def make_service_dict(name, service_dict, working_dir=None):
  65. return ServiceLoader(working_dir=working_dir).make_service_dict(name, service_dict)
  66. class ServiceLoader(object):
  67. def __init__(self, working_dir, filename=None, already_seen=None):
  68. self.working_dir = working_dir
  69. self.filename = filename
  70. self.already_seen = already_seen or []
  71. def make_service_dict(self, name, service_dict):
  72. if self.signature(name) in self.already_seen:
  73. raise CircularReference(self.already_seen)
  74. service_dict = service_dict.copy()
  75. service_dict['name'] = name
  76. service_dict = resolve_environment(service_dict, working_dir=self.working_dir)
  77. service_dict = self.resolve_extends(service_dict)
  78. return process_container_options(service_dict, working_dir=self.working_dir)
  79. def resolve_extends(self, service_dict):
  80. if 'extends' not in service_dict:
  81. return service_dict
  82. extends_options = process_extends_options(service_dict['name'], service_dict['extends'])
  83. if self.working_dir is None:
  84. raise Exception("No working_dir passed to ServiceLoader()")
  85. other_config_path = expand_path(self.working_dir, extends_options['file'])
  86. other_working_dir = os.path.dirname(other_config_path)
  87. other_already_seen = self.already_seen + [self.signature(service_dict['name'])]
  88. other_loader = ServiceLoader(
  89. working_dir=other_working_dir,
  90. filename=other_config_path,
  91. already_seen=other_already_seen,
  92. )
  93. other_config = load_yaml(other_config_path)
  94. other_service_dict = other_config[extends_options['service']]
  95. other_service_dict = other_loader.make_service_dict(
  96. service_dict['name'],
  97. other_service_dict,
  98. )
  99. validate_extended_service_dict(
  100. other_service_dict,
  101. filename=other_config_path,
  102. service=extends_options['service'],
  103. )
  104. return merge_service_dicts(other_service_dict, service_dict)
  105. def signature(self, name):
  106. return (self.filename, name)
  107. def process_extends_options(service_name, extends_options):
  108. error_prefix = "Invalid 'extends' configuration for %s:" % service_name
  109. if not isinstance(extends_options, dict):
  110. raise ConfigurationError("%s must be a dictionary" % error_prefix)
  111. if 'service' not in extends_options:
  112. raise ConfigurationError(
  113. "%s you need to specify a service, e.g. 'service: web'" % error_prefix
  114. )
  115. for k, _ in extends_options.items():
  116. if k not in ['file', 'service']:
  117. raise ConfigurationError(
  118. "%s unsupported configuration option '%s'" % (error_prefix, k)
  119. )
  120. return extends_options
  121. def validate_extended_service_dict(service_dict, filename, service):
  122. error_prefix = "Cannot extend service '%s' in %s:" % (service, filename)
  123. if 'links' in service_dict:
  124. raise ConfigurationError("%s services with 'links' cannot be extended" % error_prefix)
  125. if 'volumes_from' in service_dict:
  126. raise ConfigurationError("%s services with 'volumes_from' cannot be extended" % error_prefix)
  127. if 'net' in service_dict:
  128. if get_service_name_from_net(service_dict['net']) is not None:
  129. raise ConfigurationError("%s services with 'net: container' cannot be extended" % error_prefix)
  130. def process_container_options(service_dict, working_dir=None):
  131. for k in service_dict:
  132. if k not in ALLOWED_KEYS:
  133. msg = "Unsupported config option for %s service: '%s'" % (service_dict['name'], k)
  134. if k in DOCKER_CONFIG_HINTS:
  135. msg += " (did you mean '%s'?)" % DOCKER_CONFIG_HINTS[k]
  136. raise ConfigurationError(msg)
  137. service_dict = service_dict.copy()
  138. if 'volumes' in service_dict:
  139. service_dict['volumes'] = resolve_host_paths(service_dict['volumes'], working_dir=working_dir)
  140. if 'build' in service_dict:
  141. service_dict['build'] = resolve_build_path(service_dict['build'], working_dir=working_dir)
  142. return service_dict
  143. def merge_service_dicts(base, override):
  144. d = base.copy()
  145. if 'environment' in base or 'environment' in override:
  146. d['environment'] = merge_environment(
  147. base.get('environment'),
  148. override.get('environment'),
  149. )
  150. if 'volumes' in base or 'volumes' in override:
  151. d['volumes'] = merge_volumes(
  152. base.get('volumes'),
  153. override.get('volumes'),
  154. )
  155. if 'image' in override and 'build' in d:
  156. del d['build']
  157. if 'build' in override and 'image' in d:
  158. del d['image']
  159. list_keys = ['ports', 'expose', 'external_links']
  160. for key in list_keys:
  161. if key in base or key in override:
  162. d[key] = base.get(key, []) + override.get(key, [])
  163. list_or_string_keys = ['dns', 'dns_search']
  164. for key in list_or_string_keys:
  165. if key in base or key in override:
  166. d[key] = to_list(base.get(key)) + to_list(override.get(key))
  167. already_merged_keys = ['environment', 'volumes'] + list_keys + list_or_string_keys
  168. for k in set(ALLOWED_KEYS) - set(already_merged_keys):
  169. if k in override:
  170. d[k] = override[k]
  171. return d
  172. def merge_environment(base, override):
  173. env = parse_environment(base)
  174. env.update(parse_environment(override))
  175. return env
  176. def parse_links(links):
  177. return dict(parse_link(l) for l in links)
  178. def parse_link(link):
  179. if ':' in link:
  180. source, alias = link.split(':', 1)
  181. return (alias, source)
  182. else:
  183. return (link, link)
  184. def get_env_files(options, working_dir=None):
  185. if 'env_file' not in options:
  186. return {}
  187. if working_dir is None:
  188. raise Exception("No working_dir passed to get_env_files()")
  189. env_files = options.get('env_file', [])
  190. if not isinstance(env_files, list):
  191. env_files = [env_files]
  192. return [expand_path(working_dir, path) for path in env_files]
  193. def resolve_environment(service_dict, working_dir=None):
  194. service_dict = service_dict.copy()
  195. if 'environment' not in service_dict and 'env_file' not in service_dict:
  196. return service_dict
  197. env = {}
  198. if 'env_file' in service_dict:
  199. for f in get_env_files(service_dict, working_dir=working_dir):
  200. env.update(env_vars_from_file(f))
  201. del service_dict['env_file']
  202. env.update(parse_environment(service_dict.get('environment')))
  203. env = dict(resolve_env_var(k, v) for k, v in six.iteritems(env))
  204. service_dict['environment'] = env
  205. return service_dict
  206. def parse_environment(environment):
  207. if not environment:
  208. return {}
  209. if isinstance(environment, list):
  210. return dict(split_env(e) for e in environment)
  211. if isinstance(environment, dict):
  212. return environment
  213. raise ConfigurationError(
  214. "environment \"%s\" must be a list or mapping," %
  215. environment
  216. )
  217. def split_env(env):
  218. if '=' in env:
  219. return env.split('=', 1)
  220. else:
  221. return env, None
  222. def resolve_env_var(key, val):
  223. if val is not None:
  224. return key, val
  225. elif key in os.environ:
  226. return key, os.environ[key]
  227. else:
  228. return key, ''
  229. def env_vars_from_file(filename):
  230. """
  231. Read in a line delimited file of environment variables.
  232. """
  233. if not os.path.exists(filename):
  234. raise ConfigurationError("Couldn't find env file: %s" % filename)
  235. env = {}
  236. for line in open(filename, 'r'):
  237. line = line.strip()
  238. if line and not line.startswith('#'):
  239. k, v = split_env(line)
  240. env[k] = v
  241. return env
  242. def resolve_host_paths(volumes, working_dir=None):
  243. if working_dir is None:
  244. raise Exception("No working_dir passed to resolve_host_paths()")
  245. return [resolve_host_path(v, working_dir) for v in volumes]
  246. def resolve_host_path(volume, working_dir):
  247. container_path, host_path = split_volume(volume)
  248. if host_path is not None:
  249. host_path = os.path.expanduser(host_path)
  250. host_path = os.path.expandvars(host_path)
  251. return "%s:%s" % (expand_path(working_dir, host_path), container_path)
  252. else:
  253. return container_path
  254. def resolve_build_path(build_path, working_dir=None):
  255. if working_dir is None:
  256. raise Exception("No working_dir passed to resolve_build_path")
  257. _path = expand_path(working_dir, build_path)
  258. if not os.path.exists(_path) or not os.access(_path, os.R_OK):
  259. raise ConfigurationError("build path %s either does not exist or is not accessible." % _path)
  260. else:
  261. return _path
  262. def merge_volumes(base, override):
  263. d = dict_from_volumes(base)
  264. d.update(dict_from_volumes(override))
  265. return volumes_from_dict(d)
  266. def dict_from_volumes(volumes):
  267. if volumes:
  268. return dict(split_volume(v) for v in volumes)
  269. else:
  270. return {}
  271. def volumes_from_dict(d):
  272. return [join_volume(v) for v in d.items()]
  273. def split_volume(string):
  274. if ':' in string:
  275. (host, container) = string.split(':', 1)
  276. return (container, host)
  277. else:
  278. return (string, None)
  279. def join_volume(pair):
  280. (container, host) = pair
  281. if host is None:
  282. return container
  283. else:
  284. return ":".join((host, container))
  285. def expand_path(working_dir, path):
  286. return os.path.abspath(os.path.join(working_dir, path))
  287. def to_list(value):
  288. if value is None:
  289. return []
  290. elif isinstance(value, six.string_types):
  291. return [value]
  292. else:
  293. return value
  294. def get_service_name_from_net(net_config):
  295. if not net_config:
  296. return
  297. if not net_config.startswith('container:'):
  298. return
  299. _, net_name = net_config.split(':', 1)
  300. return net_name
  301. def load_yaml(filename):
  302. try:
  303. with open(filename, 'r') as fh:
  304. return yaml.safe_load(fh)
  305. except IOError as e:
  306. raise ConfigurationError(six.text_type(e))
  307. class ConfigurationError(Exception):
  308. def __init__(self, msg):
  309. self.msg = msg
  310. def __str__(self):
  311. return self.msg
  312. class CircularReference(ConfigurationError):
  313. def __init__(self, trail):
  314. self.trail = trail
  315. @property
  316. def msg(self):
  317. lines = [
  318. "{} in {}".format(service_name, filename)
  319. for (filename, service_name) in self.trail
  320. ]
  321. return "Circular reference:\n {}".format("\n extends ".join(lines))