config.py 19 KB

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