config.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639
  1. import logging
  2. import os
  3. import sys
  4. import yaml
  5. from collections import namedtuple
  6. import json
  7. from jsonschema import Draft4Validator, FormatChecker, ValidationError
  8. import six
  9. from compose.cli.utils import find_candidates_in_parent_dirs
  10. from .interpolation import interpolate_environment_variables
  11. from .errors import (
  12. ConfigurationError,
  13. CircularReference,
  14. ComposeFileNotFound,
  15. )
  16. VALID_NAME_CHARS = '[a-zA-Z0-9\._\-]'
  17. DOCKER_CONFIG_KEYS = [
  18. 'cap_add',
  19. 'cap_drop',
  20. 'cpu_shares',
  21. 'cpuset',
  22. 'command',
  23. 'detach',
  24. 'devices',
  25. 'dns',
  26. 'dns_search',
  27. 'domainname',
  28. 'entrypoint',
  29. 'env_file',
  30. 'environment',
  31. 'extra_hosts',
  32. 'hostname',
  33. 'image',
  34. 'labels',
  35. 'links',
  36. 'mac_address',
  37. 'mem_limit',
  38. 'memswap_limit',
  39. 'net',
  40. 'log_driver',
  41. 'log_opt',
  42. 'pid',
  43. 'ports',
  44. 'privileged',
  45. 'read_only',
  46. 'restart',
  47. 'security_opt',
  48. 'stdin_open',
  49. 'tty',
  50. 'user',
  51. 'volume_driver',
  52. 'volumes',
  53. 'volumes_from',
  54. 'working_dir',
  55. ]
  56. ALLOWED_KEYS = DOCKER_CONFIG_KEYS + [
  57. 'build',
  58. 'container_name',
  59. 'dockerfile',
  60. 'expose',
  61. 'external_links',
  62. 'name',
  63. ]
  64. DOCKER_CONFIG_HINTS = {
  65. 'cpu_share': 'cpu_shares',
  66. 'add_host': 'extra_hosts',
  67. 'hosts': 'extra_hosts',
  68. 'extra_host': 'extra_hosts',
  69. 'device': 'devices',
  70. 'link': 'links',
  71. 'memory_swap': 'memswap_limit',
  72. 'port': 'ports',
  73. 'privilege': 'privileged',
  74. 'priviliged': 'privileged',
  75. 'privilige': 'privileged',
  76. 'volume': 'volumes',
  77. 'workdir': 'working_dir',
  78. }
  79. SUPPORTED_FILENAMES = [
  80. 'docker-compose.yml',
  81. 'docker-compose.yaml',
  82. 'fig.yml',
  83. 'fig.yaml',
  84. ]
  85. log = logging.getLogger(__name__)
  86. ConfigDetails = namedtuple('ConfigDetails', 'config working_dir filename')
  87. def find(base_dir, filename):
  88. if filename == '-':
  89. return ConfigDetails(yaml.safe_load(sys.stdin), os.getcwd(), None)
  90. if filename:
  91. filename = os.path.join(base_dir, filename)
  92. else:
  93. filename = get_config_path(base_dir)
  94. return ConfigDetails(load_yaml(filename), os.path.dirname(filename), filename)
  95. def get_config_path(base_dir):
  96. (candidates, path) = find_candidates_in_parent_dirs(SUPPORTED_FILENAMES, base_dir)
  97. if len(candidates) == 0:
  98. raise ComposeFileNotFound(SUPPORTED_FILENAMES)
  99. winner = candidates[0]
  100. if len(candidates) > 1:
  101. log.warn("Found multiple config files with supported names: %s", ", ".join(candidates))
  102. log.warn("Using %s\n", winner)
  103. if winner == 'docker-compose.yaml':
  104. log.warn("Please be aware that .yml is the expected extension "
  105. "in most cases, and using .yaml can cause compatibility "
  106. "issues in future.\n")
  107. if winner.startswith("fig."):
  108. log.warn("%s is deprecated and will not be supported in future. "
  109. "Please rename your config file to docker-compose.yml\n" % winner)
  110. return os.path.join(path, winner)
  111. @FormatChecker.cls_checks(format="ports", raises=ValidationError("Ports is incorrectly formatted."))
  112. def format_ports(instance):
  113. def _is_valid(port):
  114. if ':' in port or '/' in port:
  115. return True
  116. try:
  117. int(port)
  118. return True
  119. except ValueError:
  120. return False
  121. return False
  122. if isinstance(instance, list):
  123. for port in instance:
  124. if not _is_valid(port):
  125. return False
  126. return True
  127. elif isinstance(instance, str):
  128. return _is_valid(instance)
  129. return False
  130. def get_unsupported_config_msg(service_name, error_key):
  131. msg = "Unsupported config option for '{}' service: '{}'".format(service_name, error_key)
  132. if error_key in DOCKER_CONFIG_HINTS:
  133. msg += " (did you mean '{}'?)".format(DOCKER_CONFIG_HINTS[error_key])
  134. return msg
  135. def process_errors(errors):
  136. """
  137. jsonschema gives us an error tree full of information to explain what has
  138. gone wrong. Process each error and pull out relevant information and re-write
  139. helpful error messages that are relevant.
  140. """
  141. def _parse_key_from_error_msg(error):
  142. return error.message.split("'")[1]
  143. root_msgs = []
  144. invalid_keys = []
  145. required = []
  146. type_errors = []
  147. for error in errors:
  148. # handle root level errors
  149. if len(error.path) == 0:
  150. if error.validator == 'type':
  151. msg = "Top level object needs to be a dictionary. Check your .yml file that you have defined a service at the top level."
  152. root_msgs.append(msg)
  153. elif error.validator == 'additionalProperties':
  154. invalid_service_name = _parse_key_from_error_msg(error)
  155. msg = "Invalid service name '{}' - only {} characters are allowed".format(invalid_service_name, VALID_NAME_CHARS)
  156. root_msgs.append(msg)
  157. else:
  158. root_msgs.append(error.message)
  159. else:
  160. # handle service level errors
  161. service_name = error.path[0]
  162. if error.validator == 'additionalProperties':
  163. invalid_config_key = _parse_key_from_error_msg(error)
  164. invalid_keys.append(get_unsupported_config_msg(service_name, invalid_config_key))
  165. elif error.validator == 'anyOf':
  166. if 'image' in error.instance and 'build' in error.instance:
  167. required.append("Service '{}' has both an image and build path specified. A service can either be built to image or use an existing image, not both.".format(service_name))
  168. elif 'image' not in error.instance and 'build' not in error.instance:
  169. required.append("Service '{}' has neither an image nor a build path specified. Exactly one must be provided.".format(service_name))
  170. else:
  171. required.append(error.message)
  172. elif error.validator == 'type':
  173. msg = "a"
  174. if error.validator_value == "array":
  175. msg = "an"
  176. try:
  177. config_key = error.path[1]
  178. type_errors.append("Service '{}' has an invalid value for '{}', it should be {} {}".format(service_name, config_key, msg, error.validator_value))
  179. except IndexError:
  180. config_key = error.path[0]
  181. root_msgs.append("Service '{}' doesn\'t have any configuration options. All top level keys in your docker-compose.yml must map to a dictionary of configuration options.'".format(config_key))
  182. elif error.validator == 'required':
  183. config_key = error.path[1]
  184. required.append("Service '{}' option '{}' is invalid, {}".format(service_name, config_key, error.message))
  185. elif error.validator == 'dependencies':
  186. dependency_key = error.validator_value.keys()[0]
  187. required_keys = ",".join(error.validator_value[dependency_key])
  188. required.append("Invalid '{}' configuration for '{}' service: when defining '{}' you must set '{}' as well".format(
  189. dependency_key, service_name, dependency_key, required_keys))
  190. return "\n".join(root_msgs + invalid_keys + required + type_errors)
  191. def validate_against_schema(config):
  192. config_source_dir = os.path.dirname(os.path.abspath(__file__))
  193. schema_file = os.path.join(config_source_dir, "schema.json")
  194. with open(schema_file, "r") as schema_fh:
  195. schema = json.load(schema_fh)
  196. validation_output = Draft4Validator(schema, format_checker=FormatChecker(["ports"]))
  197. errors = [error for error in sorted(validation_output.iter_errors(config), key=str)]
  198. if errors:
  199. error_msg = process_errors(errors)
  200. raise ConfigurationError("Validation failed, reason(s):\n{}".format(error_msg))
  201. def load(config_details):
  202. config, working_dir, filename = config_details
  203. config = interpolate_environment_variables(config)
  204. service_dicts = []
  205. validate_against_schema(config)
  206. for service_name, service_dict in list(config.items()):
  207. if not isinstance(service_dict, dict):
  208. 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)
  209. loader = ServiceLoader(working_dir=working_dir, filename=filename)
  210. service_dict = loader.make_service_dict(service_name, service_dict)
  211. validate_paths(service_dict)
  212. service_dicts.append(service_dict)
  213. return service_dicts
  214. class ServiceLoader(object):
  215. def __init__(self, working_dir, filename=None, already_seen=None):
  216. self.working_dir = os.path.abspath(working_dir)
  217. if filename:
  218. self.filename = os.path.abspath(filename)
  219. else:
  220. self.filename = filename
  221. self.already_seen = already_seen or []
  222. def detect_cycle(self, name):
  223. if self.signature(name) in self.already_seen:
  224. raise CircularReference(self.already_seen + [self.signature(name)])
  225. def make_service_dict(self, name, service_dict):
  226. service_dict = service_dict.copy()
  227. service_dict['name'] = name
  228. service_dict = resolve_environment(service_dict, working_dir=self.working_dir)
  229. service_dict = self.resolve_extends(service_dict)
  230. return process_container_options(service_dict, working_dir=self.working_dir)
  231. def resolve_extends(self, service_dict):
  232. if 'extends' not in service_dict:
  233. return service_dict
  234. extends_options = self.validate_extends_options(service_dict['name'], service_dict['extends'])
  235. if self.working_dir is None:
  236. raise Exception("No working_dir passed to ServiceLoader()")
  237. if 'file' in extends_options:
  238. extends_from_filename = extends_options['file']
  239. other_config_path = expand_path(self.working_dir, extends_from_filename)
  240. else:
  241. other_config_path = self.filename
  242. other_working_dir = os.path.dirname(other_config_path)
  243. other_already_seen = self.already_seen + [self.signature(service_dict['name'])]
  244. other_loader = ServiceLoader(
  245. working_dir=other_working_dir,
  246. filename=other_config_path,
  247. already_seen=other_already_seen,
  248. )
  249. other_config = load_yaml(other_config_path)
  250. other_service_dict = other_config[extends_options['service']]
  251. other_loader.detect_cycle(extends_options['service'])
  252. other_service_dict = other_loader.make_service_dict(
  253. service_dict['name'],
  254. other_service_dict,
  255. )
  256. validate_extended_service_dict(
  257. other_service_dict,
  258. filename=other_config_path,
  259. service=extends_options['service'],
  260. )
  261. return merge_service_dicts(other_service_dict, service_dict)
  262. def signature(self, name):
  263. return (self.filename, name)
  264. def validate_extends_options(self, service_name, extends_options):
  265. error_prefix = "Invalid 'extends' configuration for %s:" % service_name
  266. if 'file' not in extends_options and self.filename is None:
  267. raise ConfigurationError(
  268. "%s you need to specify a 'file', e.g. 'file: something.yml'" % error_prefix
  269. )
  270. return extends_options
  271. def validate_extended_service_dict(service_dict, filename, service):
  272. error_prefix = "Cannot extend service '%s' in %s:" % (service, filename)
  273. if 'links' in service_dict:
  274. raise ConfigurationError("%s services with 'links' cannot be extended" % error_prefix)
  275. if 'volumes_from' in service_dict:
  276. raise ConfigurationError("%s services with 'volumes_from' cannot be extended" % error_prefix)
  277. if 'net' in service_dict:
  278. if get_service_name_from_net(service_dict['net']) is not None:
  279. raise ConfigurationError("%s services with 'net: container' cannot be extended" % error_prefix)
  280. def process_container_options(service_dict, working_dir=None):
  281. for k in service_dict:
  282. if k not in ALLOWED_KEYS:
  283. msg = "Unsupported config option for %s service: '%s'" % (service_dict['name'], k)
  284. if k in DOCKER_CONFIG_HINTS:
  285. msg += " (did you mean '%s'?)" % DOCKER_CONFIG_HINTS[k]
  286. raise ConfigurationError(msg)
  287. service_dict = service_dict.copy()
  288. if 'volumes' in service_dict and service_dict.get('volume_driver') is None:
  289. service_dict['volumes'] = resolve_volume_paths(service_dict['volumes'], working_dir=working_dir)
  290. if 'build' in service_dict:
  291. service_dict['build'] = resolve_build_path(service_dict['build'], working_dir=working_dir)
  292. if 'labels' in service_dict:
  293. service_dict['labels'] = parse_labels(service_dict['labels'])
  294. return service_dict
  295. def merge_service_dicts(base, override):
  296. d = base.copy()
  297. if 'environment' in base or 'environment' in override:
  298. d['environment'] = merge_environment(
  299. base.get('environment'),
  300. override.get('environment'),
  301. )
  302. path_mapping_keys = ['volumes', 'devices']
  303. for key in path_mapping_keys:
  304. if key in base or key in override:
  305. d[key] = merge_path_mappings(
  306. base.get(key),
  307. override.get(key),
  308. )
  309. if 'labels' in base or 'labels' in override:
  310. d['labels'] = merge_labels(
  311. base.get('labels'),
  312. override.get('labels'),
  313. )
  314. if 'image' in override and 'build' in d:
  315. del d['build']
  316. if 'build' in override and 'image' in d:
  317. del d['image']
  318. list_keys = ['ports', 'expose', 'external_links']
  319. for key in list_keys:
  320. if key in base or key in override:
  321. d[key] = base.get(key, []) + override.get(key, [])
  322. list_or_string_keys = ['dns', 'dns_search']
  323. for key in list_or_string_keys:
  324. if key in base or key in override:
  325. d[key] = to_list(base.get(key)) + to_list(override.get(key))
  326. already_merged_keys = ['environment', 'labels'] + path_mapping_keys + list_keys + list_or_string_keys
  327. for k in set(ALLOWED_KEYS) - set(already_merged_keys):
  328. if k in override:
  329. d[k] = override[k]
  330. return d
  331. def merge_environment(base, override):
  332. env = parse_environment(base)
  333. env.update(parse_environment(override))
  334. return env
  335. def parse_links(links):
  336. return dict(parse_link(l) for l in links)
  337. def parse_link(link):
  338. if ':' in link:
  339. source, alias = link.split(':', 1)
  340. return (alias, source)
  341. else:
  342. return (link, link)
  343. def get_env_files(options, working_dir=None):
  344. if 'env_file' not in options:
  345. return {}
  346. if working_dir is None:
  347. raise Exception("No working_dir passed to get_env_files()")
  348. env_files = options.get('env_file', [])
  349. if not isinstance(env_files, list):
  350. env_files = [env_files]
  351. return [expand_path(working_dir, path) for path in env_files]
  352. def resolve_environment(service_dict, working_dir=None):
  353. service_dict = service_dict.copy()
  354. if 'environment' not in service_dict and 'env_file' not in service_dict:
  355. return service_dict
  356. env = {}
  357. if 'env_file' in service_dict:
  358. for f in get_env_files(service_dict, working_dir=working_dir):
  359. env.update(env_vars_from_file(f))
  360. del service_dict['env_file']
  361. env.update(parse_environment(service_dict.get('environment')))
  362. env = dict(resolve_env_var(k, v) for k, v in six.iteritems(env))
  363. service_dict['environment'] = env
  364. return service_dict
  365. def parse_environment(environment):
  366. if not environment:
  367. return {}
  368. if isinstance(environment, list):
  369. return dict(split_env(e) for e in environment)
  370. if isinstance(environment, dict):
  371. return environment
  372. raise ConfigurationError(
  373. "environment \"%s\" must be a list or mapping," %
  374. environment
  375. )
  376. def split_env(env):
  377. if '=' in env:
  378. return env.split('=', 1)
  379. else:
  380. return env, None
  381. def resolve_env_var(key, val):
  382. if val is not None:
  383. return key, val
  384. elif key in os.environ:
  385. return key, os.environ[key]
  386. else:
  387. return key, ''
  388. def env_vars_from_file(filename):
  389. """
  390. Read in a line delimited file of environment variables.
  391. """
  392. if not os.path.exists(filename):
  393. raise ConfigurationError("Couldn't find env file: %s" % filename)
  394. env = {}
  395. for line in open(filename, 'r'):
  396. line = line.strip()
  397. if line and not line.startswith('#'):
  398. k, v = split_env(line)
  399. env[k] = v
  400. return env
  401. def resolve_volume_paths(volumes, working_dir=None):
  402. if working_dir is None:
  403. raise Exception("No working_dir passed to resolve_volume_paths()")
  404. return [resolve_volume_path(v, working_dir) for v in volumes]
  405. def resolve_volume_path(volume, working_dir):
  406. container_path, host_path = split_path_mapping(volume)
  407. container_path = os.path.expanduser(container_path)
  408. if host_path is not None:
  409. host_path = os.path.expanduser(host_path)
  410. return "%s:%s" % (expand_path(working_dir, host_path), container_path)
  411. else:
  412. return container_path
  413. def resolve_build_path(build_path, working_dir=None):
  414. if working_dir is None:
  415. raise Exception("No working_dir passed to resolve_build_path")
  416. return expand_path(working_dir, build_path)
  417. def validate_paths(service_dict):
  418. if 'build' in service_dict:
  419. build_path = service_dict['build']
  420. if not os.path.exists(build_path) or not os.access(build_path, os.R_OK):
  421. raise ConfigurationError("build path %s either does not exist or is not accessible." % build_path)
  422. def merge_path_mappings(base, override):
  423. d = dict_from_path_mappings(base)
  424. d.update(dict_from_path_mappings(override))
  425. return path_mappings_from_dict(d)
  426. def dict_from_path_mappings(path_mappings):
  427. if path_mappings:
  428. return dict(split_path_mapping(v) for v in path_mappings)
  429. else:
  430. return {}
  431. def path_mappings_from_dict(d):
  432. return [join_path_mapping(v) for v in d.items()]
  433. def split_path_mapping(string):
  434. if ':' in string:
  435. (host, container) = string.split(':', 1)
  436. return (container, host)
  437. else:
  438. return (string, None)
  439. def join_path_mapping(pair):
  440. (container, host) = pair
  441. if host is None:
  442. return container
  443. else:
  444. return ":".join((host, container))
  445. def merge_labels(base, override):
  446. labels = parse_labels(base)
  447. labels.update(parse_labels(override))
  448. return labels
  449. def parse_labels(labels):
  450. if not labels:
  451. return {}
  452. if isinstance(labels, list):
  453. return dict(split_label(e) for e in labels)
  454. if isinstance(labels, dict):
  455. return labels
  456. def split_label(label):
  457. if '=' in label:
  458. return label.split('=', 1)
  459. else:
  460. return label, ''
  461. def expand_path(working_dir, path):
  462. return os.path.abspath(os.path.join(working_dir, path))
  463. def to_list(value):
  464. if value is None:
  465. return []
  466. elif isinstance(value, six.string_types):
  467. return [value]
  468. else:
  469. return value
  470. def get_service_name_from_net(net_config):
  471. if not net_config:
  472. return
  473. if not net_config.startswith('container:'):
  474. return
  475. _, net_name = net_config.split(':', 1)
  476. return net_name
  477. def load_yaml(filename):
  478. try:
  479. with open(filename, 'r') as fh:
  480. return yaml.safe_load(fh)
  481. except IOError as e:
  482. raise ConfigurationError(six.text_type(e))