validation.py 13 KB

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