config.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566
  1. import logging
  2. import os
  3. import sys
  4. import yaml
  5. from collections import namedtuple
  6. import six
  7. from compose.cli.utils import find_candidates_in_parent_dirs
  8. from .interpolation import interpolate_environment_variables
  9. from .errors import (
  10. ConfigurationError,
  11. CircularReference,
  12. ComposeFileNotFound,
  13. )
  14. DOCKER_CONFIG_KEYS = [
  15. 'cap_add',
  16. 'cap_drop',
  17. 'cpu_shares',
  18. 'cpuset',
  19. 'command',
  20. 'detach',
  21. 'devices',
  22. 'dns',
  23. 'dns_search',
  24. 'domainname',
  25. 'entrypoint',
  26. 'env_file',
  27. 'environment',
  28. 'extra_hosts',
  29. 'hostname',
  30. 'image',
  31. 'labels',
  32. 'links',
  33. 'mac_address',
  34. 'mem_limit',
  35. 'memswap_limit',
  36. 'net',
  37. 'log_driver',
  38. 'log_opt',
  39. 'pid',
  40. 'ports',
  41. 'privileged',
  42. 'read_only',
  43. 'restart',
  44. 'security_opt',
  45. 'stdin_open',
  46. 'tty',
  47. 'user',
  48. 'volume_driver',
  49. 'volumes',
  50. 'volumes_from',
  51. 'working_dir',
  52. ]
  53. ALLOWED_KEYS = DOCKER_CONFIG_KEYS + [
  54. 'build',
  55. 'container_name',
  56. 'dockerfile',
  57. 'expose',
  58. 'external_links',
  59. 'name',
  60. ]
  61. DOCKER_CONFIG_HINTS = {
  62. 'cpu_share': 'cpu_shares',
  63. 'add_host': 'extra_hosts',
  64. 'hosts': 'extra_hosts',
  65. 'extra_host': 'extra_hosts',
  66. 'device': 'devices',
  67. 'link': 'links',
  68. 'memory_swap': 'memswap_limit',
  69. 'port': 'ports',
  70. 'privilege': 'privileged',
  71. 'priviliged': 'privileged',
  72. 'privilige': 'privileged',
  73. 'volume': 'volumes',
  74. 'workdir': 'working_dir',
  75. }
  76. SUPPORTED_FILENAMES = [
  77. 'docker-compose.yml',
  78. 'docker-compose.yaml',
  79. 'fig.yml',
  80. 'fig.yaml',
  81. ]
  82. PATH_START_CHARS = [
  83. '/',
  84. '.',
  85. '~',
  86. ]
  87. log = logging.getLogger(__name__)
  88. ConfigDetails = namedtuple('ConfigDetails', 'config working_dir filename')
  89. def find(base_dir, filename):
  90. if filename == '-':
  91. return ConfigDetails(yaml.safe_load(sys.stdin), os.getcwd(), None)
  92. if filename:
  93. filename = os.path.join(base_dir, filename)
  94. else:
  95. filename = get_config_path(base_dir)
  96. return ConfigDetails(load_yaml(filename), os.path.dirname(filename), filename)
  97. def get_config_path(base_dir):
  98. (candidates, path) = find_candidates_in_parent_dirs(SUPPORTED_FILENAMES, base_dir)
  99. if len(candidates) == 0:
  100. raise ComposeFileNotFound(SUPPORTED_FILENAMES)
  101. winner = candidates[0]
  102. if len(candidates) > 1:
  103. log.warn("Found multiple config files with supported names: %s", ", ".join(candidates))
  104. log.warn("Using %s\n", winner)
  105. if winner == 'docker-compose.yaml':
  106. log.warn("Please be aware that .yml is the expected extension "
  107. "in most cases, and using .yaml can cause compatibility "
  108. "issues in future.\n")
  109. if winner.startswith("fig."):
  110. log.warn("%s is deprecated and will not be supported in future. "
  111. "Please rename your config file to docker-compose.yml\n" % winner)
  112. return os.path.join(path, winner)
  113. def load(config_details):
  114. dictionary, working_dir, filename = config_details
  115. dictionary = interpolate_environment_variables(dictionary)
  116. service_dicts = []
  117. for service_name, service_dict in list(dictionary.items()):
  118. loader = ServiceLoader(working_dir=working_dir, filename=filename)
  119. service_dict = loader.make_service_dict(service_name, service_dict)
  120. validate_paths(service_dict)
  121. service_dicts.append(service_dict)
  122. return service_dicts
  123. class ServiceLoader(object):
  124. def __init__(self, working_dir, filename=None, already_seen=None):
  125. self.working_dir = os.path.abspath(working_dir)
  126. if filename:
  127. self.filename = os.path.abspath(filename)
  128. else:
  129. self.filename = filename
  130. self.already_seen = already_seen or []
  131. def detect_cycle(self, name):
  132. if self.signature(name) in self.already_seen:
  133. raise CircularReference(self.already_seen + [self.signature(name)])
  134. def make_service_dict(self, name, service_dict):
  135. service_dict = service_dict.copy()
  136. service_dict['name'] = name
  137. service_dict = resolve_environment(service_dict, working_dir=self.working_dir)
  138. service_dict = self.resolve_extends(service_dict)
  139. return process_container_options(service_dict, working_dir=self.working_dir)
  140. def resolve_extends(self, service_dict):
  141. if 'extends' not in service_dict:
  142. return service_dict
  143. extends_options = self.validate_extends_options(service_dict['name'], service_dict['extends'])
  144. if self.working_dir is None:
  145. raise Exception("No working_dir passed to ServiceLoader()")
  146. if 'file' in extends_options:
  147. extends_from_filename = extends_options['file']
  148. other_config_path = expand_path(self.working_dir, extends_from_filename)
  149. else:
  150. other_config_path = self.filename
  151. other_working_dir = os.path.dirname(other_config_path)
  152. other_already_seen = self.already_seen + [self.signature(service_dict['name'])]
  153. other_loader = ServiceLoader(
  154. working_dir=other_working_dir,
  155. filename=other_config_path,
  156. already_seen=other_already_seen,
  157. )
  158. other_config = load_yaml(other_config_path)
  159. other_service_dict = other_config[extends_options['service']]
  160. other_loader.detect_cycle(extends_options['service'])
  161. other_service_dict = other_loader.make_service_dict(
  162. service_dict['name'],
  163. other_service_dict,
  164. )
  165. validate_extended_service_dict(
  166. other_service_dict,
  167. filename=other_config_path,
  168. service=extends_options['service'],
  169. )
  170. return merge_service_dicts(other_service_dict, service_dict)
  171. def signature(self, name):
  172. return (self.filename, name)
  173. def validate_extends_options(self, service_name, extends_options):
  174. error_prefix = "Invalid 'extends' configuration for %s:" % service_name
  175. if not isinstance(extends_options, dict):
  176. raise ConfigurationError("%s must be a dictionary" % error_prefix)
  177. if 'service' not in extends_options:
  178. raise ConfigurationError(
  179. "%s you need to specify a service, e.g. 'service: web'" % error_prefix
  180. )
  181. if 'file' not in extends_options and self.filename is None:
  182. raise ConfigurationError(
  183. "%s you need to specify a 'file', e.g. 'file: something.yml'" % error_prefix
  184. )
  185. for k, _ in extends_options.items():
  186. if k not in ['file', 'service']:
  187. raise ConfigurationError(
  188. "%s unsupported configuration option '%s'" % (error_prefix, k)
  189. )
  190. return extends_options
  191. def validate_extended_service_dict(service_dict, filename, service):
  192. error_prefix = "Cannot extend service '%s' in %s:" % (service, filename)
  193. if 'links' in service_dict:
  194. raise ConfigurationError("%s services with 'links' cannot be extended" % error_prefix)
  195. if 'volumes_from' in service_dict:
  196. raise ConfigurationError("%s services with 'volumes_from' cannot be extended" % error_prefix)
  197. if 'net' in service_dict:
  198. if get_service_name_from_net(service_dict['net']) is not None:
  199. raise ConfigurationError("%s services with 'net: container' cannot be extended" % error_prefix)
  200. def process_container_options(service_dict, working_dir=None):
  201. for k in service_dict:
  202. if k not in ALLOWED_KEYS:
  203. msg = "Unsupported config option for %s service: '%s'" % (service_dict['name'], k)
  204. if k in DOCKER_CONFIG_HINTS:
  205. msg += " (did you mean '%s'?)" % DOCKER_CONFIG_HINTS[k]
  206. raise ConfigurationError(msg)
  207. service_dict = service_dict.copy()
  208. if 'memswap_limit' in service_dict and 'mem_limit' not in service_dict:
  209. raise ConfigurationError("Invalid 'memswap_limit' configuration for %s service: when defining 'memswap_limit' you must set 'mem_limit' as well" % service_dict['name'])
  210. if 'volumes' in service_dict and service_dict.get('volume_driver') is None:
  211. service_dict['volumes'] = resolve_volume_paths(service_dict, working_dir=working_dir)
  212. if 'build' in service_dict:
  213. service_dict['build'] = resolve_build_path(service_dict['build'], working_dir=working_dir)
  214. if 'labels' in service_dict:
  215. service_dict['labels'] = parse_labels(service_dict['labels'])
  216. return service_dict
  217. def merge_service_dicts(base, override):
  218. d = base.copy()
  219. if 'environment' in base or 'environment' in override:
  220. d['environment'] = merge_environment(
  221. base.get('environment'),
  222. override.get('environment'),
  223. )
  224. path_mapping_keys = ['volumes', 'devices']
  225. for key in path_mapping_keys:
  226. if key in base or key in override:
  227. d[key] = merge_path_mappings(
  228. base.get(key),
  229. override.get(key),
  230. )
  231. if 'labels' in base or 'labels' in override:
  232. d['labels'] = merge_labels(
  233. base.get('labels'),
  234. override.get('labels'),
  235. )
  236. if 'image' in override and 'build' in d:
  237. del d['build']
  238. if 'build' in override and 'image' in d:
  239. del d['image']
  240. list_keys = ['ports', 'expose', 'external_links']
  241. for key in list_keys:
  242. if key in base or key in override:
  243. d[key] = base.get(key, []) + override.get(key, [])
  244. list_or_string_keys = ['dns', 'dns_search']
  245. for key in list_or_string_keys:
  246. if key in base or key in override:
  247. d[key] = to_list(base.get(key)) + to_list(override.get(key))
  248. already_merged_keys = ['environment', 'labels'] + path_mapping_keys + list_keys + list_or_string_keys
  249. for k in set(ALLOWED_KEYS) - set(already_merged_keys):
  250. if k in override:
  251. d[k] = override[k]
  252. return d
  253. def merge_environment(base, override):
  254. env = parse_environment(base)
  255. env.update(parse_environment(override))
  256. return env
  257. def parse_links(links):
  258. return dict(parse_link(l) for l in links)
  259. def parse_link(link):
  260. if ':' in link:
  261. source, alias = link.split(':', 1)
  262. return (alias, source)
  263. else:
  264. return (link, link)
  265. def get_env_files(options, working_dir=None):
  266. if 'env_file' not in options:
  267. return {}
  268. if working_dir is None:
  269. raise Exception("No working_dir passed to get_env_files()")
  270. env_files = options.get('env_file', [])
  271. if not isinstance(env_files, list):
  272. env_files = [env_files]
  273. return [expand_path(working_dir, path) for path in env_files]
  274. def resolve_environment(service_dict, working_dir=None):
  275. service_dict = service_dict.copy()
  276. if 'environment' not in service_dict and 'env_file' not in service_dict:
  277. return service_dict
  278. env = {}
  279. if 'env_file' in service_dict:
  280. for f in get_env_files(service_dict, working_dir=working_dir):
  281. env.update(env_vars_from_file(f))
  282. del service_dict['env_file']
  283. env.update(parse_environment(service_dict.get('environment')))
  284. env = dict(resolve_env_var(k, v) for k, v in six.iteritems(env))
  285. service_dict['environment'] = env
  286. return service_dict
  287. def parse_environment(environment):
  288. if not environment:
  289. return {}
  290. if isinstance(environment, list):
  291. return dict(split_env(e) for e in environment)
  292. if isinstance(environment, dict):
  293. return environment
  294. raise ConfigurationError(
  295. "environment \"%s\" must be a list or mapping," %
  296. environment
  297. )
  298. def split_env(env):
  299. if '=' in env:
  300. return env.split('=', 1)
  301. else:
  302. return env, None
  303. def resolve_env_var(key, val):
  304. if val is not None:
  305. return key, val
  306. elif key in os.environ:
  307. return key, os.environ[key]
  308. else:
  309. return key, ''
  310. def env_vars_from_file(filename):
  311. """
  312. Read in a line delimited file of environment variables.
  313. """
  314. if not os.path.exists(filename):
  315. raise ConfigurationError("Couldn't find env file: %s" % filename)
  316. env = {}
  317. for line in open(filename, 'r'):
  318. line = line.strip()
  319. if line and not line.startswith('#'):
  320. k, v = split_env(line)
  321. env[k] = v
  322. return env
  323. def resolve_volume_paths(service_dict, working_dir=None):
  324. if working_dir is None:
  325. raise Exception("No working_dir passed to resolve_volume_paths()")
  326. return [
  327. resolve_volume_path(v, working_dir, service_dict['name'])
  328. for v in service_dict['volumes']
  329. ]
  330. def resolve_volume_path(volume, working_dir, service_name):
  331. container_path, host_path = split_path_mapping(volume)
  332. container_path = os.path.expanduser(container_path)
  333. if host_path is not None:
  334. if not any(host_path.startswith(c) for c in PATH_START_CHARS):
  335. log.warn(
  336. 'Warning: the mapping "{0}" in the volumes config for '
  337. 'service "{1}" is ambiguous. In a future version of Docker, '
  338. 'it will designate a "named" volume '
  339. '(see https://github.com/docker/docker/pull/14242). '
  340. 'To prevent unexpected behaviour, change it to "./{0}"'
  341. .format(volume, service_name)
  342. )
  343. host_path = os.path.expanduser(host_path)
  344. return "%s:%s" % (expand_path(working_dir, host_path), container_path)
  345. else:
  346. return container_path
  347. def resolve_build_path(build_path, working_dir=None):
  348. if working_dir is None:
  349. raise Exception("No working_dir passed to resolve_build_path")
  350. return expand_path(working_dir, build_path)
  351. def validate_paths(service_dict):
  352. if 'build' in service_dict:
  353. build_path = service_dict['build']
  354. if not os.path.exists(build_path) or not os.access(build_path, os.R_OK):
  355. raise ConfigurationError("build path %s either does not exist or is not accessible." % build_path)
  356. def merge_path_mappings(base, override):
  357. d = dict_from_path_mappings(base)
  358. d.update(dict_from_path_mappings(override))
  359. return path_mappings_from_dict(d)
  360. def dict_from_path_mappings(path_mappings):
  361. if path_mappings:
  362. return dict(split_path_mapping(v) for v in path_mappings)
  363. else:
  364. return {}
  365. def path_mappings_from_dict(d):
  366. return [join_path_mapping(v) for v in d.items()]
  367. def split_path_mapping(string):
  368. if ':' in string:
  369. (host, container) = string.split(':', 1)
  370. return (container, host)
  371. else:
  372. return (string, None)
  373. def join_path_mapping(pair):
  374. (container, host) = pair
  375. if host is None:
  376. return container
  377. else:
  378. return ":".join((host, container))
  379. def merge_labels(base, override):
  380. labels = parse_labels(base)
  381. labels.update(parse_labels(override))
  382. return labels
  383. def parse_labels(labels):
  384. if not labels:
  385. return {}
  386. if isinstance(labels, list):
  387. return dict(split_label(e) for e in labels)
  388. if isinstance(labels, dict):
  389. return labels
  390. raise ConfigurationError(
  391. "labels \"%s\" must be a list or mapping" %
  392. labels
  393. )
  394. def split_label(label):
  395. if '=' in label:
  396. return label.split('=', 1)
  397. else:
  398. return label, ''
  399. def expand_path(working_dir, path):
  400. return os.path.abspath(os.path.join(working_dir, path))
  401. def to_list(value):
  402. if value is None:
  403. return []
  404. elif isinstance(value, six.string_types):
  405. return [value]
  406. else:
  407. return value
  408. def get_service_name_from_net(net_config):
  409. if not net_config:
  410. return
  411. if not net_config.startswith('container:'):
  412. return
  413. _, net_name = net_config.split(':', 1)
  414. return net_name
  415. def load_yaml(filename):
  416. try:
  417. with open(filename, 'r') as fh:
  418. return yaml.safe_load(fh)
  419. except IOError as e:
  420. raise ConfigurationError(six.text_type(e))