validation.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313
  1. import json
  2. import logging
  3. import os
  4. import sys
  5. from functools import wraps
  6. from docker.utils.ports import split_port
  7. from jsonschema import Draft4Validator
  8. from jsonschema import FormatChecker
  9. from jsonschema import RefResolver
  10. from jsonschema import ValidationError
  11. from .errors import ConfigurationError
  12. log = logging.getLogger(__name__)
  13. DOCKER_CONFIG_HINTS = {
  14. 'cpu_share': 'cpu_shares',
  15. 'add_host': 'extra_hosts',
  16. 'hosts': 'extra_hosts',
  17. 'extra_host': 'extra_hosts',
  18. 'device': 'devices',
  19. 'link': 'links',
  20. 'memory_swap': 'memswap_limit',
  21. 'port': 'ports',
  22. 'privilege': 'privileged',
  23. 'priviliged': 'privileged',
  24. 'privilige': 'privileged',
  25. 'volume': 'volumes',
  26. 'workdir': 'working_dir',
  27. }
  28. VALID_NAME_CHARS = '[a-zA-Z0-9\._\-]'
  29. @FormatChecker.cls_checks(
  30. format="ports",
  31. raises=ValidationError(
  32. "Invalid port formatting, it should be "
  33. "'[[remote_ip:]remote_port:]port[/protocol]'"))
  34. def format_ports(instance):
  35. try:
  36. split_port(instance)
  37. except ValueError:
  38. return False
  39. return True
  40. @FormatChecker.cls_checks(format="environment")
  41. def format_boolean_in_environment(instance):
  42. """
  43. Check if there is a boolean in the environment and display a warning.
  44. Always return True here so the validation won't raise an error.
  45. """
  46. if isinstance(instance, bool):
  47. log.warn(
  48. "Warning: There is a boolean value in the 'environment' key.\n"
  49. "Environment variables can only be strings.\nPlease add quotes to any boolean values to make them string "
  50. "(eg, 'True', 'yes', 'N').\nThis warning will become an error in a future release. \r\n"
  51. )
  52. return True
  53. def validate_service_names(func):
  54. @wraps(func)
  55. def func_wrapper(config):
  56. for service_name in config.keys():
  57. if type(service_name) is int:
  58. raise ConfigurationError(
  59. "Service name: {} needs to be a string, eg '{}'".format(service_name, service_name)
  60. )
  61. return func(config)
  62. return func_wrapper
  63. def validate_top_level_object(func):
  64. @wraps(func)
  65. def func_wrapper(config):
  66. if not isinstance(config, dict):
  67. raise ConfigurationError(
  68. "Top level object needs to be a dictionary. Check your .yml file that you have defined a service at the top level."
  69. )
  70. return func(config)
  71. return func_wrapper
  72. def validate_extends_file_path(service_name, extends_options, filename):
  73. """
  74. The service to be extended must either be defined in the config key 'file',
  75. or within 'filename'.
  76. """
  77. error_prefix = "Invalid 'extends' configuration for %s:" % service_name
  78. if 'file' not in extends_options and filename is None:
  79. raise ConfigurationError(
  80. "%s you need to specify a 'file', e.g. 'file: something.yml'" % error_prefix
  81. )
  82. def validate_extended_service_exists(extended_service_name, full_extended_config, extended_config_path):
  83. if extended_service_name not in full_extended_config:
  84. msg = (
  85. "Cannot extend service '%s' in %s: Service not found"
  86. ) % (extended_service_name, extended_config_path)
  87. raise ConfigurationError(msg)
  88. def get_unsupported_config_msg(service_name, error_key):
  89. msg = "Unsupported config option for '{}' service: '{}'".format(service_name, error_key)
  90. if error_key in DOCKER_CONFIG_HINTS:
  91. msg += " (did you mean '{}'?)".format(DOCKER_CONFIG_HINTS[error_key])
  92. return msg
  93. def anglicize_validator(validator):
  94. if validator in ["array", "object"]:
  95. return 'an ' + validator
  96. return 'a ' + validator
  97. def process_errors(errors, service_name=None):
  98. """
  99. jsonschema gives us an error tree full of information to explain what has
  100. gone wrong. Process each error and pull out relevant information and re-write
  101. helpful error messages that are relevant.
  102. """
  103. def _parse_key_from_error_msg(error):
  104. return error.message.split("'")[1]
  105. def _clean_error_message(message):
  106. return message.replace("u'", "'")
  107. def _parse_valid_types_from_validator(validator):
  108. """
  109. A validator value can be either an array of valid types or a string of
  110. a valid type. Parse the valid types and prefix with the correct article.
  111. """
  112. if isinstance(validator, list):
  113. if len(validator) >= 2:
  114. first_type = anglicize_validator(validator[0])
  115. last_type = anglicize_validator(validator[-1])
  116. types_from_validator = "{}{}".format(first_type, ", ".join(validator[1:-1]))
  117. msg = "{} or {}".format(
  118. types_from_validator,
  119. last_type
  120. )
  121. else:
  122. msg = "{}".format(anglicize_validator(validator[0]))
  123. else:
  124. msg = "{}".format(anglicize_validator(validator))
  125. return msg
  126. def _parse_oneof_validator(error):
  127. """
  128. oneOf has multiple schemas, so we need to reason about which schema, sub
  129. schema or constraint the validation is failing on.
  130. Inspecting the context value of a ValidationError gives us information about
  131. which sub schema failed and which kind of error it is.
  132. """
  133. constraint = [context for context in error.context if len(context.path) > 0]
  134. if constraint:
  135. valid_types = _parse_valid_types_from_validator(constraint[0].validator_value)
  136. msg = "contains {}, which is an invalid type, it should be {}".format(
  137. constraint[0].instance,
  138. valid_types
  139. )
  140. return msg
  141. uniqueness = [context for context in error.context if context.validator == 'uniqueItems']
  142. if uniqueness:
  143. msg = "contains non unique items, please remove duplicates from {}".format(
  144. uniqueness[0].instance
  145. )
  146. return msg
  147. types = [context.validator_value for context in error.context if context.validator == 'type']
  148. valid_types = _parse_valid_types_from_validator(types)
  149. msg = "contains an invalid type, it should be {}".format(valid_types)
  150. return msg
  151. root_msgs = []
  152. invalid_keys = []
  153. required = []
  154. type_errors = []
  155. other_errors = []
  156. for error in errors:
  157. # handle root level errors
  158. if len(error.path) == 0 and not error.instance.get('name'):
  159. if error.validator == 'type':
  160. msg = "Top level object needs to be a dictionary. Check your .yml file that you have defined a service at the top level."
  161. root_msgs.append(msg)
  162. elif error.validator == 'additionalProperties':
  163. invalid_service_name = _parse_key_from_error_msg(error)
  164. msg = "Invalid service name '{}' - only {} characters are allowed".format(invalid_service_name, VALID_NAME_CHARS)
  165. root_msgs.append(msg)
  166. else:
  167. root_msgs.append(_clean_error_message(error.message))
  168. else:
  169. if not service_name:
  170. # field_schema errors will have service name on the path
  171. service_name = error.path[0]
  172. error.path.popleft()
  173. else:
  174. # service_schema errors have the service name passed in, as that
  175. # is not available on error.path or necessarily error.instance
  176. service_name = service_name
  177. if error.validator == 'additionalProperties':
  178. invalid_config_key = _parse_key_from_error_msg(error)
  179. invalid_keys.append(get_unsupported_config_msg(service_name, invalid_config_key))
  180. elif error.validator == 'anyOf':
  181. if 'image' in error.instance and 'build' in error.instance:
  182. required.append(
  183. "Service '{}' has both an image and build path specified. "
  184. "A service can either be built to image or use an existing "
  185. "image, not both.".format(service_name))
  186. elif 'image' not in error.instance and 'build' not in error.instance:
  187. required.append(
  188. "Service '{}' has neither an image nor a build path "
  189. "specified. Exactly one must be provided.".format(service_name))
  190. elif 'image' in error.instance and 'dockerfile' in error.instance:
  191. required.append(
  192. "Service '{}' has both an image and alternate Dockerfile. "
  193. "A service can either be built to image or use an existing "
  194. "image, not both.".format(service_name))
  195. else:
  196. required.append(_clean_error_message(error.message))
  197. elif error.validator == 'oneOf':
  198. config_key = error.path[0]
  199. msg = _parse_oneof_validator(error)
  200. type_errors.append("Service '{}' configuration key '{}' {}".format(
  201. service_name, config_key, msg)
  202. )
  203. elif error.validator == 'type':
  204. msg = _parse_valid_types_from_validator(error.validator_value)
  205. if len(error.path) > 0:
  206. config_key = " ".join(["'%s'" % k for k in error.path])
  207. type_errors.append(
  208. "Service '{}' configuration key {} contains an invalid "
  209. "type, it should be {}".format(
  210. service_name,
  211. config_key,
  212. msg))
  213. else:
  214. root_msgs.append(
  215. "Service '{}' doesn\'t have any configuration options. "
  216. "All top level keys in your docker-compose.yml must map "
  217. "to a dictionary of configuration options.'".format(service_name))
  218. elif error.validator == 'required':
  219. config_key = error.path[0]
  220. required.append(
  221. "Service '{}' option '{}' is invalid, {}".format(
  222. service_name,
  223. config_key,
  224. _clean_error_message(error.message)))
  225. elif error.validator == 'dependencies':
  226. dependency_key = list(error.validator_value.keys())[0]
  227. required_keys = ",".join(error.validator_value[dependency_key])
  228. required.append("Invalid '{}' configuration for '{}' service: when defining '{}' you must set '{}' as well".format(
  229. dependency_key, service_name, dependency_key, required_keys))
  230. else:
  231. config_key = " ".join(["'%s'" % k for k in error.path])
  232. err_msg = "Service '{}' configuration key {} value {}".format(service_name, config_key, error.message)
  233. other_errors.append(err_msg)
  234. return "\n".join(root_msgs + invalid_keys + required + type_errors + other_errors)
  235. def validate_against_fields_schema(config):
  236. schema_filename = "fields_schema.json"
  237. format_checkers = ["ports", "environment"]
  238. return _validate_against_schema(config, schema_filename, format_checkers)
  239. def validate_against_service_schema(config, service_name):
  240. schema_filename = "service_schema.json"
  241. format_checkers = ["ports"]
  242. return _validate_against_schema(config, schema_filename, format_checkers, service_name)
  243. def _validate_against_schema(config, schema_filename, format_checker=[], service_name=None):
  244. config_source_dir = os.path.dirname(os.path.abspath(__file__))
  245. if sys.platform == "win32":
  246. file_pre_fix = "///"
  247. config_source_dir = config_source_dir.replace('\\', '/')
  248. else:
  249. file_pre_fix = "//"
  250. resolver_full_path = "file:{}{}/".format(file_pre_fix, config_source_dir)
  251. schema_file = os.path.join(config_source_dir, schema_filename)
  252. with open(schema_file, "r") as schema_fh:
  253. schema = json.load(schema_fh)
  254. resolver = RefResolver(resolver_full_path, schema)
  255. validation_output = Draft4Validator(schema, resolver=resolver, format_checker=FormatChecker(format_checker))
  256. errors = [error for error in sorted(validation_output.iter_errors(config), key=str)]
  257. if errors:
  258. error_msg = process_errors(errors, service_name)
  259. raise ConfigurationError("Validation failed, reason(s):\n{}".format(error_msg))