validation.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  1. import json
  2. import logging
  3. import os
  4. import sys
  5. import six
  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. "There is a boolean value in the 'environment' key.\n"
  49. "Environment variables can only be strings.\n"
  50. "Please add quotes to any boolean values to make them string "
  51. "(eg, 'True', 'yes', 'N').\n"
  52. "This warning will become an error in a future release. \r\n"
  53. )
  54. return True
  55. def validate_service_names(config):
  56. for service_name in config.keys():
  57. if not isinstance(service_name, six.string_types):
  58. raise ConfigurationError(
  59. "Service name: {} needs to be a string, eg '{}'".format(
  60. service_name,
  61. service_name))
  62. def validate_top_level_object(config):
  63. if not isinstance(config, dict):
  64. raise ConfigurationError(
  65. "Top level object needs to be a dictionary. Check your .yml file "
  66. "that you have defined a service at the top level.")
  67. validate_service_names(config)
  68. def validate_extends_file_path(service_name, extends_options, filename):
  69. """
  70. The service to be extended must either be defined in the config key 'file',
  71. or within 'filename'.
  72. """
  73. error_prefix = "Invalid 'extends' configuration for %s:" % service_name
  74. if 'file' not in extends_options and filename is None:
  75. raise ConfigurationError(
  76. "%s you need to specify a 'file', e.g. 'file: something.yml'" % error_prefix
  77. )
  78. def get_unsupported_config_msg(service_name, error_key):
  79. msg = "Unsupported config option for '{}' service: '{}'".format(service_name, error_key)
  80. if error_key in DOCKER_CONFIG_HINTS:
  81. msg += " (did you mean '{}'?)".format(DOCKER_CONFIG_HINTS[error_key])
  82. return msg
  83. def anglicize_validator(validator):
  84. if validator in ["array", "object"]:
  85. return 'an ' + validator
  86. return 'a ' + validator
  87. def handle_error_for_schema_with_id(error, service_name):
  88. schema_id = error.schema['id']
  89. if schema_id == 'fields_schema.json' and error.validator == 'additionalProperties':
  90. return "Invalid service name '{}' - only {} characters are allowed".format(
  91. # The service_name is the key to the json object
  92. list(error.instance)[0],
  93. VALID_NAME_CHARS)
  94. if schema_id == '#/definitions/constraints':
  95. if 'image' in error.instance and 'build' in error.instance:
  96. return (
  97. "Service '{}' has both an image and build path specified. "
  98. "A service can either be built to image or use an existing "
  99. "image, not both.".format(service_name))
  100. if 'image' not in error.instance and 'build' not in error.instance:
  101. return (
  102. "Service '{}' has neither an image nor a build path "
  103. "specified. Exactly one must be provided.".format(service_name))
  104. if 'image' in error.instance and 'dockerfile' in error.instance:
  105. return (
  106. "Service '{}' has both an image and alternate Dockerfile. "
  107. "A service can either be built to image or use an existing "
  108. "image, not both.".format(service_name))
  109. if schema_id == '#/definitions/service':
  110. if error.validator == 'additionalProperties':
  111. invalid_config_key = parse_key_from_error_msg(error)
  112. return get_unsupported_config_msg(service_name, invalid_config_key)
  113. def handle_generic_service_error(error, service_name):
  114. config_key = " ".join("'%s'" % k for k in error.path)
  115. msg_format = None
  116. error_msg = error.message
  117. if error.validator == 'oneOf':
  118. msg_format = "Service '{}' configuration key {} {}"
  119. error_msg = _parse_oneof_validator(error)
  120. elif error.validator == 'type':
  121. msg_format = ("Service '{}' configuration key {} contains an invalid "
  122. "type, it should be {}")
  123. error_msg = _parse_valid_types_from_validator(error.validator_value)
  124. # TODO: no test case for this branch, there are no config options
  125. # which exercise this branch
  126. elif error.validator == 'required':
  127. msg_format = "Service '{}' configuration key '{}' is invalid, {}"
  128. elif error.validator == 'dependencies':
  129. msg_format = "Service '{}' configuration key '{}' is invalid: {}"
  130. config_key = list(error.validator_value.keys())[0]
  131. required_keys = ",".join(error.validator_value[config_key])
  132. error_msg = "when defining '{}' you must set '{}' as well".format(
  133. config_key,
  134. required_keys)
  135. elif error.path:
  136. msg_format = "Service '{}' configuration key {} value {}"
  137. if msg_format:
  138. return msg_format.format(service_name, config_key, error_msg)
  139. return error.message
  140. def parse_key_from_error_msg(error):
  141. return error.message.split("'")[1]
  142. def _parse_valid_types_from_validator(validator):
  143. """A validator value can be either an array of valid types or a string of
  144. a valid type. Parse the valid types and prefix with the correct article.
  145. """
  146. if not isinstance(validator, list):
  147. return anglicize_validator(validator)
  148. if len(validator) == 1:
  149. return anglicize_validator(validator[0])
  150. return "{}, or {}".format(
  151. ", ".join([anglicize_validator(validator[0])] + validator[1:-1]),
  152. anglicize_validator(validator[-1]))
  153. def _parse_oneof_validator(error):
  154. """oneOf has multiple schemas, so we need to reason about which schema, sub
  155. schema or constraint the validation is failing on.
  156. Inspecting the context value of a ValidationError gives us information about
  157. which sub schema failed and which kind of error it is.
  158. """
  159. types = []
  160. for context in error.context:
  161. if context.validator == 'required':
  162. return context.message
  163. if context.validator == 'additionalProperties':
  164. invalid_config_key = parse_key_from_error_msg(context)
  165. return "contains unsupported option: '{}'".format(invalid_config_key)
  166. if context.path:
  167. invalid_config_key = " ".join(
  168. "'{}' ".format(fragment) for fragment in context.path
  169. if isinstance(fragment, six.string_types)
  170. )
  171. return "{}contains {}, which is an invalid type, it should be {}".format(
  172. invalid_config_key,
  173. context.instance,
  174. _parse_valid_types_from_validator(context.validator_value))
  175. if context.validator == 'uniqueItems':
  176. return "contains non unique items, please remove duplicates from {}".format(
  177. context.instance)
  178. if context.validator == 'type':
  179. types.append(context.validator_value)
  180. valid_types = _parse_valid_types_from_validator(types)
  181. return "contains an invalid type, it should be {}".format(valid_types)
  182. def process_errors(errors, service_name=None):
  183. """jsonschema gives us an error tree full of information to explain what has
  184. gone wrong. Process each error and pull out relevant information and re-write
  185. helpful error messages that are relevant.
  186. """
  187. def format_error_message(error, service_name):
  188. if not service_name and error.path:
  189. # field_schema errors will have service name on the path
  190. service_name = error.path.popleft()
  191. if 'id' in error.schema:
  192. error_msg = handle_error_for_schema_with_id(error, service_name)
  193. if error_msg:
  194. return error_msg
  195. return handle_generic_service_error(error, service_name)
  196. return '\n'.join(format_error_message(error, service_name) for error in errors)
  197. def validate_against_fields_schema(config):
  198. return _validate_against_schema(
  199. config,
  200. "fields_schema.json",
  201. ["ports", "environment"])
  202. def validate_against_service_schema(config, service_name):
  203. return _validate_against_schema(
  204. config,
  205. "service_schema.json",
  206. ["ports"],
  207. service_name)
  208. def _validate_against_schema(
  209. config,
  210. schema_filename,
  211. format_checker=(),
  212. service_name=None):
  213. config_source_dir = os.path.dirname(os.path.abspath(__file__))
  214. if sys.platform == "win32":
  215. file_pre_fix = "///"
  216. config_source_dir = config_source_dir.replace('\\', '/')
  217. else:
  218. file_pre_fix = "//"
  219. resolver_full_path = "file:{}{}/".format(file_pre_fix, config_source_dir)
  220. schema_file = os.path.join(config_source_dir, schema_filename)
  221. with open(schema_file, "r") as schema_fh:
  222. schema = json.load(schema_fh)
  223. resolver = RefResolver(resolver_full_path, schema)
  224. validation_output = Draft4Validator(
  225. schema,
  226. resolver=resolver,
  227. format_checker=FormatChecker(format_checker))
  228. errors = [error for error in sorted(validation_output.iter_errors(config), key=str)]
  229. if errors:
  230. error_msg = process_errors(errors, service_name)
  231. raise ConfigurationError("Validation failed, reason(s):\n{}".format(error_msg))