config.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565
  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. 'memswap_limit',
  31. 'net',
  32. 'log_driver',
  33. 'pid',
  34. 'ports',
  35. 'privileged',
  36. 'restart',
  37. 'security_opt',
  38. 'stdin_open',
  39. 'tty',
  40. 'user',
  41. 'volumes',
  42. 'volumes_from',
  43. 'working_dir',
  44. ]
  45. ALLOWED_KEYS = DOCKER_CONFIG_KEYS + [
  46. 'build',
  47. 'dockerfile',
  48. 'expose',
  49. 'external_links',
  50. 'name',
  51. ]
  52. DOCKER_CONFIG_HINTS = {
  53. 'cpu_share': 'cpu_shares',
  54. 'add_host': 'extra_hosts',
  55. 'hosts': 'extra_hosts',
  56. 'extra_host': 'extra_hosts',
  57. 'device': 'devices',
  58. 'link': 'links',
  59. 'memory_swap': 'memswap_limit',
  60. 'port': 'ports',
  61. 'privilege': 'privileged',
  62. 'priviliged': 'privileged',
  63. 'privilige': 'privileged',
  64. 'volume': 'volumes',
  65. 'workdir': 'working_dir',
  66. }
  67. SUPPORTED_FILENAMES = [
  68. 'docker-compose.yml',
  69. 'docker-compose.yaml',
  70. 'fig.yml',
  71. 'fig.yaml',
  72. ]
  73. log = logging.getLogger(__name__)
  74. ConfigDetails = namedtuple('ConfigDetails', 'config working_dir filename')
  75. def find(base_dir, filename):
  76. if filename == '-':
  77. return ConfigDetails(yaml.safe_load(sys.stdin), os.getcwd(), None)
  78. if filename:
  79. filename = os.path.join(base_dir, filename)
  80. else:
  81. filename = get_config_path(base_dir)
  82. return ConfigDetails(load_yaml(filename), os.path.dirname(filename), filename)
  83. def get_config_path(base_dir):
  84. (candidates, path) = find_candidates_in_parent_dirs(SUPPORTED_FILENAMES, base_dir)
  85. if len(candidates) == 0:
  86. raise ComposeFileNotFound(SUPPORTED_FILENAMES)
  87. winner = candidates[0]
  88. if len(candidates) > 1:
  89. log.warn("Found multiple config files with supported names: %s", ", ".join(candidates))
  90. log.warn("Using %s\n", winner)
  91. if winner == 'docker-compose.yaml':
  92. log.warn("Please be aware that .yml is the expected extension "
  93. "in most cases, and using .yaml can cause compatibility "
  94. "issues in future.\n")
  95. if winner.startswith("fig."):
  96. log.warn("%s is deprecated and will not be supported in future. "
  97. "Please rename your config file to docker-compose.yml\n" % winner)
  98. return os.path.join(path, winner)
  99. def load(config_details):
  100. dictionary, working_dir, filename = config_details
  101. service_dicts = []
  102. for service_name, service_dict in list(dictionary.items()):
  103. if not isinstance(service_dict, dict):
  104. 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)
  105. loader = ServiceLoader(working_dir=working_dir, filename=filename)
  106. service_dict = loader.make_service_dict(service_name, service_dict)
  107. validate_paths(service_dict)
  108. service_dicts.append(service_dict)
  109. return service_dicts
  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 'memswap_limit' in service_dict and 'mem_limit' not in service_dict:
  196. raise ConfigurationError("Invalid 'memswap_limit' configuration for %s service: when defining 'memswap_limit' you must set 'mem_limit' as well" % service_dict['name'])
  197. if 'volumes' in service_dict:
  198. service_dict['volumes'] = resolve_volume_paths(service_dict['volumes'], working_dir=working_dir)
  199. if 'build' in service_dict:
  200. service_dict['build'] = resolve_build_path(service_dict['build'], working_dir=working_dir)
  201. if 'labels' in service_dict:
  202. service_dict['labels'] = parse_labels(service_dict['labels'])
  203. return service_dict
  204. def merge_service_dicts(base, override):
  205. d = base.copy()
  206. if 'environment' in base or 'environment' in override:
  207. d['environment'] = merge_environment(
  208. base.get('environment'),
  209. override.get('environment'),
  210. )
  211. path_mapping_keys = ['volumes', 'devices']
  212. for key in path_mapping_keys:
  213. if key in base or key in override:
  214. d[key] = merge_path_mappings(
  215. base.get(key),
  216. override.get(key),
  217. )
  218. if 'labels' in base or 'labels' in override:
  219. d['labels'] = merge_labels(
  220. base.get('labels'),
  221. override.get('labels'),
  222. )
  223. if 'image' in override and 'build' in d:
  224. del d['build']
  225. if 'build' in override and 'image' in d:
  226. del d['image']
  227. list_keys = ['ports', 'expose', 'external_links']
  228. for key in list_keys:
  229. if key in base or key in override:
  230. d[key] = base.get(key, []) + override.get(key, [])
  231. list_or_string_keys = ['dns', 'dns_search']
  232. for key in list_or_string_keys:
  233. if key in base or key in override:
  234. d[key] = to_list(base.get(key)) + to_list(override.get(key))
  235. already_merged_keys = ['environment', 'labels'] + path_mapping_keys + list_keys + list_or_string_keys
  236. for k in set(ALLOWED_KEYS) - set(already_merged_keys):
  237. if k in override:
  238. d[k] = override[k]
  239. return d
  240. def merge_environment(base, override):
  241. env = parse_environment(base)
  242. env.update(parse_environment(override))
  243. return env
  244. def parse_links(links):
  245. return dict(parse_link(l) for l in links)
  246. def parse_link(link):
  247. if ':' in link:
  248. source, alias = link.split(':', 1)
  249. return (alias, source)
  250. else:
  251. return (link, link)
  252. def get_env_files(options, working_dir=None):
  253. if 'env_file' not in options:
  254. return {}
  255. if working_dir is None:
  256. raise Exception("No working_dir passed to get_env_files()")
  257. env_files = options.get('env_file', [])
  258. if not isinstance(env_files, list):
  259. env_files = [env_files]
  260. return [expand_path(working_dir, path) for path in env_files]
  261. def resolve_environment(service_dict, working_dir=None):
  262. service_dict = service_dict.copy()
  263. if 'environment' not in service_dict and 'env_file' not in service_dict:
  264. return service_dict
  265. env = {}
  266. if 'env_file' in service_dict:
  267. for f in get_env_files(service_dict, working_dir=working_dir):
  268. env.update(env_vars_from_file(f))
  269. del service_dict['env_file']
  270. env.update(parse_environment(service_dict.get('environment')))
  271. env = dict(resolve_env_var(k, v) for k, v in six.iteritems(env))
  272. service_dict['environment'] = env
  273. return service_dict
  274. def parse_environment(environment):
  275. if not environment:
  276. return {}
  277. if isinstance(environment, list):
  278. return dict(split_env(e) for e in environment)
  279. if isinstance(environment, dict):
  280. return environment
  281. raise ConfigurationError(
  282. "environment \"%s\" must be a list or mapping," %
  283. environment
  284. )
  285. def split_env(env):
  286. if '=' in env:
  287. return env.split('=', 1)
  288. else:
  289. return env, None
  290. def resolve_env_var(key, val):
  291. if val is not None:
  292. return key, val
  293. elif key in os.environ:
  294. return key, os.environ[key]
  295. else:
  296. return key, ''
  297. def env_vars_from_file(filename):
  298. """
  299. Read in a line delimited file of environment variables.
  300. """
  301. if not os.path.exists(filename):
  302. raise ConfigurationError("Couldn't find env file: %s" % filename)
  303. env = {}
  304. for line in open(filename, 'r'):
  305. line = line.strip()
  306. if line and not line.startswith('#'):
  307. k, v = split_env(line)
  308. env[k] = v
  309. return env
  310. def resolve_volume_paths(volumes, working_dir=None):
  311. if working_dir is None:
  312. raise Exception("No working_dir passed to resolve_volume_paths()")
  313. return [resolve_volume_path(v, working_dir) for v in volumes]
  314. def resolve_volume_path(volume, working_dir):
  315. container_path, host_path = split_path_mapping(volume)
  316. container_path = os.path.expanduser(os.path.expandvars(container_path))
  317. if host_path is not None:
  318. host_path = os.path.expanduser(os.path.expandvars(host_path))
  319. return "%s:%s" % (expand_path(working_dir, host_path), container_path)
  320. else:
  321. return container_path
  322. def resolve_build_path(build_path, working_dir=None):
  323. if working_dir is None:
  324. raise Exception("No working_dir passed to resolve_build_path")
  325. return expand_path(working_dir, build_path)
  326. def validate_paths(service_dict):
  327. if 'build' in service_dict:
  328. build_path = service_dict['build']
  329. if not os.path.exists(build_path) or not os.access(build_path, os.R_OK):
  330. raise ConfigurationError("build path %s either does not exist or is not accessible." % build_path)
  331. def merge_path_mappings(base, override):
  332. d = dict_from_path_mappings(base)
  333. d.update(dict_from_path_mappings(override))
  334. return path_mappings_from_dict(d)
  335. def dict_from_path_mappings(path_mappings):
  336. if path_mappings:
  337. return dict(split_path_mapping(v) for v in path_mappings)
  338. else:
  339. return {}
  340. def path_mappings_from_dict(d):
  341. return [join_path_mapping(v) for v in d.items()]
  342. def split_path_mapping(string):
  343. if ':' in string:
  344. (host, container) = string.split(':', 1)
  345. return (container, host)
  346. else:
  347. return (string, None)
  348. def join_path_mapping(pair):
  349. (container, host) = pair
  350. if host is None:
  351. return container
  352. else:
  353. return ":".join((host, container))
  354. def merge_labels(base, override):
  355. labels = parse_labels(base)
  356. labels.update(parse_labels(override))
  357. return labels
  358. def parse_labels(labels):
  359. if not labels:
  360. return {}
  361. if isinstance(labels, list):
  362. return dict(split_label(e) for e in labels)
  363. if isinstance(labels, dict):
  364. return labels
  365. raise ConfigurationError(
  366. "labels \"%s\" must be a list or mapping" %
  367. labels
  368. )
  369. def split_label(label):
  370. if '=' in label:
  371. return label.split('=', 1)
  372. else:
  373. return label, ''
  374. def expand_path(working_dir, path):
  375. return os.path.abspath(os.path.join(working_dir, path))
  376. def to_list(value):
  377. if value is None:
  378. return []
  379. elif isinstance(value, six.string_types):
  380. return [value]
  381. else:
  382. return value
  383. def get_service_name_from_net(net_config):
  384. if not net_config:
  385. return
  386. if not net_config.startswith('container:'):
  387. return
  388. _, net_name = net_config.split(':', 1)
  389. return net_name
  390. def load_yaml(filename):
  391. try:
  392. with open(filename, 'r') as fh:
  393. return yaml.safe_load(fh)
  394. except IOError as e:
  395. raise ConfigurationError(six.text_type(e))
  396. class ConfigurationError(Exception):
  397. def __init__(self, msg):
  398. self.msg = msg
  399. def __str__(self):
  400. return self.msg
  401. class CircularReference(ConfigurationError):
  402. def __init__(self, trail):
  403. self.trail = trail
  404. @property
  405. def msg(self):
  406. lines = [
  407. "{} in {}".format(service_name, filename)
  408. for (filename, service_name) in self.trail
  409. ]
  410. return "Circular reference:\n {}".format("\n extends ".join(lines))
  411. class ComposeFileNotFound(ConfigurationError):
  412. def __init__(self, supported_filenames):
  413. super(ComposeFileNotFound, self).__init__("""
  414. Can't find a suitable configuration file in this directory or any parent. Are you in the right directory?
  415. Supported filenames: %s
  416. """ % ", ".join(supported_filenames))