config.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609
  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_service_names
  16. from .validation import validate_top_level_object
  17. DOCKER_CONFIG_KEYS = [
  18. 'cap_add',
  19. 'cap_drop',
  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. @validate_top_level_object
  134. @validate_service_names
  135. def pre_process_config(config):
  136. """
  137. Pre validation checks and processing of the config file to interpolate env
  138. vars returning a config dict ready to be tested against the schema.
  139. """
  140. return interpolate_environment_variables(config)
  141. def load(config_details):
  142. """Load the configuration from a working directory and a list of
  143. configuration files. Files are loaded in order, and merged on top
  144. of each other to create the final configuration.
  145. Return a fully interpolated, extended and validated configuration.
  146. """
  147. def build_service(filename, service_name, service_dict):
  148. loader = ServiceLoader(
  149. config_details.working_dir,
  150. filename,
  151. service_name,
  152. service_dict)
  153. service_dict = loader.make_service_dict()
  154. validate_paths(service_dict)
  155. return service_dict
  156. def load_file(filename, config):
  157. processed_config = pre_process_config(config)
  158. validate_against_fields_schema(processed_config)
  159. return [
  160. build_service(filename, name, service_config)
  161. for name, service_config in processed_config.items()
  162. ]
  163. def merge_services(base, override):
  164. all_service_names = set(base) | set(override)
  165. return {
  166. name: merge_service_dicts(base.get(name, {}), override.get(name, {}))
  167. for name in all_service_names
  168. }
  169. config_file = config_details.config_files[0]
  170. for next_file in config_details.config_files[1:]:
  171. config_file = ConfigFile(
  172. config_file.filename,
  173. merge_services(config_file.config, next_file.config))
  174. return load_file(config_file.filename, config_file.config)
  175. class ServiceLoader(object):
  176. def __init__(self, working_dir, filename, service_name, service_dict, already_seen=None):
  177. if working_dir is None:
  178. raise Exception("No working_dir passed to ServiceLoader()")
  179. self.working_dir = os.path.abspath(working_dir)
  180. if filename:
  181. self.filename = os.path.abspath(filename)
  182. else:
  183. self.filename = filename
  184. self.already_seen = already_seen or []
  185. self.service_dict = service_dict.copy()
  186. self.service_name = service_name
  187. self.service_dict['name'] = service_name
  188. def detect_cycle(self, name):
  189. if self.signature(name) in self.already_seen:
  190. raise CircularReference(self.already_seen + [self.signature(name)])
  191. def make_service_dict(self):
  192. self.resolve_environment()
  193. if 'extends' in self.service_dict:
  194. self.validate_and_construct_extends()
  195. self.service_dict = self.resolve_extends()
  196. if not self.already_seen:
  197. validate_against_service_schema(self.service_dict, self.service_name)
  198. return process_container_options(self.service_dict, working_dir=self.working_dir)
  199. def resolve_environment(self):
  200. """
  201. Unpack any environment variables from an env_file, if set.
  202. Interpolate environment values if set.
  203. """
  204. if 'environment' not in self.service_dict and 'env_file' not in self.service_dict:
  205. return
  206. env = {}
  207. if 'env_file' in self.service_dict:
  208. for f in get_env_files(self.service_dict, working_dir=self.working_dir):
  209. env.update(env_vars_from_file(f))
  210. del self.service_dict['env_file']
  211. env.update(parse_environment(self.service_dict.get('environment')))
  212. env = dict(resolve_env_var(k, v) for k, v in six.iteritems(env))
  213. self.service_dict['environment'] = env
  214. def validate_and_construct_extends(self):
  215. validate_extends_file_path(
  216. self.service_name,
  217. self.service_dict['extends'],
  218. self.filename
  219. )
  220. self.extended_config_path = self.get_extended_config_path(
  221. self.service_dict['extends']
  222. )
  223. self.extended_service_name = self.service_dict['extends']['service']
  224. full_extended_config = pre_process_config(
  225. load_yaml(self.extended_config_path)
  226. )
  227. validate_extended_service_exists(
  228. self.extended_service_name,
  229. full_extended_config,
  230. self.extended_config_path
  231. )
  232. validate_against_fields_schema(full_extended_config)
  233. self.extended_config = full_extended_config[self.extended_service_name]
  234. def resolve_extends(self):
  235. other_working_dir = os.path.dirname(self.extended_config_path)
  236. other_already_seen = self.already_seen + [self.signature(self.service_name)]
  237. other_loader = ServiceLoader(
  238. working_dir=other_working_dir,
  239. filename=self.extended_config_path,
  240. service_name=self.service_name,
  241. service_dict=self.extended_config,
  242. already_seen=other_already_seen,
  243. )
  244. other_loader.detect_cycle(self.extended_service_name)
  245. other_service_dict = other_loader.make_service_dict()
  246. validate_extended_service_dict(
  247. other_service_dict,
  248. filename=self.extended_config_path,
  249. service=self.extended_service_name,
  250. )
  251. return merge_service_dicts(other_service_dict, self.service_dict)
  252. def get_extended_config_path(self, extends_options):
  253. """
  254. Service we are extending either has a value for 'file' set, which we
  255. need to obtain a full path too or we are extending from a service
  256. defined in our own file.
  257. """
  258. if 'file' in extends_options:
  259. extends_from_filename = extends_options['file']
  260. return expand_path(self.working_dir, extends_from_filename)
  261. return self.filename
  262. def signature(self, name):
  263. return (self.filename, name)
  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("%s services with 'links' cannot be extended" % error_prefix)
  268. if 'volumes_from' in service_dict:
  269. raise ConfigurationError("%s services with 'volumes_from' cannot be extended" % error_prefix)
  270. if 'net' in service_dict:
  271. if get_service_name_from_net(service_dict['net']) is not None:
  272. raise ConfigurationError("%s services with 'net: container' cannot be extended" % error_prefix)
  273. def process_container_options(service_dict, working_dir=None):
  274. service_dict = service_dict.copy()
  275. if 'volumes' in service_dict and service_dict.get('volume_driver') is None:
  276. service_dict['volumes'] = resolve_volume_paths(service_dict, working_dir=working_dir)
  277. if 'build' in service_dict:
  278. service_dict['build'] = resolve_build_path(service_dict['build'], working_dir=working_dir)
  279. if 'labels' in service_dict:
  280. service_dict['labels'] = parse_labels(service_dict['labels'])
  281. return service_dict
  282. def merge_service_dicts(base, override):
  283. d = base.copy()
  284. if 'environment' in base or 'environment' in override:
  285. d['environment'] = merge_environment(
  286. base.get('environment'),
  287. override.get('environment'),
  288. )
  289. path_mapping_keys = ['volumes', 'devices']
  290. for key in path_mapping_keys:
  291. if key in base or key in override:
  292. d[key] = merge_path_mappings(
  293. base.get(key),
  294. override.get(key),
  295. )
  296. if 'labels' in base or 'labels' in override:
  297. d['labels'] = merge_labels(
  298. base.get('labels'),
  299. override.get('labels'),
  300. )
  301. if 'image' in override and 'build' in d:
  302. del d['build']
  303. if 'build' in override and 'image' in d:
  304. del d['image']
  305. list_keys = ['ports', 'expose', 'external_links']
  306. for key in list_keys:
  307. if key in base or key in override:
  308. d[key] = base.get(key, []) + override.get(key, [])
  309. list_or_string_keys = ['dns', 'dns_search']
  310. for key in list_or_string_keys:
  311. if key in base or key in override:
  312. d[key] = to_list(base.get(key)) + to_list(override.get(key))
  313. already_merged_keys = ['environment', 'labels'] + path_mapping_keys + list_keys + list_or_string_keys
  314. for k in set(ALLOWED_KEYS) - set(already_merged_keys):
  315. if k in override:
  316. d[k] = override[k]
  317. return d
  318. def merge_environment(base, override):
  319. env = parse_environment(base)
  320. env.update(parse_environment(override))
  321. return env
  322. def get_env_files(options, working_dir=None):
  323. if 'env_file' not in options:
  324. return {}
  325. env_files = options.get('env_file', [])
  326. if not isinstance(env_files, list):
  327. env_files = [env_files]
  328. return [expand_path(working_dir, path) for path in env_files]
  329. def parse_environment(environment):
  330. if not environment:
  331. return {}
  332. if isinstance(environment, list):
  333. return dict(split_env(e) for e in environment)
  334. if isinstance(environment, dict):
  335. return dict(environment)
  336. raise ConfigurationError(
  337. "environment \"%s\" must be a list or mapping," %
  338. environment
  339. )
  340. def split_env(env):
  341. if '=' in env:
  342. return env.split('=', 1)
  343. else:
  344. return env, None
  345. def resolve_env_var(key, val):
  346. if val is not None:
  347. return key, val
  348. elif key in os.environ:
  349. return key, os.environ[key]
  350. else:
  351. return key, ''
  352. def env_vars_from_file(filename):
  353. """
  354. Read in a line delimited file of environment variables.
  355. """
  356. if not os.path.exists(filename):
  357. raise ConfigurationError("Couldn't find env file: %s" % filename)
  358. env = {}
  359. for line in open(filename, 'r'):
  360. line = line.strip()
  361. if line and not line.startswith('#'):
  362. k, v = split_env(line)
  363. env[k] = v
  364. return env
  365. def resolve_volume_paths(service_dict, working_dir=None):
  366. if working_dir is None:
  367. raise Exception("No working_dir passed to resolve_volume_paths()")
  368. return [
  369. resolve_volume_path(v, working_dir, service_dict['name'])
  370. for v in service_dict['volumes']
  371. ]
  372. def resolve_volume_path(volume, working_dir, service_name):
  373. container_path, host_path = split_path_mapping(volume)
  374. if host_path is not None:
  375. if host_path.startswith('.'):
  376. host_path = expand_path(working_dir, host_path)
  377. host_path = os.path.expanduser(host_path)
  378. return "{}:{}".format(host_path, container_path)
  379. else:
  380. return container_path
  381. def resolve_build_path(build_path, working_dir=None):
  382. if working_dir is None:
  383. raise Exception("No working_dir passed to resolve_build_path")
  384. return expand_path(working_dir, build_path)
  385. def validate_paths(service_dict):
  386. if 'build' in service_dict:
  387. build_path = service_dict['build']
  388. if not os.path.exists(build_path) or not os.access(build_path, os.R_OK):
  389. raise ConfigurationError("build path %s either does not exist or is not accessible." % build_path)
  390. def merge_path_mappings(base, override):
  391. d = dict_from_path_mappings(base)
  392. d.update(dict_from_path_mappings(override))
  393. return path_mappings_from_dict(d)
  394. def dict_from_path_mappings(path_mappings):
  395. if path_mappings:
  396. return dict(split_path_mapping(v) for v in path_mappings)
  397. else:
  398. return {}
  399. def path_mappings_from_dict(d):
  400. return [join_path_mapping(v) for v in d.items()]
  401. def split_path_mapping(volume_path):
  402. """
  403. Ascertain if the volume_path contains a host path as well as a container
  404. path. Using splitdrive so windows absolute paths won't cause issues with
  405. splitting on ':'.
  406. """
  407. # splitdrive has limitations when it comes to relative paths, so when it's
  408. # relative, handle special case to set the drive to ''
  409. if volume_path.startswith('.') or volume_path.startswith('~'):
  410. drive, volume_config = '', volume_path
  411. else:
  412. drive, volume_config = os.path.splitdrive(volume_path)
  413. if ':' in volume_config:
  414. (host, container) = volume_config.split(':', 1)
  415. return (container, drive + host)
  416. else:
  417. return (volume_path, None)
  418. def join_path_mapping(pair):
  419. (container, host) = pair
  420. if host is None:
  421. return container
  422. else:
  423. return ":".join((host, container))
  424. def merge_labels(base, override):
  425. labels = parse_labels(base)
  426. labels.update(parse_labels(override))
  427. return labels
  428. def parse_labels(labels):
  429. if not labels:
  430. return {}
  431. if isinstance(labels, list):
  432. return dict(split_label(e) for e in labels)
  433. if isinstance(labels, dict):
  434. return labels
  435. def split_label(label):
  436. if '=' in label:
  437. return label.split('=', 1)
  438. else:
  439. return label, ''
  440. def expand_path(working_dir, path):
  441. return os.path.abspath(os.path.join(working_dir, os.path.expanduser(path)))
  442. def to_list(value):
  443. if value is None:
  444. return []
  445. elif isinstance(value, six.string_types):
  446. return [value]
  447. else:
  448. return value
  449. def get_service_name_from_net(net_config):
  450. if not net_config:
  451. return
  452. if not net_config.startswith('container:'):
  453. return
  454. _, net_name = net_config.split(':', 1)
  455. return net_name
  456. def load_yaml(filename):
  457. try:
  458. with open(filename, 'r') as fh:
  459. return yaml.safe_load(fh)
  460. except IOError as e:
  461. raise ConfigurationError(six.text_type(e))