config.py 16 KB

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