config.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559
  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 = self.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. if 'file' in extends_options:
  130. extends_from_filename = extends_options['file']
  131. other_config_path = expand_path(self.working_dir, extends_from_filename)
  132. else:
  133. other_config_path = self.filename
  134. other_working_dir = os.path.dirname(other_config_path)
  135. other_already_seen = self.already_seen + [self.signature(service_dict['name'])]
  136. other_loader = ServiceLoader(
  137. working_dir=other_working_dir,
  138. filename=other_config_path,
  139. already_seen=other_already_seen,
  140. )
  141. other_config = load_yaml(other_config_path)
  142. other_service_dict = other_config[extends_options['service']]
  143. other_service_dict = other_loader.make_service_dict(
  144. service_dict['name'],
  145. other_service_dict,
  146. )
  147. validate_extended_service_dict(
  148. other_service_dict,
  149. filename=other_config_path,
  150. service=extends_options['service'],
  151. )
  152. return merge_service_dicts(other_service_dict, service_dict)
  153. def signature(self, name):
  154. return (self.filename, name)
  155. def validate_extends_options(self, service_name, extends_options):
  156. error_prefix = "Invalid 'extends' configuration for %s:" % service_name
  157. if not isinstance(extends_options, dict):
  158. raise ConfigurationError("%s must be a dictionary" % error_prefix)
  159. if 'service' not in extends_options:
  160. raise ConfigurationError(
  161. "%s you need to specify a service, e.g. 'service: web'" % error_prefix
  162. )
  163. if 'file' not in extends_options and self.filename is None:
  164. raise ConfigurationError(
  165. "%s you need to specify a 'file', e.g. 'file: something.yml'" % error_prefix
  166. )
  167. for k, _ in extends_options.items():
  168. if k not in ['file', 'service']:
  169. raise ConfigurationError(
  170. "%s unsupported configuration option '%s'" % (error_prefix, k)
  171. )
  172. return extends_options
  173. def validate_extended_service_dict(service_dict, filename, service):
  174. error_prefix = "Cannot extend service '%s' in %s:" % (service, filename)
  175. if 'links' in service_dict:
  176. raise ConfigurationError("%s services with 'links' cannot be extended" % error_prefix)
  177. if 'volumes_from' in service_dict:
  178. raise ConfigurationError("%s services with 'volumes_from' cannot be extended" % error_prefix)
  179. if 'net' in service_dict:
  180. if get_service_name_from_net(service_dict['net']) is not None:
  181. raise ConfigurationError("%s services with 'net: container' cannot be extended" % error_prefix)
  182. def process_container_options(service_dict, working_dir=None):
  183. for k in service_dict:
  184. if k not in ALLOWED_KEYS:
  185. msg = "Unsupported config option for %s service: '%s'" % (service_dict['name'], k)
  186. if k in DOCKER_CONFIG_HINTS:
  187. msg += " (did you mean '%s'?)" % DOCKER_CONFIG_HINTS[k]
  188. raise ConfigurationError(msg)
  189. service_dict = service_dict.copy()
  190. if 'volumes' in service_dict:
  191. service_dict['volumes'] = resolve_volume_paths(service_dict['volumes'], working_dir=working_dir)
  192. if 'build' in service_dict:
  193. service_dict['build'] = resolve_build_path(service_dict['build'], working_dir=working_dir)
  194. if 'labels' in service_dict:
  195. service_dict['labels'] = parse_labels(service_dict['labels'])
  196. return service_dict
  197. def merge_service_dicts(base, override):
  198. d = base.copy()
  199. if 'environment' in base or 'environment' in override:
  200. d['environment'] = merge_environment(
  201. base.get('environment'),
  202. override.get('environment'),
  203. )
  204. path_mapping_keys = ['volumes', 'devices']
  205. for key in path_mapping_keys:
  206. if key in base or key in override:
  207. d[key] = merge_path_mappings(
  208. base.get(key),
  209. override.get(key),
  210. )
  211. if 'labels' in base or 'labels' in override:
  212. d['labels'] = merge_labels(
  213. base.get('labels'),
  214. override.get('labels'),
  215. )
  216. if 'image' in override and 'build' in d:
  217. del d['build']
  218. if 'build' in override and 'image' in d:
  219. del d['image']
  220. list_keys = ['ports', 'expose', 'external_links']
  221. for key in list_keys:
  222. if key in base or key in override:
  223. d[key] = base.get(key, []) + override.get(key, [])
  224. list_or_string_keys = ['dns', 'dns_search']
  225. for key in list_or_string_keys:
  226. if key in base or key in override:
  227. d[key] = to_list(base.get(key)) + to_list(override.get(key))
  228. already_merged_keys = ['environment', 'labels'] + path_mapping_keys + list_keys + list_or_string_keys
  229. for k in set(ALLOWED_KEYS) - set(already_merged_keys):
  230. if k in override:
  231. d[k] = override[k]
  232. return d
  233. def merge_environment(base, override):
  234. env = parse_environment(base)
  235. env.update(parse_environment(override))
  236. return env
  237. def parse_links(links):
  238. return dict(parse_link(l) for l in links)
  239. def parse_link(link):
  240. if ':' in link:
  241. source, alias = link.split(':', 1)
  242. return (alias, source)
  243. else:
  244. return (link, link)
  245. def get_env_files(options, working_dir=None):
  246. if 'env_file' not in options:
  247. return {}
  248. if working_dir is None:
  249. raise Exception("No working_dir passed to get_env_files()")
  250. env_files = options.get('env_file', [])
  251. if not isinstance(env_files, list):
  252. env_files = [env_files]
  253. return [expand_path(working_dir, path) for path in env_files]
  254. def resolve_environment(service_dict, working_dir=None):
  255. service_dict = service_dict.copy()
  256. if 'environment' not in service_dict and 'env_file' not in service_dict:
  257. return service_dict
  258. env = {}
  259. if 'env_file' in service_dict:
  260. for f in get_env_files(service_dict, working_dir=working_dir):
  261. env.update(env_vars_from_file(f))
  262. del service_dict['env_file']
  263. env.update(parse_environment(service_dict.get('environment')))
  264. env = dict(resolve_env_var(k, v) for k, v in six.iteritems(env))
  265. service_dict['environment'] = env
  266. return service_dict
  267. def parse_environment(environment):
  268. if not environment:
  269. return {}
  270. if isinstance(environment, list):
  271. return dict(split_env(e) for e in environment)
  272. if isinstance(environment, dict):
  273. return environment
  274. raise ConfigurationError(
  275. "environment \"%s\" must be a list or mapping," %
  276. environment
  277. )
  278. def split_env(env):
  279. if '=' in env:
  280. return env.split('=', 1)
  281. else:
  282. return env, None
  283. def resolve_env_var(key, val):
  284. if val is not None:
  285. return key, val
  286. elif key in os.environ:
  287. return key, os.environ[key]
  288. else:
  289. return key, ''
  290. def env_vars_from_file(filename):
  291. """
  292. Read in a line delimited file of environment variables.
  293. """
  294. if not os.path.exists(filename):
  295. raise ConfigurationError("Couldn't find env file: %s" % filename)
  296. env = {}
  297. for line in open(filename, 'r'):
  298. line = line.strip()
  299. if line and not line.startswith('#'):
  300. k, v = split_env(line)
  301. env[k] = v
  302. return env
  303. def resolve_volume_paths(volumes, working_dir=None):
  304. if working_dir is None:
  305. raise Exception("No working_dir passed to resolve_volume_paths()")
  306. return [resolve_volume_path(v, working_dir) for v in volumes]
  307. def resolve_volume_path(volume, working_dir):
  308. container_path, host_path = split_path_mapping(volume)
  309. container_path = os.path.expanduser(os.path.expandvars(container_path))
  310. if host_path is not None:
  311. host_path = os.path.expanduser(os.path.expandvars(host_path))
  312. return "%s:%s" % (expand_path(working_dir, host_path), container_path)
  313. else:
  314. return container_path
  315. def resolve_build_path(build_path, working_dir=None):
  316. if working_dir is None:
  317. raise Exception("No working_dir passed to resolve_build_path")
  318. return expand_path(working_dir, build_path)
  319. def validate_paths(service_dict):
  320. if 'build' in service_dict:
  321. build_path = service_dict['build']
  322. if not os.path.exists(build_path) or not os.access(build_path, os.R_OK):
  323. raise ConfigurationError("build path %s either does not exist or is not accessible." % build_path)
  324. def merge_path_mappings(base, override):
  325. d = dict_from_path_mappings(base)
  326. d.update(dict_from_path_mappings(override))
  327. return path_mappings_from_dict(d)
  328. def dict_from_path_mappings(path_mappings):
  329. if path_mappings:
  330. return dict(split_path_mapping(v) for v in path_mappings)
  331. else:
  332. return {}
  333. def path_mappings_from_dict(d):
  334. return [join_path_mapping(v) for v in d.items()]
  335. def split_path_mapping(string):
  336. if ':' in string:
  337. (host, container) = string.split(':', 1)
  338. return (container, host)
  339. else:
  340. return (string, None)
  341. def join_path_mapping(pair):
  342. (container, host) = pair
  343. if host is None:
  344. return container
  345. else:
  346. return ":".join((host, container))
  347. def merge_labels(base, override):
  348. labels = parse_labels(base)
  349. labels.update(parse_labels(override))
  350. return labels
  351. def parse_labels(labels):
  352. if not labels:
  353. return {}
  354. if isinstance(labels, list):
  355. return dict(split_label(e) for e in labels)
  356. if isinstance(labels, dict):
  357. return labels
  358. raise ConfigurationError(
  359. "labels \"%s\" must be a list or mapping" %
  360. labels
  361. )
  362. def split_label(label):
  363. if '=' in label:
  364. return label.split('=', 1)
  365. else:
  366. return label, ''
  367. def expand_path(working_dir, path):
  368. return os.path.abspath(os.path.join(working_dir, path))
  369. def to_list(value):
  370. if value is None:
  371. return []
  372. elif isinstance(value, six.string_types):
  373. return [value]
  374. else:
  375. return value
  376. def get_service_name_from_net(net_config):
  377. if not net_config:
  378. return
  379. if not net_config.startswith('container:'):
  380. return
  381. _, net_name = net_config.split(':', 1)
  382. return net_name
  383. def load_yaml(filename):
  384. try:
  385. with open(filename, 'r') as fh:
  386. return yaml.safe_load(fh)
  387. except IOError as e:
  388. raise ConfigurationError(six.text_type(e))
  389. class ConfigurationError(Exception):
  390. def __init__(self, msg):
  391. self.msg = msg
  392. def __str__(self):
  393. return self.msg
  394. class CircularReference(ConfigurationError):
  395. def __init__(self, trail):
  396. self.trail = trail
  397. @property
  398. def msg(self):
  399. lines = [
  400. "{} in {}".format(service_name, filename)
  401. for (filename, service_name) in self.trail
  402. ]
  403. return "Circular reference:\n {}".format("\n extends ".join(lines))
  404. class ComposeFileNotFound(ConfigurationError):
  405. def __init__(self, supported_filenames):
  406. super(ComposeFileNotFound, self).__init__("""
  407. Can't find a suitable configuration file in this directory or any parent. Are you in the right directory?
  408. Supported filenames: %s
  409. """ % ", ".join(supported_filenames))