config.py 15 KB

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