config.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662
  1. from __future__ import absolute_import
  2. import codecs
  3. import logging
  4. import operator
  5. import os
  6. import sys
  7. from collections import namedtuple
  8. import six
  9. import yaml
  10. from .errors import CircularReference
  11. from .errors import ComposeFileNotFound
  12. from .errors import ConfigurationError
  13. from .interpolation import interpolate_environment_variables
  14. from .sort_services import get_service_name_from_net
  15. from .sort_services import sort_service_dicts
  16. from .types import parse_extra_hosts
  17. from .types import parse_restart_spec
  18. from .types import VolumeFromSpec
  19. from .types import VolumeSpec
  20. from .validation import validate_against_fields_schema
  21. from .validation import validate_against_service_schema
  22. from .validation import validate_extends_file_path
  23. from .validation import validate_top_level_object
  24. DOCKER_CONFIG_KEYS = [
  25. 'cap_add',
  26. 'cap_drop',
  27. 'cgroup_parent',
  28. 'command',
  29. 'cpu_shares',
  30. 'cpuset',
  31. 'detach',
  32. 'devices',
  33. 'dns',
  34. 'dns_search',
  35. 'domainname',
  36. 'entrypoint',
  37. 'env_file',
  38. 'environment',
  39. 'extra_hosts',
  40. 'hostname',
  41. 'image',
  42. 'ipc',
  43. 'labels',
  44. 'links',
  45. 'log_driver',
  46. 'log_opt',
  47. 'mac_address',
  48. 'mem_limit',
  49. 'memswap_limit',
  50. 'net',
  51. 'pid',
  52. 'ports',
  53. 'privileged',
  54. 'read_only',
  55. 'restart',
  56. 'security_opt',
  57. 'stdin_open',
  58. 'tty',
  59. 'user',
  60. 'volume_driver',
  61. 'volumes',
  62. 'volumes_from',
  63. 'working_dir',
  64. ]
  65. ALLOWED_KEYS = DOCKER_CONFIG_KEYS + [
  66. 'build',
  67. 'container_name',
  68. 'dockerfile',
  69. 'expose',
  70. 'external_links',
  71. ]
  72. DOCKER_VALID_URL_PREFIXES = (
  73. 'http://',
  74. 'https://',
  75. 'git://',
  76. 'github.com/',
  77. 'git@',
  78. )
  79. SUPPORTED_FILENAMES = [
  80. 'docker-compose.yml',
  81. 'docker-compose.yaml',
  82. 'fig.yml',
  83. 'fig.yaml',
  84. ]
  85. DEFAULT_OVERRIDE_FILENAME = 'docker-compose.override.yml'
  86. log = logging.getLogger(__name__)
  87. class ConfigDetails(namedtuple('_ConfigDetails', 'working_dir config_files')):
  88. """
  89. :param working_dir: the directory to use for relative paths in the config
  90. :type working_dir: string
  91. :param config_files: list of configuration files to load
  92. :type config_files: list of :class:`ConfigFile`
  93. """
  94. class ConfigFile(namedtuple('_ConfigFile', 'filename config')):
  95. """
  96. :param filename: filename of the config file
  97. :type filename: string
  98. :param config: contents of the config file
  99. :type config: :class:`dict`
  100. """
  101. @classmethod
  102. def from_filename(cls, filename):
  103. return cls(filename, load_yaml(filename))
  104. class ServiceConfig(namedtuple('_ServiceConfig', 'working_dir filename name config')):
  105. @classmethod
  106. def with_abs_paths(cls, working_dir, filename, name, config):
  107. if not working_dir:
  108. raise ValueError("No working_dir for ServiceConfig.")
  109. return cls(
  110. os.path.abspath(working_dir),
  111. os.path.abspath(filename) if filename else filename,
  112. name,
  113. config)
  114. def find(base_dir, filenames):
  115. if filenames == ['-']:
  116. return ConfigDetails(
  117. os.getcwd(),
  118. [ConfigFile(None, yaml.safe_load(sys.stdin))])
  119. if filenames:
  120. filenames = [os.path.join(base_dir, f) for f in filenames]
  121. else:
  122. filenames = get_default_config_files(base_dir)
  123. log.debug("Using configuration files: {}".format(",".join(filenames)))
  124. return ConfigDetails(
  125. os.path.dirname(filenames[0]),
  126. [ConfigFile.from_filename(f) for f in filenames])
  127. def get_default_config_files(base_dir):
  128. (candidates, path) = find_candidates_in_parent_dirs(SUPPORTED_FILENAMES, base_dir)
  129. if not candidates:
  130. raise ComposeFileNotFound(SUPPORTED_FILENAMES)
  131. winner = candidates[0]
  132. if len(candidates) > 1:
  133. log.warn("Found multiple config files with supported names: %s", ", ".join(candidates))
  134. log.warn("Using %s\n", winner)
  135. if winner.startswith("fig."):
  136. log.warn("%s is deprecated and will not be supported in future. "
  137. "Please rename your config file to docker-compose.yml\n" % winner)
  138. return [os.path.join(path, winner)] + get_default_override_file(path)
  139. def get_default_override_file(path):
  140. override_filename = os.path.join(path, DEFAULT_OVERRIDE_FILENAME)
  141. return [override_filename] if os.path.exists(override_filename) else []
  142. def find_candidates_in_parent_dirs(filenames, path):
  143. """
  144. Given a directory path to start, looks for filenames in the
  145. directory, and then each parent directory successively,
  146. until found.
  147. Returns tuple (candidates, path).
  148. """
  149. candidates = [filename for filename in filenames
  150. if os.path.exists(os.path.join(path, filename))]
  151. if not candidates:
  152. parent_dir = os.path.join(path, '..')
  153. if os.path.abspath(parent_dir) != os.path.abspath(path):
  154. return find_candidates_in_parent_dirs(filenames, parent_dir)
  155. return (candidates, path)
  156. def load(config_details):
  157. """Load the configuration from a working directory and a list of
  158. configuration files. Files are loaded in order, and merged on top
  159. of each other to create the final configuration.
  160. Return a fully interpolated, extended and validated configuration.
  161. """
  162. def build_service(filename, service_name, service_dict):
  163. service_config = ServiceConfig.with_abs_paths(
  164. config_details.working_dir,
  165. filename,
  166. service_name,
  167. service_dict)
  168. resolver = ServiceExtendsResolver(service_config)
  169. service_dict = process_service(resolver.run())
  170. # TODO: move to validate_service()
  171. validate_against_service_schema(service_dict, service_config.name)
  172. validate_paths(service_dict)
  173. service_dict = finalize_service(service_config._replace(config=service_dict))
  174. service_dict['name'] = service_config.name
  175. return service_dict
  176. def build_services(config_file):
  177. return sort_service_dicts([
  178. build_service(config_file.filename, name, service_dict)
  179. for name, service_dict in config_file.config.items()
  180. ])
  181. def merge_services(base, override):
  182. all_service_names = set(base) | set(override)
  183. return {
  184. name: merge_service_dicts_from_files(
  185. base.get(name, {}),
  186. override.get(name, {}))
  187. for name in all_service_names
  188. }
  189. config_file = process_config_file(config_details.config_files[0])
  190. for next_file in config_details.config_files[1:]:
  191. next_file = process_config_file(next_file)
  192. config = merge_services(config_file.config, next_file.config)
  193. config_file = config_file._replace(config=config)
  194. return build_services(config_file)
  195. def process_config_file(config_file, service_name=None):
  196. validate_top_level_object(config_file)
  197. processed_config = interpolate_environment_variables(config_file.config)
  198. validate_against_fields_schema(processed_config, config_file.filename)
  199. if service_name and service_name not in processed_config:
  200. raise ConfigurationError(
  201. "Cannot extend service '{}' in {}: Service not found".format(
  202. service_name, config_file.filename))
  203. return config_file._replace(config=processed_config)
  204. class ServiceExtendsResolver(object):
  205. def __init__(self, service_config, already_seen=None):
  206. self.service_config = service_config
  207. self.working_dir = service_config.working_dir
  208. self.already_seen = already_seen or []
  209. @property
  210. def signature(self):
  211. return self.service_config.filename, self.service_config.name
  212. def detect_cycle(self):
  213. if self.signature in self.already_seen:
  214. raise CircularReference(self.already_seen + [self.signature])
  215. def run(self):
  216. self.detect_cycle()
  217. if 'extends' in self.service_config.config:
  218. service_dict = self.resolve_extends(*self.validate_and_construct_extends())
  219. return self.service_config._replace(config=service_dict)
  220. return self.service_config
  221. def validate_and_construct_extends(self):
  222. extends = self.service_config.config['extends']
  223. if not isinstance(extends, dict):
  224. extends = {'service': extends}
  225. config_path = self.get_extended_config_path(extends)
  226. service_name = extends['service']
  227. extended_file = process_config_file(
  228. ConfigFile.from_filename(config_path),
  229. service_name=service_name)
  230. service_config = extended_file.config[service_name]
  231. return config_path, service_config, service_name
  232. def resolve_extends(self, extended_config_path, service_dict, service_name):
  233. resolver = ServiceExtendsResolver(
  234. ServiceConfig.with_abs_paths(
  235. os.path.dirname(extended_config_path),
  236. extended_config_path,
  237. service_name,
  238. service_dict),
  239. already_seen=self.already_seen + [self.signature])
  240. service_config = resolver.run()
  241. other_service_dict = process_service(service_config)
  242. validate_extended_service_dict(
  243. other_service_dict,
  244. extended_config_path,
  245. service_name,
  246. )
  247. return merge_service_dicts(other_service_dict, self.service_config.config)
  248. def get_extended_config_path(self, extends_options):
  249. """Service we are extending either has a value for 'file' set, which we
  250. need to obtain a full path too or we are extending from a service
  251. defined in our own file.
  252. """
  253. filename = self.service_config.filename
  254. validate_extends_file_path(
  255. self.service_config.name,
  256. extends_options,
  257. filename)
  258. if 'file' in extends_options:
  259. return expand_path(self.working_dir, extends_options['file'])
  260. return filename
  261. def resolve_environment(service_dict):
  262. """Unpack any environment variables from an env_file, if set.
  263. Interpolate environment values if set.
  264. """
  265. env = {}
  266. for env_file in service_dict.get('env_file', []):
  267. env.update(env_vars_from_file(env_file))
  268. env.update(parse_environment(service_dict.get('environment')))
  269. return dict(resolve_env_var(k, v) for k, v in six.iteritems(env))
  270. def validate_extended_service_dict(service_dict, filename, service):
  271. error_prefix = "Cannot extend service '%s' in %s:" % (service, filename)
  272. if 'links' in service_dict:
  273. raise ConfigurationError(
  274. "%s services with 'links' cannot be extended" % error_prefix)
  275. if 'volumes_from' in service_dict:
  276. raise ConfigurationError(
  277. "%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(
  281. "%s services with 'net: container' cannot be extended" % error_prefix)
  282. def validate_ulimits(ulimit_config):
  283. for limit_name, soft_hard_values in six.iteritems(ulimit_config):
  284. if isinstance(soft_hard_values, dict):
  285. if not soft_hard_values['soft'] <= soft_hard_values['hard']:
  286. raise ConfigurationError(
  287. "ulimit_config \"{}\" cannot contain a 'soft' value higher "
  288. "than 'hard' value".format(ulimit_config))
  289. # TODO: rename to normalize_service
  290. def process_service(service_config):
  291. working_dir = service_config.working_dir
  292. service_dict = dict(service_config.config)
  293. if 'env_file' in service_dict:
  294. service_dict['env_file'] = [
  295. expand_path(working_dir, path)
  296. for path in to_list(service_dict['env_file'])
  297. ]
  298. if 'volumes' in service_dict and service_dict.get('volume_driver') is None:
  299. service_dict['volumes'] = resolve_volume_paths(working_dir, service_dict)
  300. if 'build' in service_dict:
  301. service_dict['build'] = resolve_build_path(working_dir, service_dict['build'])
  302. if 'labels' in service_dict:
  303. service_dict['labels'] = parse_labels(service_dict['labels'])
  304. if 'extra_hosts' in service_dict:
  305. service_dict['extra_hosts'] = parse_extra_hosts(service_dict['extra_hosts'])
  306. for field in ['dns', 'dns_search']:
  307. if field in service_dict:
  308. service_dict[field] = to_list(service_dict[field])
  309. # TODO: move to a validate_service()
  310. if 'ulimits' in service_dict:
  311. validate_ulimits(service_dict['ulimits'])
  312. return service_dict
  313. def finalize_service(service_config):
  314. service_dict = dict(service_config.config)
  315. if 'environment' in service_dict or 'env_file' in service_dict:
  316. service_dict['environment'] = resolve_environment(service_dict)
  317. service_dict.pop('env_file', None)
  318. if 'volumes_from' in service_dict:
  319. service_dict['volumes_from'] = [
  320. VolumeFromSpec.parse(vf) for vf in service_dict['volumes_from']]
  321. if 'volumes' in service_dict:
  322. service_dict['volumes'] = [
  323. VolumeSpec.parse(v) for v in service_dict['volumes']]
  324. if 'restart' in service_dict:
  325. service_dict['restart'] = parse_restart_spec(service_dict['restart'])
  326. return service_dict
  327. def merge_service_dicts_from_files(base, override):
  328. """When merging services from multiple files we need to merge the `extends`
  329. field. This is not handled by `merge_service_dicts()` which is used to
  330. perform the `extends`.
  331. """
  332. new_service = merge_service_dicts(base, override)
  333. if 'extends' in override:
  334. new_service['extends'] = override['extends']
  335. return new_service
  336. def merge_service_dicts(base, override):
  337. d = {}
  338. def merge_field(field, merge_func, default=None):
  339. if field in base or field in override:
  340. d[field] = merge_func(
  341. base.get(field, default),
  342. override.get(field, default))
  343. merge_field('environment', merge_environment)
  344. merge_field('labels', merge_labels)
  345. merge_image_or_build(base, override, d)
  346. for field in ['volumes', 'devices']:
  347. merge_field(field, merge_path_mappings)
  348. for field in ['ports', 'expose', 'external_links']:
  349. merge_field(field, operator.add, default=[])
  350. for field in ['dns', 'dns_search', 'env_file']:
  351. merge_field(field, merge_list_or_string)
  352. already_merged_keys = set(d) | {'image', 'build'}
  353. for field in set(ALLOWED_KEYS) - already_merged_keys:
  354. if field in base or field in override:
  355. d[field] = override.get(field, base.get(field))
  356. return d
  357. def merge_image_or_build(base, override, output):
  358. if 'image' in override:
  359. output['image'] = override['image']
  360. elif 'build' in override:
  361. output['build'] = override['build']
  362. elif 'image' in base:
  363. output['image'] = base['image']
  364. elif 'build' in base:
  365. output['build'] = base['build']
  366. def merge_environment(base, override):
  367. env = parse_environment(base)
  368. env.update(parse_environment(override))
  369. return env
  370. def parse_environment(environment):
  371. if not environment:
  372. return {}
  373. if isinstance(environment, list):
  374. return dict(split_env(e) for e in environment)
  375. if isinstance(environment, dict):
  376. return dict(environment)
  377. raise ConfigurationError(
  378. "environment \"%s\" must be a list or mapping," %
  379. environment
  380. )
  381. def split_env(env):
  382. if isinstance(env, six.binary_type):
  383. env = env.decode('utf-8', 'replace')
  384. if '=' in env:
  385. return env.split('=', 1)
  386. else:
  387. return env, None
  388. def resolve_env_var(key, val):
  389. if val is not None:
  390. return key, val
  391. elif key in os.environ:
  392. return key, os.environ[key]
  393. else:
  394. return key, ''
  395. def env_vars_from_file(filename):
  396. """
  397. Read in a line delimited file of environment variables.
  398. """
  399. if not os.path.exists(filename):
  400. raise ConfigurationError("Couldn't find env file: %s" % filename)
  401. env = {}
  402. for line in codecs.open(filename, 'r', 'utf-8'):
  403. line = line.strip()
  404. if line and not line.startswith('#'):
  405. k, v = split_env(line)
  406. env[k] = v
  407. return env
  408. def resolve_volume_paths(working_dir, service_dict):
  409. return [
  410. resolve_volume_path(working_dir, volume)
  411. for volume in service_dict['volumes']
  412. ]
  413. def resolve_volume_path(working_dir, volume):
  414. container_path, host_path = split_path_mapping(volume)
  415. if host_path is not None:
  416. if host_path.startswith('.'):
  417. host_path = expand_path(working_dir, host_path)
  418. host_path = os.path.expanduser(host_path)
  419. return u"{}:{}".format(host_path, container_path)
  420. else:
  421. return container_path
  422. def resolve_build_path(working_dir, build_path):
  423. if is_url(build_path):
  424. return build_path
  425. return expand_path(working_dir, build_path)
  426. def is_url(build_path):
  427. return build_path.startswith(DOCKER_VALID_URL_PREFIXES)
  428. def validate_paths(service_dict):
  429. if 'build' in service_dict:
  430. build_path = service_dict['build']
  431. if (
  432. not is_url(build_path) and
  433. (not os.path.exists(build_path) or not os.access(build_path, os.R_OK))
  434. ):
  435. raise ConfigurationError(
  436. "build path %s either does not exist, is not accessible, "
  437. "or is not a valid URL." % build_path)
  438. def merge_path_mappings(base, override):
  439. d = dict_from_path_mappings(base)
  440. d.update(dict_from_path_mappings(override))
  441. return path_mappings_from_dict(d)
  442. def dict_from_path_mappings(path_mappings):
  443. if path_mappings:
  444. return dict(split_path_mapping(v) for v in path_mappings)
  445. else:
  446. return {}
  447. def path_mappings_from_dict(d):
  448. return [join_path_mapping(v) for v in d.items()]
  449. def split_path_mapping(volume_path):
  450. """
  451. Ascertain if the volume_path contains a host path as well as a container
  452. path. Using splitdrive so windows absolute paths won't cause issues with
  453. splitting on ':'.
  454. """
  455. # splitdrive has limitations when it comes to relative paths, so when it's
  456. # relative, handle special case to set the drive to ''
  457. if volume_path.startswith('.') or volume_path.startswith('~'):
  458. drive, volume_config = '', volume_path
  459. else:
  460. drive, volume_config = os.path.splitdrive(volume_path)
  461. if ':' in volume_config:
  462. (host, container) = volume_config.split(':', 1)
  463. return (container, drive + host)
  464. else:
  465. return (volume_path, None)
  466. def join_path_mapping(pair):
  467. (container, host) = pair
  468. if host is None:
  469. return container
  470. else:
  471. return ":".join((host, container))
  472. def merge_labels(base, override):
  473. labels = parse_labels(base)
  474. labels.update(parse_labels(override))
  475. return labels
  476. def parse_labels(labels):
  477. if not labels:
  478. return {}
  479. if isinstance(labels, list):
  480. return dict(split_label(e) for e in labels)
  481. if isinstance(labels, dict):
  482. return dict(labels)
  483. def split_label(label):
  484. if '=' in label:
  485. return label.split('=', 1)
  486. else:
  487. return label, ''
  488. def expand_path(working_dir, path):
  489. return os.path.abspath(os.path.join(working_dir, os.path.expanduser(path)))
  490. def merge_list_or_string(base, override):
  491. return to_list(base) + to_list(override)
  492. def to_list(value):
  493. if value is None:
  494. return []
  495. elif isinstance(value, six.string_types):
  496. return [value]
  497. else:
  498. return value
  499. def load_yaml(filename):
  500. try:
  501. with open(filename, 'r') as fh:
  502. return yaml.safe_load(fh)
  503. except (IOError, yaml.YAMLError) as e:
  504. error_name = getattr(e, '__module__', '') + '.' + e.__class__.__name__
  505. raise ConfigurationError(u"{}: {}".format(error_name, e))