config.py 13 KB

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