1
0

validation.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269
  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 process_errors(errors, service_name=None):
  78. """
  79. jsonschema gives us an error tree full of information to explain what has
  80. gone wrong. Process each error and pull out relevant information and re-write
  81. helpful error messages that are relevant.
  82. """
  83. def _parse_key_from_error_msg(error):
  84. return error.message.split("'")[1]
  85. def _clean_error_message(message):
  86. return message.replace("u'", "'")
  87. def _parse_valid_types_from_schema(schema):
  88. """
  89. Our defined types using $ref in the schema require some extra parsing
  90. retrieve a helpful type for error message display.
  91. """
  92. if '$ref' in schema:
  93. return schema['$ref'].replace("#/definitions/", "").replace("_", " ")
  94. else:
  95. return str(schema['type'])
  96. def _parse_valid_types_from_validator(validator):
  97. """
  98. A validator value can be either an array of valid types or a string of
  99. a valid type. Parse the valid types and prefix with the correct article.
  100. """
  101. pre_msg_type_prefix = "a"
  102. last_msg_type_prefix = "a"
  103. types_requiring_an = ["array", "object"]
  104. if isinstance(validator, list):
  105. last_type = validator.pop()
  106. types_from_validator = ", ".join(validator)
  107. if validator[0] in types_requiring_an:
  108. pre_msg_type_prefix = "an"
  109. if last_type in types_requiring_an:
  110. last_msg_type_prefix = "an"
  111. msg = "{} {} or {} {}".format(
  112. pre_msg_type_prefix,
  113. types_from_validator,
  114. last_msg_type_prefix,
  115. last_type
  116. )
  117. else:
  118. if validator in types_requiring_an:
  119. pre_msg_type_prefix = "an"
  120. msg = "{} {}".format(pre_msg_type_prefix, validator)
  121. return msg
  122. root_msgs = []
  123. invalid_keys = []
  124. required = []
  125. type_errors = []
  126. other_errors = []
  127. for error in errors:
  128. # handle root level errors
  129. if len(error.path) == 0 and not error.instance.get('name'):
  130. if error.validator == 'type':
  131. msg = "Top level object needs to be a dictionary. Check your .yml file that you have defined a service at the top level."
  132. root_msgs.append(msg)
  133. elif error.validator == 'additionalProperties':
  134. invalid_service_name = _parse_key_from_error_msg(error)
  135. msg = "Invalid service name '{}' - only {} characters are allowed".format(invalid_service_name, VALID_NAME_CHARS)
  136. root_msgs.append(msg)
  137. else:
  138. root_msgs.append(_clean_error_message(error.message))
  139. else:
  140. if not service_name:
  141. # field_schema errors will have service name on the path
  142. service_name = error.path[0]
  143. error.path.popleft()
  144. else:
  145. # service_schema errors have the service name passed in, as that
  146. # is not available on error.path or necessarily error.instance
  147. service_name = service_name
  148. if error.validator == 'additionalProperties':
  149. invalid_config_key = _parse_key_from_error_msg(error)
  150. invalid_keys.append(get_unsupported_config_msg(service_name, invalid_config_key))
  151. elif error.validator == 'anyOf':
  152. if 'image' in error.instance and 'build' in error.instance:
  153. required.append(
  154. "Service '{}' has both an image and build path specified. "
  155. "A service can either be built to image or use an existing "
  156. "image, not both.".format(service_name))
  157. elif 'image' not in error.instance and 'build' not in error.instance:
  158. required.append(
  159. "Service '{}' has neither an image nor a build path "
  160. "specified. Exactly one must be provided.".format(service_name))
  161. elif 'image' in error.instance and 'dockerfile' in error.instance:
  162. required.append(
  163. "Service '{}' has both an image and alternate Dockerfile. "
  164. "A service can either be built to image or use an existing "
  165. "image, not both.".format(service_name))
  166. else:
  167. required.append(_clean_error_message(error.message))
  168. elif error.validator == 'oneOf':
  169. config_key = error.path[0]
  170. valid_types = [_parse_valid_types_from_schema(schema) for schema in error.schema['oneOf']]
  171. valid_type_msg = " or ".join(valid_types)
  172. type_errors.append("Service '{}' configuration key '{}' contains an invalid type, valid types are {}".format(
  173. service_name, config_key, valid_type_msg)
  174. )
  175. elif error.validator == 'type':
  176. msg = _parse_valid_types_from_validator(error.validator_value)
  177. if len(error.path) > 0:
  178. config_key = " ".join(["'%s'" % k for k in error.path])
  179. type_errors.append(
  180. "Service '{}' configuration key {} contains an invalid "
  181. "type, it should be {}".format(
  182. service_name,
  183. config_key,
  184. msg))
  185. else:
  186. root_msgs.append(
  187. "Service '{}' doesn\'t have any configuration options. "
  188. "All top level keys in your docker-compose.yml must map "
  189. "to a dictionary of configuration options.'".format(service_name))
  190. elif error.validator == 'required':
  191. config_key = error.path[0]
  192. required.append(
  193. "Service '{}' option '{}' is invalid, {}".format(
  194. service_name,
  195. config_key,
  196. _clean_error_message(error.message)))
  197. elif error.validator == 'dependencies':
  198. dependency_key = list(error.validator_value.keys())[0]
  199. required_keys = ",".join(error.validator_value[dependency_key])
  200. required.append("Invalid '{}' configuration for '{}' service: when defining '{}' you must set '{}' as well".format(
  201. dependency_key, service_name, dependency_key, required_keys))
  202. else:
  203. config_key = " ".join(["'%s'" % k for k in error.path])
  204. err_msg = "Service '{}' configuration key {} value {}".format(service_name, config_key, error.message)
  205. other_errors.append(err_msg)
  206. return "\n".join(root_msgs + invalid_keys + required + type_errors + other_errors)
  207. def validate_against_fields_schema(config):
  208. schema_filename = "fields_schema.json"
  209. return _validate_against_schema(config, schema_filename)
  210. def validate_against_service_schema(config, service_name):
  211. schema_filename = "service_schema.json"
  212. return _validate_against_schema(config, schema_filename, service_name)
  213. def _validate_against_schema(config, schema_filename, service_name=None):
  214. config_source_dir = os.path.dirname(os.path.abspath(__file__))
  215. schema_file = os.path.join(config_source_dir, schema_filename)
  216. with open(schema_file, "r") as schema_fh:
  217. schema = json.load(schema_fh)
  218. resolver = RefResolver('file://' + config_source_dir + '/', schema)
  219. validation_output = Draft4Validator(schema, resolver=resolver, format_checker=FormatChecker(["ports"]))
  220. errors = [error for error in sorted(validation_output.iter_errors(config), key=str)]
  221. if errors:
  222. error_msg = process_errors(errors, service_name)
  223. raise ConfigurationError("Validation failed, reason(s):\n{}".format(error_msg))