config.py 16 KB

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