validation.py 11 KB

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