config.py 15 KB

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