validation.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323
  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 validate_extended_service_exists(extended_service_name, full_extended_config, extended_config_path):
  79. if extended_service_name not in full_extended_config:
  80. msg = (
  81. "Cannot extend service '%s' in %s: Service not found"
  82. ) % (extended_service_name, extended_config_path)
  83. raise ConfigurationError(msg)
  84. def get_unsupported_config_msg(service_name, error_key):
  85. msg = "Unsupported config option for '{}' service: '{}'".format(service_name, error_key)
  86. if error_key in DOCKER_CONFIG_HINTS:
  87. msg += " (did you mean '{}'?)".format(DOCKER_CONFIG_HINTS[error_key])
  88. return msg
  89. def anglicize_validator(validator):
  90. if validator in ["array", "object"]:
  91. return 'an ' + validator
  92. return 'a ' + validator
  93. def process_errors(errors, service_name=None):
  94. """
  95. jsonschema gives us an error tree full of information to explain what has
  96. gone wrong. Process each error and pull out relevant information and re-write
  97. helpful error messages that are relevant.
  98. """
  99. def _parse_key_from_error_msg(error):
  100. return error.message.split("'")[1]
  101. def _clean_error_message(message):
  102. return message.replace("u'", "'")
  103. def _parse_valid_types_from_validator(validator):
  104. """
  105. A validator value can be either an array of valid types or a string of
  106. a valid type. Parse the valid types and prefix with the correct article.
  107. """
  108. if isinstance(validator, list):
  109. if len(validator) >= 2:
  110. first_type = anglicize_validator(validator[0])
  111. last_type = anglicize_validator(validator[-1])
  112. types_from_validator = ", ".join([first_type] + validator[1:-1])
  113. msg = "{} or {}".format(
  114. types_from_validator,
  115. last_type
  116. )
  117. else:
  118. msg = "{}".format(anglicize_validator(validator[0]))
  119. else:
  120. msg = "{}".format(anglicize_validator(validator))
  121. return msg
  122. def _parse_oneof_validator(error):
  123. """
  124. oneOf has multiple schemas, so we need to reason about which schema, sub
  125. schema or constraint the validation is failing on.
  126. Inspecting the context value of a ValidationError gives us information about
  127. which sub schema failed and which kind of error it is.
  128. """
  129. required = [context for context in error.context if context.validator == 'required']
  130. if required:
  131. return required[0].message
  132. additionalProperties = [context for context in error.context if context.validator == 'additionalProperties']
  133. if additionalProperties:
  134. invalid_config_key = _parse_key_from_error_msg(additionalProperties[0])
  135. return "contains unsupported option: '{}'".format(invalid_config_key)
  136. constraint = [context for context in error.context if len(context.path) > 0]
  137. if constraint:
  138. valid_types = _parse_valid_types_from_validator(constraint[0].validator_value)
  139. invalid_config_key = "".join(
  140. "'{}' ".format(fragment) for fragment in constraint[0].path
  141. if isinstance(fragment, six.string_types)
  142. )
  143. msg = "{}contains {}, which is an invalid type, it should be {}".format(
  144. invalid_config_key,
  145. constraint[0].instance,
  146. valid_types
  147. )
  148. return msg
  149. uniqueness = [context for context in error.context if context.validator == 'uniqueItems']
  150. if uniqueness:
  151. msg = "contains non unique items, please remove duplicates from {}".format(
  152. uniqueness[0].instance
  153. )
  154. return msg
  155. types = [context.validator_value for context in error.context if context.validator == 'type']
  156. valid_types = _parse_valid_types_from_validator(types)
  157. msg = "contains an invalid type, it should be {}".format(valid_types)
  158. return msg
  159. root_msgs = []
  160. invalid_keys = []
  161. required = []
  162. type_errors = []
  163. other_errors = []
  164. for error in errors:
  165. # handle root level errors
  166. if len(error.path) == 0 and not error.instance.get('name'):
  167. if error.validator == 'type':
  168. msg = "Top level object needs to be a dictionary. Check your .yml file that you have defined a service at the top level."
  169. root_msgs.append(msg)
  170. elif error.validator == 'additionalProperties':
  171. invalid_service_name = _parse_key_from_error_msg(error)
  172. msg = "Invalid service name '{}' - only {} characters are allowed".format(invalid_service_name, VALID_NAME_CHARS)
  173. root_msgs.append(msg)
  174. else:
  175. root_msgs.append(_clean_error_message(error.message))
  176. else:
  177. if not service_name:
  178. # field_schema errors will have service name on the path
  179. service_name = error.path[0]
  180. error.path.popleft()
  181. else:
  182. # service_schema errors have the service name passed in, as that
  183. # is not available on error.path or necessarily error.instance
  184. service_name = service_name
  185. if error.validator == 'additionalProperties':
  186. invalid_config_key = _parse_key_from_error_msg(error)
  187. invalid_keys.append(get_unsupported_config_msg(service_name, invalid_config_key))
  188. elif error.validator == 'anyOf':
  189. if 'image' in error.instance and 'build' in error.instance:
  190. required.append(
  191. "Service '{}' has both an image and build path specified. "
  192. "A service can either be built to image or use an existing "
  193. "image, not both.".format(service_name))
  194. elif 'image' not in error.instance and 'build' not in error.instance:
  195. required.append(
  196. "Service '{}' has neither an image nor a build path "
  197. "specified. Exactly one must be provided.".format(service_name))
  198. elif 'image' in error.instance and 'dockerfile' in error.instance:
  199. required.append(
  200. "Service '{}' has both an image and alternate Dockerfile. "
  201. "A service can either be built to image or use an existing "
  202. "image, not both.".format(service_name))
  203. else:
  204. required.append(_clean_error_message(error.message))
  205. elif error.validator == 'oneOf':
  206. config_key = error.path[0]
  207. msg = _parse_oneof_validator(error)
  208. type_errors.append("Service '{}' configuration key '{}' {}".format(
  209. service_name, config_key, msg)
  210. )
  211. elif error.validator == 'type':
  212. msg = _parse_valid_types_from_validator(error.validator_value)
  213. if len(error.path) > 0:
  214. config_key = " ".join(["'%s'" % k for k in error.path])
  215. type_errors.append(
  216. "Service '{}' configuration key {} contains an invalid "
  217. "type, it should be {}".format(
  218. service_name,
  219. config_key,
  220. msg))
  221. else:
  222. root_msgs.append(
  223. "Service '{}' doesn\'t have any configuration options. "
  224. "All top level keys in your docker-compose.yml must map "
  225. "to a dictionary of configuration options.'".format(service_name))
  226. elif error.validator == 'required':
  227. config_key = error.path[0]
  228. required.append(
  229. "Service '{}' option '{}' is invalid, {}".format(
  230. service_name,
  231. config_key,
  232. _clean_error_message(error.message)))
  233. elif error.validator == 'dependencies':
  234. dependency_key = list(error.validator_value.keys())[0]
  235. required_keys = ",".join(error.validator_value[dependency_key])
  236. required.append("Invalid '{}' configuration for '{}' service: when defining '{}' you must set '{}' as well".format(
  237. dependency_key, service_name, dependency_key, required_keys))
  238. else:
  239. config_key = " ".join(["'%s'" % k for k in error.path])
  240. err_msg = "Service '{}' configuration key {} value {}".format(service_name, config_key, error.message)
  241. other_errors.append(err_msg)
  242. return "\n".join(root_msgs + invalid_keys + required + type_errors + other_errors)
  243. def validate_against_fields_schema(config):
  244. schema_filename = "fields_schema.json"
  245. format_checkers = ["ports", "environment"]
  246. return _validate_against_schema(config, schema_filename, format_checkers)
  247. def validate_against_service_schema(config, service_name):
  248. schema_filename = "service_schema.json"
  249. format_checkers = ["ports"]
  250. return _validate_against_schema(config, schema_filename, format_checkers, service_name)
  251. def _validate_against_schema(config, schema_filename, format_checker=[], service_name=None):
  252. config_source_dir = os.path.dirname(os.path.abspath(__file__))
  253. if sys.platform == "win32":
  254. file_pre_fix = "///"
  255. config_source_dir = config_source_dir.replace('\\', '/')
  256. else:
  257. file_pre_fix = "//"
  258. resolver_full_path = "file:{}{}/".format(file_pre_fix, config_source_dir)
  259. schema_file = os.path.join(config_source_dir, schema_filename)
  260. with open(schema_file, "r") as schema_fh:
  261. schema = json.load(schema_fh)
  262. resolver = RefResolver(resolver_full_path, schema)
  263. validation_output = Draft4Validator(schema, resolver=resolver, format_checker=FormatChecker(format_checker))
  264. errors = [error for error in sorted(validation_output.iter_errors(config), key=str)]
  265. if errors:
  266. error_msg = process_errors(errors, service_name)
  267. raise ConfigurationError("Validation failed, reason(s):\n{}".format(error_msg))