config.py 16 KB

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