config.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388
  1. import os
  2. import yaml
  3. import six
  4. DOCKER_CONFIG_KEYS = [
  5. 'cap_add',
  6. 'cap_drop',
  7. 'cpu_shares',
  8. 'command',
  9. 'detach',
  10. 'dns',
  11. 'dns_search',
  12. 'domainname',
  13. 'entrypoint',
  14. 'env_file',
  15. 'environment',
  16. 'hostname',
  17. 'image',
  18. 'links',
  19. 'mem_limit',
  20. 'net',
  21. 'ports',
  22. 'privileged',
  23. 'restart',
  24. 'stdin_open',
  25. 'tty',
  26. 'user',
  27. 'volumes',
  28. 'volumes_from',
  29. 'working_dir',
  30. ]
  31. ALLOWED_KEYS = DOCKER_CONFIG_KEYS + [
  32. 'build',
  33. 'expose',
  34. 'external_links',
  35. 'name',
  36. ]
  37. DOCKER_CONFIG_HINTS = {
  38. 'cpu_share': 'cpu_shares',
  39. 'link': 'links',
  40. 'port': 'ports',
  41. 'privilege': 'privileged',
  42. 'priviliged': 'privileged',
  43. 'privilige': 'privileged',
  44. 'volume': 'volumes',
  45. 'workdir': 'working_dir',
  46. }
  47. def load(filename):
  48. working_dir = os.path.dirname(filename)
  49. return from_dictionary(load_yaml(filename), working_dir=working_dir, filename=filename)
  50. def from_dictionary(dictionary, working_dir=None, filename=None):
  51. service_dicts = []
  52. for service_name, service_dict in list(dictionary.items()):
  53. if not isinstance(service_dict, dict):
  54. 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)
  55. loader = ServiceLoader(working_dir=working_dir, filename=filename)
  56. service_dict = loader.make_service_dict(service_name, service_dict)
  57. service_dicts.append(service_dict)
  58. return service_dicts
  59. def make_service_dict(name, service_dict, working_dir=None):
  60. return ServiceLoader(working_dir=working_dir).make_service_dict(name, service_dict)
  61. class ServiceLoader(object):
  62. def __init__(self, working_dir, filename=None, already_seen=None):
  63. self.working_dir = working_dir
  64. self.filename = filename
  65. self.already_seen = already_seen or []
  66. def make_service_dict(self, name, service_dict):
  67. if self.signature(name) in self.already_seen:
  68. raise CircularReference(self.already_seen)
  69. service_dict = service_dict.copy()
  70. service_dict['name'] = name
  71. service_dict = resolve_environment(service_dict, working_dir=self.working_dir)
  72. service_dict = self.resolve_extends(service_dict)
  73. return process_container_options(service_dict, working_dir=self.working_dir)
  74. def resolve_extends(self, service_dict):
  75. if 'extends' not in service_dict:
  76. return service_dict
  77. extends_options = process_extends_options(service_dict['name'], service_dict['extends'])
  78. if self.working_dir is None:
  79. raise Exception("No working_dir passed to ServiceLoader()")
  80. other_config_path = expand_path(self.working_dir, extends_options['file'])
  81. other_working_dir = os.path.dirname(other_config_path)
  82. other_already_seen = self.already_seen + [self.signature(service_dict['name'])]
  83. other_loader = ServiceLoader(
  84. working_dir=other_working_dir,
  85. filename=other_config_path,
  86. already_seen=other_already_seen,
  87. )
  88. other_config = load_yaml(other_config_path)
  89. other_service_dict = other_config[extends_options['service']]
  90. other_service_dict = other_loader.make_service_dict(
  91. service_dict['name'],
  92. other_service_dict,
  93. )
  94. validate_extended_service_dict(
  95. other_service_dict,
  96. filename=other_config_path,
  97. service=extends_options['service'],
  98. )
  99. return merge_service_dicts(other_service_dict, service_dict)
  100. def signature(self, name):
  101. return (self.filename, name)
  102. def process_extends_options(service_name, extends_options):
  103. error_prefix = "Invalid 'extends' configuration for %s:" % service_name
  104. if not isinstance(extends_options, dict):
  105. raise ConfigurationError("%s must be a dictionary" % error_prefix)
  106. if 'service' not in extends_options:
  107. raise ConfigurationError(
  108. "%s you need to specify a service, e.g. 'service: web'" % error_prefix
  109. )
  110. for k, _ in extends_options.items():
  111. if k not in ['file', 'service']:
  112. raise ConfigurationError(
  113. "%s unsupported configuration option '%s'" % (error_prefix, k)
  114. )
  115. return extends_options
  116. def validate_extended_service_dict(service_dict, filename, service):
  117. error_prefix = "Cannot extend service '%s' in %s:" % (service, filename)
  118. if 'links' in service_dict:
  119. raise ConfigurationError("%s services with 'links' cannot be extended" % error_prefix)
  120. if 'volumes_from' in service_dict:
  121. raise ConfigurationError("%s services with 'volumes_from' cannot be extended" % error_prefix)
  122. if 'net' in service_dict:
  123. if get_service_name_from_net(service_dict['net']) is not None:
  124. raise ConfigurationError("%s services with 'net: container' cannot be extended" % error_prefix)
  125. def process_container_options(service_dict, working_dir=None):
  126. for k in service_dict:
  127. if k not in ALLOWED_KEYS:
  128. msg = "Unsupported config option for %s service: '%s'" % (service_dict['name'], k)
  129. if k in DOCKER_CONFIG_HINTS:
  130. msg += " (did you mean '%s'?)" % DOCKER_CONFIG_HINTS[k]
  131. raise ConfigurationError(msg)
  132. service_dict = service_dict.copy()
  133. if 'volumes' in service_dict:
  134. service_dict['volumes'] = resolve_host_paths(service_dict['volumes'], working_dir=working_dir)
  135. return service_dict
  136. def merge_service_dicts(base, override):
  137. d = base.copy()
  138. if 'environment' in base or 'environment' in override:
  139. d['environment'] = merge_environment(
  140. base.get('environment'),
  141. override.get('environment'),
  142. )
  143. if 'volumes' in base or 'volumes' in override:
  144. d['volumes'] = merge_volumes(
  145. base.get('volumes'),
  146. override.get('volumes'),
  147. )
  148. for k in ALLOWED_KEYS:
  149. if k not in ['environment', 'volumes']:
  150. if k in override:
  151. d[k] = override[k]
  152. return d
  153. def merge_environment(base, override):
  154. env = parse_environment(base)
  155. env.update(parse_environment(override))
  156. return env
  157. def parse_links(links):
  158. return dict(parse_link(l) for l in links)
  159. def parse_link(link):
  160. if ':' in link:
  161. source, alias = link.split(':', 1)
  162. return (alias, source)
  163. else:
  164. return (link, link)
  165. def get_env_files(options, working_dir=None):
  166. if 'env_file' not in options:
  167. return {}
  168. if working_dir is None:
  169. raise Exception("No working_dir passed to get_env_files()")
  170. env_files = options.get('env_file', [])
  171. if not isinstance(env_files, list):
  172. env_files = [env_files]
  173. return [expand_path(working_dir, path) for path in env_files]
  174. def resolve_environment(service_dict, working_dir=None):
  175. service_dict = service_dict.copy()
  176. if 'environment' not in service_dict and 'env_file' not in service_dict:
  177. return service_dict
  178. env = {}
  179. if 'env_file' in service_dict:
  180. for f in get_env_files(service_dict, working_dir=working_dir):
  181. env.update(env_vars_from_file(f))
  182. del service_dict['env_file']
  183. env.update(parse_environment(service_dict.get('environment')))
  184. env = dict(resolve_env_var(k, v) for k, v in six.iteritems(env))
  185. service_dict['environment'] = env
  186. return service_dict
  187. def parse_environment(environment):
  188. if not environment:
  189. return {}
  190. if isinstance(environment, list):
  191. return dict(split_env(e) for e in environment)
  192. if isinstance(environment, dict):
  193. return environment
  194. raise ConfigurationError(
  195. "environment \"%s\" must be a list or mapping," %
  196. environment
  197. )
  198. def split_env(env):
  199. if '=' in env:
  200. return env.split('=', 1)
  201. else:
  202. return env, None
  203. def resolve_env_var(key, val):
  204. if val is not None:
  205. return key, val
  206. elif key in os.environ:
  207. return key, os.environ[key]
  208. else:
  209. return key, ''
  210. def env_vars_from_file(filename):
  211. """
  212. Read in a line delimited file of environment variables.
  213. """
  214. if not os.path.exists(filename):
  215. raise ConfigurationError("Couldn't find env file: %s" % filename)
  216. env = {}
  217. for line in open(filename, 'r'):
  218. line = line.strip()
  219. if line and not line.startswith('#'):
  220. k, v = split_env(line)
  221. env[k] = v
  222. return env
  223. def resolve_host_paths(volumes, working_dir=None):
  224. if working_dir is None:
  225. raise Exception("No working_dir passed to resolve_host_paths()")
  226. return [resolve_host_path(v, working_dir) for v in volumes]
  227. def resolve_host_path(volume, working_dir):
  228. container_path, host_path = split_volume(volume)
  229. if host_path is not None:
  230. return "%s:%s" % (expand_path(working_dir, host_path), container_path)
  231. else:
  232. return container_path
  233. def merge_volumes(base, override):
  234. d = dict_from_volumes(base)
  235. d.update(dict_from_volumes(override))
  236. return volumes_from_dict(d)
  237. def dict_from_volumes(volumes):
  238. if volumes:
  239. return dict(split_volume(v) for v in volumes)
  240. else:
  241. return {}
  242. def volumes_from_dict(d):
  243. return [join_volume(v) for v in d.items()]
  244. def split_volume(string):
  245. if ':' in string:
  246. (host, container) = string.split(':', 1)
  247. return (container, host)
  248. else:
  249. return (string, None)
  250. def join_volume(pair):
  251. (container, host) = pair
  252. if host is None:
  253. return container
  254. else:
  255. return ":".join((host, container))
  256. def expand_path(working_dir, path):
  257. return os.path.abspath(os.path.join(working_dir, path))
  258. def get_service_name_from_net(net_config):
  259. if not net_config:
  260. return
  261. if not net_config.startswith('container:'):
  262. return
  263. _, net_name = net_config.split(':', 1)
  264. return net_name
  265. def load_yaml(filename):
  266. try:
  267. with open(filename, 'r') as fh:
  268. return yaml.safe_load(fh)
  269. except IOError as e:
  270. raise ConfigurationError(six.text_type(e))
  271. class ConfigurationError(Exception):
  272. def __init__(self, msg):
  273. self.msg = msg
  274. def __str__(self):
  275. return self.msg
  276. class CircularReference(ConfigurationError):
  277. def __init__(self, trail):
  278. self.trail = trail
  279. @property
  280. def msg(self):
  281. lines = [
  282. "{} in {}".format(service_name, filename)
  283. for (filename, service_name) in self.trail
  284. ]
  285. return "Circular reference:\n {}".format("\n extends ".join(lines))