config.py 13 KB

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