config.py 18 KB

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