1
0

config.py 13 KB

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