config.py 12 KB

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