config.py 15 KB

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