config.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631
  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. if 'extends' in self.service_config.config:
  205. service_dict = self.resolve_extends(*self.validate_and_construct_extends())
  206. return self.service_config._replace(config=service_dict)
  207. return self.service_config
  208. def validate_and_construct_extends(self):
  209. extends = self.service_config.config['extends']
  210. if not isinstance(extends, dict):
  211. extends = {'service': extends}
  212. config_path = self.get_extended_config_path(extends)
  213. service_name = extends['service']
  214. extended_file = process_config_file(
  215. ConfigFile.from_filename(config_path),
  216. service_name=service_name)
  217. service_config = extended_file.config[service_name]
  218. return config_path, service_config, service_name
  219. def resolve_extends(self, extended_config_path, service_dict, service_name):
  220. resolver = ServiceExtendsResolver(
  221. ServiceConfig.with_abs_paths(
  222. os.path.dirname(extended_config_path),
  223. extended_config_path,
  224. service_name,
  225. service_dict),
  226. already_seen=self.already_seen + [self.signature])
  227. service_config = resolver.run()
  228. other_service_dict = process_service(service_config)
  229. validate_extended_service_dict(
  230. other_service_dict,
  231. extended_config_path,
  232. service_name,
  233. )
  234. return merge_service_dicts(other_service_dict, self.service_config.config)
  235. def get_extended_config_path(self, extends_options):
  236. """Service we are extending either has a value for 'file' set, which we
  237. need to obtain a full path too or we are extending from a service
  238. defined in our own file.
  239. """
  240. filename = self.service_config.filename
  241. validate_extends_file_path(
  242. self.service_config.name,
  243. extends_options,
  244. filename)
  245. if 'file' in extends_options:
  246. return expand_path(self.working_dir, extends_options['file'])
  247. return filename
  248. def resolve_environment(service_config):
  249. """Unpack any environment variables from an env_file, if set.
  250. Interpolate environment values if set.
  251. """
  252. service_dict = service_config.config
  253. env = {}
  254. if 'env_file' in service_dict:
  255. for env_file in get_env_files(service_config.working_dir, service_dict):
  256. env.update(env_vars_from_file(env_file))
  257. env.update(parse_environment(service_dict.get('environment')))
  258. return dict(resolve_env_var(k, v) for k, v in six.iteritems(env))
  259. def validate_extended_service_dict(service_dict, filename, service):
  260. error_prefix = "Cannot extend service '%s' in %s:" % (service, filename)
  261. if 'links' in service_dict:
  262. raise ConfigurationError(
  263. "%s services with 'links' cannot be extended" % error_prefix)
  264. if 'volumes_from' in service_dict:
  265. raise ConfigurationError(
  266. "%s services with 'volumes_from' cannot be extended" % error_prefix)
  267. if 'net' in service_dict:
  268. if get_service_name_from_net(service_dict['net']) is not None:
  269. raise ConfigurationError(
  270. "%s services with 'net: container' cannot be extended" % error_prefix)
  271. def validate_ulimits(ulimit_config):
  272. for limit_name, soft_hard_values in six.iteritems(ulimit_config):
  273. if isinstance(soft_hard_values, dict):
  274. if not soft_hard_values['soft'] <= soft_hard_values['hard']:
  275. raise ConfigurationError(
  276. "ulimit_config \"{}\" cannot contain a 'soft' value higher "
  277. "than 'hard' value".format(ulimit_config))
  278. def process_service(service_config):
  279. working_dir = service_config.working_dir
  280. service_dict = dict(service_config.config)
  281. if 'environment' in service_dict or 'env_file' in service_dict:
  282. service_dict['environment'] = resolve_environment(service_config)
  283. service_dict.pop('env_file', None)
  284. if 'volumes' in service_dict and service_dict.get('volume_driver') is None:
  285. service_dict['volumes'] = resolve_volume_paths(working_dir, service_dict)
  286. if 'build' in service_dict:
  287. service_dict['build'] = expand_path(working_dir, service_dict['build'])
  288. if 'labels' in service_dict:
  289. service_dict['labels'] = parse_labels(service_dict['labels'])
  290. if 'ulimits' in service_dict:
  291. validate_ulimits(service_dict['ulimits'])
  292. return service_dict
  293. def merge_service_dicts_from_files(base, override):
  294. """When merging services from multiple files we need to merge the `extends`
  295. field. This is not handled by `merge_service_dicts()` which is used to
  296. perform the `extends`.
  297. """
  298. new_service = merge_service_dicts(base, override)
  299. if 'extends' in override:
  300. new_service['extends'] = override['extends']
  301. return new_service
  302. def merge_service_dicts(base, override):
  303. d = base.copy()
  304. if 'environment' in base or 'environment' in override:
  305. d['environment'] = merge_environment(
  306. base.get('environment'),
  307. override.get('environment'),
  308. )
  309. path_mapping_keys = ['volumes', 'devices']
  310. for key in path_mapping_keys:
  311. if key in base or key in override:
  312. d[key] = merge_path_mappings(
  313. base.get(key),
  314. override.get(key),
  315. )
  316. if 'labels' in base or 'labels' in override:
  317. d['labels'] = merge_labels(
  318. base.get('labels'),
  319. override.get('labels'),
  320. )
  321. if 'image' in override and 'build' in d:
  322. del d['build']
  323. if 'build' in override and 'image' in d:
  324. del d['image']
  325. list_keys = ['ports', 'expose', 'external_links']
  326. for key in list_keys:
  327. if key in base or key in override:
  328. d[key] = base.get(key, []) + override.get(key, [])
  329. list_or_string_keys = ['dns', 'dns_search']
  330. for key in list_or_string_keys:
  331. if key in base or key in override:
  332. d[key] = to_list(base.get(key)) + to_list(override.get(key))
  333. already_merged_keys = ['environment', 'labels'] + path_mapping_keys + list_keys + list_or_string_keys
  334. for k in set(ALLOWED_KEYS) - set(already_merged_keys):
  335. if k in override:
  336. d[k] = override[k]
  337. return d
  338. def merge_environment(base, override):
  339. env = parse_environment(base)
  340. env.update(parse_environment(override))
  341. return env
  342. def get_env_files(working_dir, options):
  343. if 'env_file' not in options:
  344. return {}
  345. env_files = options.get('env_file', [])
  346. if not isinstance(env_files, list):
  347. env_files = [env_files]
  348. return [expand_path(working_dir, path) for path in env_files]
  349. def parse_environment(environment):
  350. if not environment:
  351. return {}
  352. if isinstance(environment, list):
  353. return dict(split_env(e) for e in environment)
  354. if isinstance(environment, dict):
  355. return dict(environment)
  356. raise ConfigurationError(
  357. "environment \"%s\" must be a list or mapping," %
  358. environment
  359. )
  360. def split_env(env):
  361. if isinstance(env, six.binary_type):
  362. env = env.decode('utf-8', 'replace')
  363. if '=' in env:
  364. return env.split('=', 1)
  365. else:
  366. return env, None
  367. def resolve_env_var(key, val):
  368. if val is not None:
  369. return key, val
  370. elif key in os.environ:
  371. return key, os.environ[key]
  372. else:
  373. return key, ''
  374. def env_vars_from_file(filename):
  375. """
  376. Read in a line delimited file of environment variables.
  377. """
  378. if not os.path.exists(filename):
  379. raise ConfigurationError("Couldn't find env file: %s" % filename)
  380. env = {}
  381. for line in codecs.open(filename, 'r', 'utf-8'):
  382. line = line.strip()
  383. if line and not line.startswith('#'):
  384. k, v = split_env(line)
  385. env[k] = v
  386. return env
  387. def resolve_volume_paths(working_dir, service_dict):
  388. return [
  389. resolve_volume_path(working_dir, volume)
  390. for volume in service_dict['volumes']
  391. ]
  392. def resolve_volume_path(working_dir, volume):
  393. container_path, host_path = split_path_mapping(volume)
  394. if host_path is not None:
  395. if host_path.startswith('.'):
  396. host_path = expand_path(working_dir, host_path)
  397. host_path = os.path.expanduser(host_path)
  398. return u"{}:{}".format(host_path, container_path)
  399. else:
  400. return container_path
  401. def validate_paths(service_dict):
  402. if 'build' in service_dict:
  403. build_path = service_dict['build']
  404. if not os.path.exists(build_path) or not os.access(build_path, os.R_OK):
  405. raise ConfigurationError("build path %s either does not exist or is not accessible." % build_path)
  406. def merge_path_mappings(base, override):
  407. d = dict_from_path_mappings(base)
  408. d.update(dict_from_path_mappings(override))
  409. return path_mappings_from_dict(d)
  410. def dict_from_path_mappings(path_mappings):
  411. if path_mappings:
  412. return dict(split_path_mapping(v) for v in path_mappings)
  413. else:
  414. return {}
  415. def path_mappings_from_dict(d):
  416. return [join_path_mapping(v) for v in d.items()]
  417. def split_path_mapping(volume_path):
  418. """
  419. Ascertain if the volume_path contains a host path as well as a container
  420. path. Using splitdrive so windows absolute paths won't cause issues with
  421. splitting on ':'.
  422. """
  423. # splitdrive has limitations when it comes to relative paths, so when it's
  424. # relative, handle special case to set the drive to ''
  425. if volume_path.startswith('.') or volume_path.startswith('~'):
  426. drive, volume_config = '', volume_path
  427. else:
  428. drive, volume_config = os.path.splitdrive(volume_path)
  429. if ':' in volume_config:
  430. (host, container) = volume_config.split(':', 1)
  431. return (container, drive + host)
  432. else:
  433. return (volume_path, None)
  434. def join_path_mapping(pair):
  435. (container, host) = pair
  436. if host is None:
  437. return container
  438. else:
  439. return ":".join((host, container))
  440. def merge_labels(base, override):
  441. labels = parse_labels(base)
  442. labels.update(parse_labels(override))
  443. return labels
  444. def parse_labels(labels):
  445. if not labels:
  446. return {}
  447. if isinstance(labels, list):
  448. return dict(split_label(e) for e in labels)
  449. if isinstance(labels, dict):
  450. return dict(labels)
  451. def split_label(label):
  452. if '=' in label:
  453. return label.split('=', 1)
  454. else:
  455. return label, ''
  456. def expand_path(working_dir, path):
  457. return os.path.abspath(os.path.join(working_dir, os.path.expanduser(path)))
  458. def to_list(value):
  459. if value is None:
  460. return []
  461. elif isinstance(value, six.string_types):
  462. return [value]
  463. else:
  464. return value
  465. def get_service_name_from_net(net_config):
  466. if not net_config:
  467. return
  468. if not net_config.startswith('container:'):
  469. return
  470. _, net_name = net_config.split(':', 1)
  471. return net_name
  472. def load_yaml(filename):
  473. try:
  474. with open(filename, 'r') as fh:
  475. return yaml.safe_load(fh)
  476. except (IOError, yaml.YAMLError) as e:
  477. error_name = getattr(e, '__module__', '') + '.' + e.__class__.__name__
  478. raise ConfigurationError(u"{}: {}".format(error_name, e))