config.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523
  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 validate_against_schema
  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. def load(config_details):
  100. config, working_dir, filename = config_details
  101. if not isinstance(config, dict):
  102. raise ConfigurationError(
  103. "Top level object needs to be a dictionary. Check your .yml file that you have defined a service at the top level."
  104. )
  105. config = interpolate_environment_variables(config)
  106. validate_against_schema(config)
  107. service_dicts = []
  108. for service_name, service_dict in list(config.items()):
  109. loader = ServiceLoader(working_dir=working_dir, filename=filename)
  110. service_dict = loader.make_service_dict(service_name, service_dict)
  111. validate_paths(service_dict)
  112. service_dicts.append(service_dict)
  113. return service_dicts
  114. class ServiceLoader(object):
  115. def __init__(self, working_dir, filename=None, already_seen=None):
  116. self.working_dir = os.path.abspath(working_dir)
  117. if filename:
  118. self.filename = os.path.abspath(filename)
  119. else:
  120. self.filename = filename
  121. self.already_seen = already_seen or []
  122. def detect_cycle(self, name):
  123. if self.signature(name) in self.already_seen:
  124. raise CircularReference(self.already_seen + [self.signature(name)])
  125. def make_service_dict(self, name, service_dict):
  126. service_dict = service_dict.copy()
  127. service_dict['name'] = name
  128. service_dict = resolve_environment(service_dict, working_dir=self.working_dir)
  129. service_dict = self.resolve_extends(service_dict)
  130. return process_container_options(service_dict, working_dir=self.working_dir)
  131. def resolve_extends(self, service_dict):
  132. if 'extends' not in service_dict:
  133. return service_dict
  134. extends_options = self.validate_extends_options(service_dict['name'], service_dict['extends'])
  135. if self.working_dir is None:
  136. raise Exception("No working_dir passed to ServiceLoader()")
  137. if 'file' in extends_options:
  138. extends_from_filename = extends_options['file']
  139. other_config_path = expand_path(self.working_dir, extends_from_filename)
  140. else:
  141. other_config_path = self.filename
  142. other_working_dir = os.path.dirname(other_config_path)
  143. other_already_seen = self.already_seen + [self.signature(service_dict['name'])]
  144. other_loader = ServiceLoader(
  145. working_dir=other_working_dir,
  146. filename=other_config_path,
  147. already_seen=other_already_seen,
  148. )
  149. base_service = extends_options['service']
  150. other_config = load_yaml(other_config_path)
  151. if base_service not in other_config:
  152. msg = (
  153. "Cannot extend service '%s' in %s: Service not found"
  154. ) % (base_service, other_config_path)
  155. raise ConfigurationError(msg)
  156. other_service_dict = other_config[base_service]
  157. other_loader.detect_cycle(extends_options['service'])
  158. other_service_dict = other_loader.make_service_dict(
  159. service_dict['name'],
  160. other_service_dict,
  161. )
  162. validate_extended_service_dict(
  163. other_service_dict,
  164. filename=other_config_path,
  165. service=extends_options['service'],
  166. )
  167. return merge_service_dicts(other_service_dict, service_dict)
  168. def signature(self, name):
  169. return (self.filename, name)
  170. def validate_extends_options(self, service_name, extends_options):
  171. error_prefix = "Invalid 'extends' configuration for %s:" % service_name
  172. if 'file' not in extends_options and self.filename is None:
  173. raise ConfigurationError(
  174. "%s you need to specify a 'file', e.g. 'file: something.yml'" % error_prefix
  175. )
  176. return extends_options
  177. def validate_extended_service_dict(service_dict, filename, service):
  178. error_prefix = "Cannot extend service '%s' in %s:" % (service, filename)
  179. if 'links' in service_dict:
  180. raise ConfigurationError("%s services with 'links' cannot be extended" % error_prefix)
  181. if 'volumes_from' in service_dict:
  182. raise ConfigurationError("%s services with 'volumes_from' cannot be extended" % error_prefix)
  183. if 'net' in service_dict:
  184. if get_service_name_from_net(service_dict['net']) is not None:
  185. raise ConfigurationError("%s services with 'net: container' cannot be extended" % error_prefix)
  186. def process_container_options(service_dict, working_dir=None):
  187. service_dict = service_dict.copy()
  188. if 'volumes' in service_dict and service_dict.get('volume_driver') is None:
  189. service_dict['volumes'] = resolve_volume_paths(service_dict, working_dir=working_dir)
  190. if 'build' in service_dict:
  191. service_dict['build'] = resolve_build_path(service_dict['build'], working_dir=working_dir)
  192. if 'labels' in service_dict:
  193. service_dict['labels'] = parse_labels(service_dict['labels'])
  194. return service_dict
  195. def merge_service_dicts(base, override):
  196. d = base.copy()
  197. if 'environment' in base or 'environment' in override:
  198. d['environment'] = merge_environment(
  199. base.get('environment'),
  200. override.get('environment'),
  201. )
  202. path_mapping_keys = ['volumes', 'devices']
  203. for key in path_mapping_keys:
  204. if key in base or key in override:
  205. d[key] = merge_path_mappings(
  206. base.get(key),
  207. override.get(key),
  208. )
  209. if 'labels' in base or 'labels' in override:
  210. d['labels'] = merge_labels(
  211. base.get('labels'),
  212. override.get('labels'),
  213. )
  214. if 'image' in override and 'build' in d:
  215. del d['build']
  216. if 'build' in override and 'image' in d:
  217. del d['image']
  218. list_keys = ['ports', 'expose', 'external_links']
  219. for key in list_keys:
  220. if key in base or key in override:
  221. d[key] = base.get(key, []) + override.get(key, [])
  222. list_or_string_keys = ['dns', 'dns_search']
  223. for key in list_or_string_keys:
  224. if key in base or key in override:
  225. d[key] = to_list(base.get(key)) + to_list(override.get(key))
  226. already_merged_keys = ['environment', 'labels'] + path_mapping_keys + list_keys + list_or_string_keys
  227. for k in set(ALLOWED_KEYS) - set(already_merged_keys):
  228. if k in override:
  229. d[k] = override[k]
  230. return d
  231. def merge_environment(base, override):
  232. env = parse_environment(base)
  233. env.update(parse_environment(override))
  234. return env
  235. def get_env_files(options, working_dir=None):
  236. if 'env_file' not in options:
  237. return {}
  238. if working_dir is None:
  239. raise Exception("No working_dir passed to get_env_files()")
  240. env_files = options.get('env_file', [])
  241. if not isinstance(env_files, list):
  242. env_files = [env_files]
  243. return [expand_path(working_dir, path) for path in env_files]
  244. def resolve_environment(service_dict, working_dir=None):
  245. service_dict = service_dict.copy()
  246. if 'environment' not in service_dict and 'env_file' not in service_dict:
  247. return service_dict
  248. env = {}
  249. if 'env_file' in service_dict:
  250. for f in get_env_files(service_dict, working_dir=working_dir):
  251. env.update(env_vars_from_file(f))
  252. del service_dict['env_file']
  253. env.update(parse_environment(service_dict.get('environment')))
  254. env = dict(resolve_env_var(k, v) for k, v in six.iteritems(env))
  255. service_dict['environment'] = env
  256. return service_dict
  257. def parse_environment(environment):
  258. if not environment:
  259. return {}
  260. if isinstance(environment, list):
  261. return dict(split_env(e) for e in environment)
  262. if isinstance(environment, dict):
  263. return environment
  264. raise ConfigurationError(
  265. "environment \"%s\" must be a list or mapping," %
  266. environment
  267. )
  268. def split_env(env):
  269. if '=' in env:
  270. return env.split('=', 1)
  271. else:
  272. return env, None
  273. def resolve_env_var(key, val):
  274. if val is not None:
  275. return key, val
  276. elif key in os.environ:
  277. return key, os.environ[key]
  278. else:
  279. return key, ''
  280. def env_vars_from_file(filename):
  281. """
  282. Read in a line delimited file of environment variables.
  283. """
  284. if not os.path.exists(filename):
  285. raise ConfigurationError("Couldn't find env file: %s" % filename)
  286. env = {}
  287. for line in open(filename, 'r'):
  288. line = line.strip()
  289. if line and not line.startswith('#'):
  290. k, v = split_env(line)
  291. env[k] = v
  292. return env
  293. def resolve_volume_paths(service_dict, working_dir=None):
  294. if working_dir is None:
  295. raise Exception("No working_dir passed to resolve_volume_paths()")
  296. return [
  297. resolve_volume_path(v, working_dir, service_dict['name'])
  298. for v in service_dict['volumes']
  299. ]
  300. def resolve_volume_path(volume, working_dir, service_name):
  301. container_path, host_path = split_path_mapping(volume)
  302. container_path = os.path.expanduser(container_path)
  303. if host_path is not None:
  304. if not any(host_path.startswith(c) for c in PATH_START_CHARS):
  305. log.warn(
  306. 'Warning: the mapping "{0}:{1}" in the volumes config for '
  307. 'service "{2}" is ambiguous. In a future version of Docker, '
  308. 'it will designate a "named" volume '
  309. '(see https://github.com/docker/docker/pull/14242). '
  310. 'To prevent unexpected behaviour, change it to "./{0}:{1}"'
  311. .format(host_path, container_path, service_name)
  312. )
  313. host_path = os.path.expanduser(host_path)
  314. return "%s:%s" % (expand_path(working_dir, host_path), container_path)
  315. else:
  316. return container_path
  317. def resolve_build_path(build_path, working_dir=None):
  318. if working_dir is None:
  319. raise Exception("No working_dir passed to resolve_build_path")
  320. return expand_path(working_dir, build_path)
  321. def validate_paths(service_dict):
  322. if 'build' in service_dict:
  323. build_path = service_dict['build']
  324. if not os.path.exists(build_path) or not os.access(build_path, os.R_OK):
  325. raise ConfigurationError("build path %s either does not exist or is not accessible." % build_path)
  326. def merge_path_mappings(base, override):
  327. d = dict_from_path_mappings(base)
  328. d.update(dict_from_path_mappings(override))
  329. return path_mappings_from_dict(d)
  330. def dict_from_path_mappings(path_mappings):
  331. if path_mappings:
  332. return dict(split_path_mapping(v) for v in path_mappings)
  333. else:
  334. return {}
  335. def path_mappings_from_dict(d):
  336. return [join_path_mapping(v) for v in d.items()]
  337. def split_path_mapping(string):
  338. if ':' in string:
  339. (host, container) = string.split(':', 1)
  340. return (container, host)
  341. else:
  342. return (string, None)
  343. def join_path_mapping(pair):
  344. (container, host) = pair
  345. if host is None:
  346. return container
  347. else:
  348. return ":".join((host, container))
  349. def merge_labels(base, override):
  350. labels = parse_labels(base)
  351. labels.update(parse_labels(override))
  352. return labels
  353. def parse_labels(labels):
  354. if not labels:
  355. return {}
  356. if isinstance(labels, list):
  357. return dict(split_label(e) for e in labels)
  358. if isinstance(labels, dict):
  359. return labels
  360. def split_label(label):
  361. if '=' in label:
  362. return label.split('=', 1)
  363. else:
  364. return label, ''
  365. def expand_path(working_dir, path):
  366. return os.path.abspath(os.path.join(working_dir, path))
  367. def to_list(value):
  368. if value is None:
  369. return []
  370. elif isinstance(value, six.string_types):
  371. return [value]
  372. else:
  373. return value
  374. def get_service_name_from_net(net_config):
  375. if not net_config:
  376. return
  377. if not net_config.startswith('container:'):
  378. return
  379. _, net_name = net_config.split(':', 1)
  380. return net_name
  381. def load_yaml(filename):
  382. try:
  383. with open(filename, 'r') as fh:
  384. return yaml.safe_load(fh)
  385. except IOError as e:
  386. raise ConfigurationError(six.text_type(e))