config.py 13 KB

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