validation.py 13 KB

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