validation.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426
  1. from __future__ import absolute_import
  2. from __future__ import unicode_literals
  3. import json
  4. import logging
  5. import os
  6. import re
  7. import sys
  8. import six
  9. from docker.utils.ports import split_port
  10. from jsonschema import Draft4Validator
  11. from jsonschema import FormatChecker
  12. from jsonschema import RefResolver
  13. from jsonschema import ValidationError
  14. from ..const import COMPOSEFILE_V1 as V1
  15. from .errors import ConfigurationError
  16. from .errors import VERSION_EXPLANATION
  17. from .sort_services import get_service_name_from_network_mode
  18. log = logging.getLogger(__name__)
  19. DOCKER_CONFIG_HINTS = {
  20. 'cpu_share': 'cpu_shares',
  21. 'add_host': 'extra_hosts',
  22. 'hosts': 'extra_hosts',
  23. 'extra_host': 'extra_hosts',
  24. 'device': 'devices',
  25. 'link': 'links',
  26. 'memory_swap': 'memswap_limit',
  27. 'port': 'ports',
  28. 'privilege': 'privileged',
  29. 'priviliged': 'privileged',
  30. 'privilige': 'privileged',
  31. 'volume': 'volumes',
  32. 'workdir': 'working_dir',
  33. }
  34. VALID_NAME_CHARS = '[a-zA-Z0-9\._\-]'
  35. VALID_EXPOSE_FORMAT = r'^\d+(\-\d+)?(\/[a-zA-Z]+)?$'
  36. @FormatChecker.cls_checks(format="ports", raises=ValidationError)
  37. def format_ports(instance):
  38. try:
  39. split_port(instance)
  40. except ValueError as e:
  41. raise ValidationError(six.text_type(e))
  42. return True
  43. @FormatChecker.cls_checks(format="expose", raises=ValidationError)
  44. def format_expose(instance):
  45. if isinstance(instance, six.string_types):
  46. if not re.match(VALID_EXPOSE_FORMAT, instance):
  47. raise ValidationError(
  48. "should be of the format 'PORT[/PROTOCOL]'")
  49. return True
  50. def match_named_volumes(service_dict, project_volumes):
  51. service_volumes = service_dict.get('volumes', [])
  52. for volume_spec in service_volumes:
  53. if volume_spec.is_named_volume and volume_spec.external not in project_volumes:
  54. raise ConfigurationError(
  55. 'Named volume "{0}" is used in service "{1}" but no'
  56. ' declaration was found in the volumes section.'.format(
  57. volume_spec.repr(), service_dict.get('name')
  58. )
  59. )
  60. def python_type_to_yaml_type(type_):
  61. type_name = type(type_).__name__
  62. return {
  63. 'dict': 'mapping',
  64. 'list': 'array',
  65. 'int': 'number',
  66. 'float': 'number',
  67. 'bool': 'boolean',
  68. 'unicode': 'string',
  69. 'str': 'string',
  70. 'bytes': 'string',
  71. }.get(type_name, type_name)
  72. def validate_config_section(filename, config, section):
  73. """Validate the structure of a configuration section. This must be done
  74. before interpolation so it's separate from schema validation.
  75. """
  76. if not isinstance(config, dict):
  77. raise ConfigurationError(
  78. "In file '{filename}', {section} must be a mapping, not "
  79. "{type}.".format(
  80. filename=filename,
  81. section=section,
  82. type=anglicize_json_type(python_type_to_yaml_type(config))))
  83. for key, value in config.items():
  84. if not isinstance(key, six.string_types):
  85. raise ConfigurationError(
  86. "In file '{filename}', the {section} name {name} must be a "
  87. "quoted string, i.e. '{name}'.".format(
  88. filename=filename,
  89. section=section,
  90. name=key))
  91. if not isinstance(value, (dict, type(None))):
  92. raise ConfigurationError(
  93. "In file '{filename}', {section} '{name}' must be a mapping not "
  94. "{type}.".format(
  95. filename=filename,
  96. section=section,
  97. name=key,
  98. type=anglicize_json_type(python_type_to_yaml_type(value))))
  99. def validate_top_level_object(config_file):
  100. if not isinstance(config_file.config, dict):
  101. raise ConfigurationError(
  102. "Top level object in '{}' needs to be an object not '{}'.".format(
  103. config_file.filename,
  104. type(config_file.config)))
  105. def validate_ulimits(service_config):
  106. ulimit_config = service_config.config.get('ulimits', {})
  107. for limit_name, soft_hard_values in six.iteritems(ulimit_config):
  108. if isinstance(soft_hard_values, dict):
  109. if not soft_hard_values['soft'] <= soft_hard_values['hard']:
  110. raise ConfigurationError(
  111. "Service '{s.name}' has invalid ulimit '{ulimit}'. "
  112. "'soft' value can not be greater than 'hard' value ".format(
  113. s=service_config,
  114. ulimit=ulimit_config))
  115. def validate_extends_file_path(service_name, extends_options, filename):
  116. """
  117. The service to be extended must either be defined in the config key 'file',
  118. or within 'filename'.
  119. """
  120. error_prefix = "Invalid 'extends' configuration for %s:" % service_name
  121. if 'file' not in extends_options and filename is None:
  122. raise ConfigurationError(
  123. "%s you need to specify a 'file', e.g. 'file: something.yml'" % error_prefix
  124. )
  125. def validate_network_mode(service_config, service_names):
  126. network_mode = service_config.config.get('network_mode')
  127. if not network_mode:
  128. return
  129. if 'networks' in service_config.config:
  130. raise ConfigurationError("'network_mode' and 'networks' cannot be combined")
  131. dependency = get_service_name_from_network_mode(network_mode)
  132. if not dependency:
  133. return
  134. if dependency not in service_names:
  135. raise ConfigurationError(
  136. "Service '{s.name}' uses the network stack of service '{dep}' which "
  137. "is undefined.".format(s=service_config, dep=dependency))
  138. def validate_links(service_config, service_names):
  139. for link in service_config.config.get('links', []):
  140. if link.split(':')[0] not in service_names:
  141. raise ConfigurationError(
  142. "Service '{s.name}' has a link to service '{link}' which is "
  143. "undefined.".format(s=service_config, link=link))
  144. def validate_depends_on(service_config, service_names):
  145. deps = service_config.config.get('depends_on', {})
  146. for dependency in deps.keys():
  147. if dependency not in service_names:
  148. raise ConfigurationError(
  149. "Service '{s.name}' depends on service '{dep}' which is "
  150. "undefined.".format(s=service_config, dep=dependency)
  151. )
  152. def get_unsupported_config_msg(path, error_key):
  153. msg = "Unsupported config option for {}: '{}'".format(path_string(path), error_key)
  154. if error_key in DOCKER_CONFIG_HINTS:
  155. msg += " (did you mean '{}'?)".format(DOCKER_CONFIG_HINTS[error_key])
  156. return msg
  157. def anglicize_json_type(json_type):
  158. if json_type.startswith(('a', 'e', 'i', 'o', 'u')):
  159. return 'an ' + json_type
  160. return 'a ' + json_type
  161. def is_service_dict_schema(schema_id):
  162. return schema_id in ('config_schema_v1.json', '#/properties/services')
  163. def handle_error_for_schema_with_id(error, path):
  164. schema_id = error.schema['id']
  165. if is_service_dict_schema(schema_id) and error.validator == 'additionalProperties':
  166. return "Invalid service name '{}' - only {} characters are allowed".format(
  167. # The service_name is one of the keys in the json object
  168. [i for i in list(error.instance) if not i or any(filter(
  169. lambda c: not re.match(VALID_NAME_CHARS, c), i
  170. ))][0],
  171. VALID_NAME_CHARS
  172. )
  173. if error.validator == 'additionalProperties':
  174. if schema_id == '#/definitions/service':
  175. invalid_config_key = parse_key_from_error_msg(error)
  176. return get_unsupported_config_msg(path, invalid_config_key)
  177. if not error.path:
  178. return '{}\n\n{}'.format(error.message, VERSION_EXPLANATION)
  179. def handle_generic_error(error, path):
  180. msg_format = None
  181. error_msg = error.message
  182. if error.validator == 'oneOf':
  183. msg_format = "{path} {msg}"
  184. config_key, error_msg = _parse_oneof_validator(error)
  185. if config_key:
  186. path.append(config_key)
  187. elif error.validator == 'type':
  188. msg_format = "{path} contains an invalid type, it should be {msg}"
  189. error_msg = _parse_valid_types_from_validator(error.validator_value)
  190. elif error.validator == 'required':
  191. error_msg = ", ".join(error.validator_value)
  192. msg_format = "{path} is invalid, {msg} is required."
  193. elif error.validator == 'dependencies':
  194. config_key = list(error.validator_value.keys())[0]
  195. required_keys = ",".join(error.validator_value[config_key])
  196. msg_format = "{path} is invalid: {msg}"
  197. path.append(config_key)
  198. error_msg = "when defining '{}' you must set '{}' as well".format(
  199. config_key,
  200. required_keys)
  201. elif error.cause:
  202. error_msg = six.text_type(error.cause)
  203. msg_format = "{path} is invalid: {msg}"
  204. elif error.path:
  205. msg_format = "{path} value {msg}"
  206. if msg_format:
  207. return msg_format.format(path=path_string(path), msg=error_msg)
  208. return error.message
  209. def parse_key_from_error_msg(error):
  210. return error.message.split("'")[1]
  211. def path_string(path):
  212. return ".".join(c for c in path if isinstance(c, six.string_types))
  213. def _parse_valid_types_from_validator(validator):
  214. """A validator value can be either an array of valid types or a string of
  215. a valid type. Parse the valid types and prefix with the correct article.
  216. """
  217. if not isinstance(validator, list):
  218. return anglicize_json_type(validator)
  219. if len(validator) == 1:
  220. return anglicize_json_type(validator[0])
  221. return "{}, or {}".format(
  222. ", ".join([anglicize_json_type(validator[0])] + validator[1:-1]),
  223. anglicize_json_type(validator[-1]))
  224. def _parse_oneof_validator(error):
  225. """oneOf has multiple schemas, so we need to reason about which schema, sub
  226. schema or constraint the validation is failing on.
  227. Inspecting the context value of a ValidationError gives us information about
  228. which sub schema failed and which kind of error it is.
  229. """
  230. types = []
  231. for context in error.context:
  232. if context.validator == 'oneOf':
  233. _, error_msg = _parse_oneof_validator(context)
  234. return path_string(context.path), error_msg
  235. if context.validator == 'required':
  236. return (None, context.message)
  237. if context.validator == 'additionalProperties':
  238. invalid_config_key = parse_key_from_error_msg(context)
  239. return (None, "contains unsupported option: '{}'".format(invalid_config_key))
  240. if context.path:
  241. return (
  242. path_string(context.path),
  243. "contains {}, which is an invalid type, it should be {}".format(
  244. json.dumps(context.instance),
  245. _parse_valid_types_from_validator(context.validator_value)),
  246. )
  247. if context.validator == 'uniqueItems':
  248. return (
  249. None,
  250. "contains non unique items, please remove duplicates from {}".format(
  251. context.instance),
  252. )
  253. if context.validator == 'type':
  254. types.append(context.validator_value)
  255. valid_types = _parse_valid_types_from_validator(types)
  256. return (None, "contains an invalid type, it should be {}".format(valid_types))
  257. def process_service_constraint_errors(error, service_name, version):
  258. if version == V1:
  259. if 'image' in error.instance and 'build' in error.instance:
  260. return (
  261. "Service {} has both an image and build path specified. "
  262. "A service can either be built to image or use an existing "
  263. "image, not both.".format(service_name))
  264. if 'image' in error.instance and 'dockerfile' in error.instance:
  265. return (
  266. "Service {} has both an image and alternate Dockerfile. "
  267. "A service can either be built to image or use an existing "
  268. "image, not both.".format(service_name))
  269. if 'image' not in error.instance and 'build' not in error.instance:
  270. return (
  271. "Service {} has neither an image nor a build context specified. "
  272. "At least one must be provided.".format(service_name))
  273. def process_config_schema_errors(error):
  274. path = list(error.path)
  275. if 'id' in error.schema:
  276. error_msg = handle_error_for_schema_with_id(error, path)
  277. if error_msg:
  278. return error_msg
  279. return handle_generic_error(error, path)
  280. def validate_against_config_schema(config_file):
  281. schema = load_jsonschema(config_file.version)
  282. format_checker = FormatChecker(["ports", "expose"])
  283. validator = Draft4Validator(
  284. schema,
  285. resolver=RefResolver(get_resolver_path(), schema),
  286. format_checker=format_checker)
  287. handle_errors(
  288. validator.iter_errors(config_file.config),
  289. process_config_schema_errors,
  290. config_file.filename)
  291. def validate_service_constraints(config, service_name, version):
  292. def handler(errors):
  293. return process_service_constraint_errors(errors, service_name, version)
  294. schema = load_jsonschema(version)
  295. validator = Draft4Validator(schema['definitions']['constraints']['service'])
  296. handle_errors(validator.iter_errors(config), handler, None)
  297. def get_schema_path():
  298. return os.path.dirname(os.path.abspath(__file__))
  299. def load_jsonschema(version):
  300. filename = os.path.join(
  301. get_schema_path(),
  302. "config_schema_v{0}.json".format(version))
  303. with open(filename, "r") as fh:
  304. return json.load(fh)
  305. def get_resolver_path():
  306. schema_path = get_schema_path()
  307. if sys.platform == "win32":
  308. scheme = "///"
  309. # TODO: why is this necessary?
  310. schema_path = schema_path.replace('\\', '/')
  311. else:
  312. scheme = "//"
  313. return "file:{}{}/".format(scheme, schema_path)
  314. def handle_errors(errors, format_error_func, filename):
  315. """jsonschema returns an error tree full of information to explain what has
  316. gone wrong. Process each error and pull out relevant information and re-write
  317. helpful error messages that are relevant.
  318. """
  319. errors = list(sorted(errors, key=str))
  320. if not errors:
  321. return
  322. error_msg = '\n'.join(format_error_func(error) for error in errors)
  323. raise ConfigurationError(
  324. "The Compose file{file_msg} is invalid because:\n{error_msg}".format(
  325. file_msg=" '{}'".format(filename) if filename else "",
  326. error_msg=error_msg))