validation.py 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  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):
  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. root_msgs = []
  97. invalid_keys = []
  98. required = []
  99. type_errors = []
  100. other_errors = []
  101. for error in errors:
  102. # handle root level errors
  103. if len(error.path) == 0:
  104. if error.validator == 'type':
  105. msg = "Top level object needs to be a dictionary. Check your .yml file that you have defined a service at the top level."
  106. root_msgs.append(msg)
  107. elif error.validator == 'additionalProperties':
  108. invalid_service_name = _parse_key_from_error_msg(error)
  109. msg = "Invalid service name '{}' - only {} characters are allowed".format(invalid_service_name, VALID_NAME_CHARS)
  110. root_msgs.append(msg)
  111. else:
  112. root_msgs.append(_clean_error_message(error.message))
  113. else:
  114. # handle service level errors
  115. service_name = error.path[0]
  116. # pop the service name off our path
  117. error.path.popleft()
  118. if error.validator == 'additionalProperties':
  119. invalid_config_key = _parse_key_from_error_msg(error)
  120. invalid_keys.append(get_unsupported_config_msg(service_name, invalid_config_key))
  121. elif error.validator == 'anyOf':
  122. if 'image' in error.instance and 'build' in error.instance:
  123. required.append(
  124. "Service '{}' has both an image and build path specified. "
  125. "A service can either be built to image or use an existing "
  126. "image, not both.".format(service_name))
  127. elif 'image' not in error.instance and 'build' not in error.instance:
  128. required.append(
  129. "Service '{}' has neither an image nor a build path "
  130. "specified. Exactly one must be provided.".format(service_name))
  131. elif 'image' in error.instance and 'dockerfile' in error.instance:
  132. required.append(
  133. "Service '{}' has both an image and alternate Dockerfile. "
  134. "A service can either be built to image or use an existing "
  135. "image, not both.".format(service_name))
  136. else:
  137. required.append(_clean_error_message(error.message))
  138. elif error.validator == 'oneOf':
  139. config_key = error.path[0]
  140. valid_types = [_parse_valid_types_from_schema(schema) for schema in error.schema['oneOf']]
  141. valid_type_msg = " or ".join(valid_types)
  142. type_errors.append("Service '{}' configuration key '{}' contains an invalid type, valid types are {}".format(
  143. service_name, config_key, valid_type_msg)
  144. )
  145. elif error.validator == 'type':
  146. msg = "a"
  147. if error.validator_value == "array":
  148. msg = "an"
  149. if len(error.path) > 0:
  150. config_key = " ".join(["'%s'" % k for k in error.path])
  151. type_errors.append(
  152. "Service '{}' configuration key {} contains an invalid "
  153. "type, it should be {} {}".format(
  154. service_name,
  155. config_key,
  156. msg,
  157. error.validator_value))
  158. else:
  159. root_msgs.append(
  160. "Service '{}' doesn\'t have any configuration options. "
  161. "All top level keys in your docker-compose.yml must map "
  162. "to a dictionary of configuration options.'".format(service_name))
  163. elif error.validator == 'required':
  164. config_key = error.path[0]
  165. required.append(
  166. "Service '{}' option '{}' is invalid, {}".format(
  167. service_name,
  168. config_key,
  169. _clean_error_message(error.message)))
  170. elif error.validator == 'dependencies':
  171. dependency_key = list(error.validator_value.keys())[0]
  172. required_keys = ",".join(error.validator_value[dependency_key])
  173. required.append("Invalid '{}' configuration for '{}' service: when defining '{}' you must set '{}' as well".format(
  174. dependency_key, service_name, dependency_key, required_keys))
  175. else:
  176. config_key = " ".join(["'%s'" % k for k in error.path])
  177. err_msg = "Service '{}' configuration key {} value {}".format(service_name, config_key, error.message)
  178. other_errors.append(err_msg)
  179. return "\n".join(root_msgs + invalid_keys + required + type_errors + other_errors)
  180. def validate_against_fields_schema(config):
  181. schema_filename = "fields_schema.json"
  182. return _validate_against_schema(config, schema_filename)
  183. def validate_against_service_schema(config):
  184. schema_filename = "service_schema.json"
  185. return _validate_against_schema(config, schema_filename)
  186. def _validate_against_schema(config, schema_filename):
  187. config_source_dir = os.path.dirname(os.path.abspath(__file__))
  188. schema_file = os.path.join(config_source_dir, schema_filename)
  189. with open(schema_file, "r") as schema_fh:
  190. schema = json.load(schema_fh)
  191. resolver = RefResolver('file://' + config_source_dir + '/', schema)
  192. validation_output = Draft4Validator(schema, resolver=resolver, format_checker=FormatChecker(["ports"]))
  193. errors = [error for error in sorted(validation_output.iter_errors(config), key=str)]
  194. if errors:
  195. error_msg = process_errors(errors)
  196. raise ConfigurationError("Validation failed, reason(s):\n{}".format(error_msg))