config.py 18 KB

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