config.py 15 KB

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