validation.py 15 KB

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