config.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545
  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. log = logging.getLogger(__name__)
  83. ConfigDetails = namedtuple('ConfigDetails', 'config working_dir filename')
  84. def find(base_dir, filename):
  85. if filename == '-':
  86. return ConfigDetails(yaml.safe_load(sys.stdin), os.getcwd(), None)
  87. if filename:
  88. filename = os.path.join(base_dir, filename)
  89. else:
  90. filename = get_config_path(base_dir)
  91. return ConfigDetails(load_yaml(filename), os.path.dirname(filename), filename)
  92. def get_config_path(base_dir):
  93. (candidates, path) = find_candidates_in_parent_dirs(SUPPORTED_FILENAMES, base_dir)
  94. if len(candidates) == 0:
  95. raise ComposeFileNotFound(SUPPORTED_FILENAMES)
  96. winner = candidates[0]
  97. if len(candidates) > 1:
  98. log.warn("Found multiple config files with supported names: %s", ", ".join(candidates))
  99. log.warn("Using %s\n", winner)
  100. if winner == 'docker-compose.yaml':
  101. log.warn("Please be aware that .yml is the expected extension "
  102. "in most cases, and using .yaml can cause compatibility "
  103. "issues in future.\n")
  104. if winner.startswith("fig."):
  105. log.warn("%s is deprecated and will not be supported in future. "
  106. "Please rename your config file to docker-compose.yml\n" % winner)
  107. return os.path.join(path, winner)
  108. def load(config_details):
  109. dictionary, working_dir, filename = config_details
  110. dictionary = interpolate_environment_variables(dictionary)
  111. service_dicts = []
  112. for service_name, service_dict in list(dictionary.items()):
  113. loader = ServiceLoader(working_dir=working_dir, filename=filename)
  114. service_dict = loader.make_service_dict(service_name, service_dict)
  115. validate_paths(service_dict)
  116. service_dicts.append(service_dict)
  117. return service_dicts
  118. class ServiceLoader(object):
  119. def __init__(self, working_dir, filename=None, already_seen=None):
  120. self.working_dir = os.path.abspath(working_dir)
  121. if filename:
  122. self.filename = os.path.abspath(filename)
  123. else:
  124. self.filename = filename
  125. self.already_seen = already_seen or []
  126. def detect_cycle(self, name):
  127. if self.signature(name) in self.already_seen:
  128. raise CircularReference(self.already_seen + [self.signature(name)])
  129. def make_service_dict(self, name, service_dict):
  130. service_dict = service_dict.copy()
  131. service_dict['name'] = name
  132. service_dict = resolve_environment(service_dict, working_dir=self.working_dir)
  133. service_dict = self.resolve_extends(service_dict)
  134. return process_container_options(service_dict, working_dir=self.working_dir)
  135. def resolve_extends(self, service_dict):
  136. if 'extends' not in service_dict:
  137. return service_dict
  138. extends_options = self.validate_extends_options(service_dict['name'], service_dict['extends'])
  139. if self.working_dir is None:
  140. raise Exception("No working_dir passed to ServiceLoader()")
  141. if 'file' in extends_options:
  142. extends_from_filename = extends_options['file']
  143. other_config_path = expand_path(self.working_dir, extends_from_filename)
  144. else:
  145. other_config_path = self.filename
  146. other_working_dir = os.path.dirname(other_config_path)
  147. other_already_seen = self.already_seen + [self.signature(service_dict['name'])]
  148. other_loader = ServiceLoader(
  149. working_dir=other_working_dir,
  150. filename=other_config_path,
  151. already_seen=other_already_seen,
  152. )
  153. other_config = load_yaml(other_config_path)
  154. other_service_dict = other_config[extends_options['service']]
  155. other_loader.detect_cycle(extends_options['service'])
  156. other_service_dict = other_loader.make_service_dict(
  157. service_dict['name'],
  158. other_service_dict,
  159. )
  160. validate_extended_service_dict(
  161. other_service_dict,
  162. filename=other_config_path,
  163. service=extends_options['service'],
  164. )
  165. return merge_service_dicts(other_service_dict, service_dict)
  166. def signature(self, name):
  167. return (self.filename, name)
  168. def validate_extends_options(self, service_name, extends_options):
  169. error_prefix = "Invalid 'extends' configuration for %s:" % service_name
  170. if not isinstance(extends_options, dict):
  171. raise ConfigurationError("%s must be a dictionary" % error_prefix)
  172. if 'service' not in extends_options:
  173. raise ConfigurationError(
  174. "%s you need to specify a service, e.g. 'service: web'" % error_prefix
  175. )
  176. if 'file' not in extends_options and self.filename is None:
  177. raise ConfigurationError(
  178. "%s you need to specify a 'file', e.g. 'file: something.yml'" % error_prefix
  179. )
  180. for k, _ in extends_options.items():
  181. if k not in ['file', 'service']:
  182. raise ConfigurationError(
  183. "%s unsupported configuration option '%s'" % (error_prefix, k)
  184. )
  185. return extends_options
  186. def validate_extended_service_dict(service_dict, filename, service):
  187. error_prefix = "Cannot extend service '%s' in %s:" % (service, filename)
  188. if 'links' in service_dict:
  189. raise ConfigurationError("%s services with 'links' cannot be extended" % error_prefix)
  190. if 'volumes_from' in service_dict:
  191. raise ConfigurationError("%s services with 'volumes_from' cannot be extended" % error_prefix)
  192. if 'net' in service_dict:
  193. if get_service_name_from_net(service_dict['net']) is not None:
  194. raise ConfigurationError("%s services with 'net: container' cannot be extended" % error_prefix)
  195. def process_container_options(service_dict, working_dir=None):
  196. for k in service_dict:
  197. if k not in ALLOWED_KEYS:
  198. msg = "Unsupported config option for %s service: '%s'" % (service_dict['name'], k)
  199. if k in DOCKER_CONFIG_HINTS:
  200. msg += " (did you mean '%s'?)" % DOCKER_CONFIG_HINTS[k]
  201. raise ConfigurationError(msg)
  202. service_dict = service_dict.copy()
  203. if 'memswap_limit' in service_dict and 'mem_limit' not in service_dict:
  204. raise ConfigurationError("Invalid 'memswap_limit' configuration for %s service: when defining 'memswap_limit' you must set 'mem_limit' as well" % service_dict['name'])
  205. if 'volumes' in service_dict and service_dict.get('volume_driver') is None:
  206. service_dict['volumes'] = resolve_volume_paths(service_dict['volumes'], working_dir=working_dir)
  207. if 'build' in service_dict:
  208. service_dict['build'] = resolve_build_path(service_dict['build'], working_dir=working_dir)
  209. if 'labels' in service_dict:
  210. service_dict['labels'] = parse_labels(service_dict['labels'])
  211. return service_dict
  212. def merge_service_dicts(base, override):
  213. d = base.copy()
  214. if 'environment' in base or 'environment' in override:
  215. d['environment'] = merge_environment(
  216. base.get('environment'),
  217. override.get('environment'),
  218. )
  219. path_mapping_keys = ['volumes', 'devices']
  220. for key in path_mapping_keys:
  221. if key in base or key in override:
  222. d[key] = merge_path_mappings(
  223. base.get(key),
  224. override.get(key),
  225. )
  226. if 'labels' in base or 'labels' in override:
  227. d['labels'] = merge_labels(
  228. base.get('labels'),
  229. override.get('labels'),
  230. )
  231. if 'image' in override and 'build' in d:
  232. del d['build']
  233. if 'build' in override and 'image' in d:
  234. del d['image']
  235. list_keys = ['ports', 'expose', 'external_links']
  236. for key in list_keys:
  237. if key in base or key in override:
  238. d[key] = base.get(key, []) + override.get(key, [])
  239. list_or_string_keys = ['dns', 'dns_search']
  240. for key in list_or_string_keys:
  241. if key in base or key in override:
  242. d[key] = to_list(base.get(key)) + to_list(override.get(key))
  243. already_merged_keys = ['environment', 'labels'] + path_mapping_keys + list_keys + list_or_string_keys
  244. for k in set(ALLOWED_KEYS) - set(already_merged_keys):
  245. if k in override:
  246. d[k] = override[k]
  247. return d
  248. def merge_environment(base, override):
  249. env = parse_environment(base)
  250. env.update(parse_environment(override))
  251. return env
  252. def parse_links(links):
  253. return dict(parse_link(l) for l in links)
  254. def parse_link(link):
  255. if ':' in link:
  256. source, alias = link.split(':', 1)
  257. return (alias, source)
  258. else:
  259. return (link, link)
  260. def get_env_files(options, working_dir=None):
  261. if 'env_file' not in options:
  262. return {}
  263. if working_dir is None:
  264. raise Exception("No working_dir passed to get_env_files()")
  265. env_files = options.get('env_file', [])
  266. if not isinstance(env_files, list):
  267. env_files = [env_files]
  268. return [expand_path(working_dir, path) for path in env_files]
  269. def resolve_environment(service_dict, working_dir=None):
  270. service_dict = service_dict.copy()
  271. if 'environment' not in service_dict and 'env_file' not in service_dict:
  272. return service_dict
  273. env = {}
  274. if 'env_file' in service_dict:
  275. for f in get_env_files(service_dict, working_dir=working_dir):
  276. env.update(env_vars_from_file(f))
  277. del service_dict['env_file']
  278. env.update(parse_environment(service_dict.get('environment')))
  279. env = dict(resolve_env_var(k, v) for k, v in six.iteritems(env))
  280. service_dict['environment'] = env
  281. return service_dict
  282. def parse_environment(environment):
  283. if not environment:
  284. return {}
  285. if isinstance(environment, list):
  286. return dict(split_env(e) for e in environment)
  287. if isinstance(environment, dict):
  288. return environment
  289. raise ConfigurationError(
  290. "environment \"%s\" must be a list or mapping," %
  291. environment
  292. )
  293. def split_env(env):
  294. if '=' in env:
  295. return env.split('=', 1)
  296. else:
  297. return env, None
  298. def resolve_env_var(key, val):
  299. if val is not None:
  300. return key, val
  301. elif key in os.environ:
  302. return key, os.environ[key]
  303. else:
  304. return key, ''
  305. def env_vars_from_file(filename):
  306. """
  307. Read in a line delimited file of environment variables.
  308. """
  309. if not os.path.exists(filename):
  310. raise ConfigurationError("Couldn't find env file: %s" % filename)
  311. env = {}
  312. for line in open(filename, 'r'):
  313. line = line.strip()
  314. if line and not line.startswith('#'):
  315. k, v = split_env(line)
  316. env[k] = v
  317. return env
  318. def resolve_volume_paths(volumes, working_dir=None):
  319. if working_dir is None:
  320. raise Exception("No working_dir passed to resolve_volume_paths()")
  321. return [resolve_volume_path(v, working_dir) for v in volumes]
  322. def resolve_volume_path(volume, working_dir):
  323. container_path, host_path = split_path_mapping(volume)
  324. container_path = os.path.expanduser(container_path)
  325. if host_path is not None:
  326. host_path = os.path.expanduser(host_path)
  327. return "%s:%s" % (expand_path(working_dir, host_path), container_path)
  328. else:
  329. return container_path
  330. def resolve_build_path(build_path, working_dir=None):
  331. if working_dir is None:
  332. raise Exception("No working_dir passed to resolve_build_path")
  333. return expand_path(working_dir, build_path)
  334. def validate_paths(service_dict):
  335. if 'build' in service_dict:
  336. build_path = service_dict['build']
  337. if not os.path.exists(build_path) or not os.access(build_path, os.R_OK):
  338. raise ConfigurationError("build path %s either does not exist or is not accessible." % build_path)
  339. def merge_path_mappings(base, override):
  340. d = dict_from_path_mappings(base)
  341. d.update(dict_from_path_mappings(override))
  342. return path_mappings_from_dict(d)
  343. def dict_from_path_mappings(path_mappings):
  344. if path_mappings:
  345. return dict(split_path_mapping(v) for v in path_mappings)
  346. else:
  347. return {}
  348. def path_mappings_from_dict(d):
  349. return [join_path_mapping(v) for v in d.items()]
  350. def split_path_mapping(string):
  351. if ':' in string:
  352. (host, container) = string.split(':', 1)
  353. return (container, host)
  354. else:
  355. return (string, None)
  356. def join_path_mapping(pair):
  357. (container, host) = pair
  358. if host is None:
  359. return container
  360. else:
  361. return ":".join((host, container))
  362. def merge_labels(base, override):
  363. labels = parse_labels(base)
  364. labels.update(parse_labels(override))
  365. return labels
  366. def parse_labels(labels):
  367. if not labels:
  368. return {}
  369. if isinstance(labels, list):
  370. return dict(split_label(e) for e in labels)
  371. if isinstance(labels, dict):
  372. return labels
  373. raise ConfigurationError(
  374. "labels \"%s\" must be a list or mapping" %
  375. labels
  376. )
  377. def split_label(label):
  378. if '=' in label:
  379. return label.split('=', 1)
  380. else:
  381. return label, ''
  382. def expand_path(working_dir, path):
  383. return os.path.abspath(os.path.join(working_dir, path))
  384. def to_list(value):
  385. if value is None:
  386. return []
  387. elif isinstance(value, six.string_types):
  388. return [value]
  389. else:
  390. return value
  391. def get_service_name_from_net(net_config):
  392. if not net_config:
  393. return
  394. if not net_config.startswith('container:'):
  395. return
  396. _, net_name = net_config.split(':', 1)
  397. return net_name
  398. def load_yaml(filename):
  399. try:
  400. with open(filename, 'r') as fh:
  401. return yaml.safe_load(fh)
  402. except IOError as e:
  403. raise ConfigurationError(six.text_type(e))