config.py 18 KB

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