config.py 15 KB

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