config.py 13 KB

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