config.py 18 KB

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