config.py 15 KB

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