config.py 13 KB

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