config.py 15 KB

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