config.py 11 KB

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