config.py 18 KB

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