config.py 18 KB

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