1
0

config.py 19 KB

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