validation.py 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225
  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 ValidationError
  8. from .errors import ConfigurationError
  9. DOCKER_CONFIG_HINTS = {
  10. 'cpu_share': 'cpu_shares',
  11. 'add_host': 'extra_hosts',
  12. 'hosts': 'extra_hosts',
  13. 'extra_host': 'extra_hosts',
  14. 'device': 'devices',
  15. 'link': 'links',
  16. 'memory_swap': 'memswap_limit',
  17. 'port': 'ports',
  18. 'privilege': 'privileged',
  19. 'priviliged': 'privileged',
  20. 'privilige': 'privileged',
  21. 'volume': 'volumes',
  22. 'workdir': 'working_dir',
  23. }
  24. VALID_NAME_CHARS = '[a-zA-Z0-9\._\-]'
  25. @FormatChecker.cls_checks(
  26. format="ports",
  27. raises=ValidationError(
  28. "Invalid port formatting, it should be "
  29. "'[[remote_ip:]remote_port:]port[/protocol]'"))
  30. def format_ports(instance):
  31. try:
  32. split_port(instance)
  33. except ValueError:
  34. return False
  35. return True
  36. def validate_service_names(func):
  37. @wraps(func)
  38. def func_wrapper(config):
  39. for service_name in config.keys():
  40. if type(service_name) is int:
  41. raise ConfigurationError(
  42. "Service name: {} needs to be a string, eg '{}'".format(service_name, service_name)
  43. )
  44. return func(config)
  45. return func_wrapper
  46. def validate_top_level_object(func):
  47. @wraps(func)
  48. def func_wrapper(config):
  49. if not isinstance(config, dict):
  50. raise ConfigurationError(
  51. "Top level object needs to be a dictionary. Check your .yml file that you have defined a service at the top level."
  52. )
  53. return func(config)
  54. return func_wrapper
  55. def validate_extends_file_path(service_name, extends_options, filename):
  56. """
  57. The service to be extended must either be defined in the config key 'file',
  58. or within 'filename'.
  59. """
  60. error_prefix = "Invalid 'extends' configuration for %s:" % service_name
  61. if 'file' not in extends_options and filename is None:
  62. raise ConfigurationError(
  63. "%s you need to specify a 'file', e.g. 'file: something.yml'" % error_prefix
  64. )
  65. def validate_extended_service_exists(extended_service_name, full_extended_config, extended_config_path):
  66. if extended_service_name not in full_extended_config:
  67. msg = (
  68. "Cannot extend service '%s' in %s: Service not found"
  69. ) % (extended_service_name, extended_config_path)
  70. raise ConfigurationError(msg)
  71. def get_unsupported_config_msg(service_name, error_key):
  72. msg = "Unsupported config option for '{}' service: '{}'".format(service_name, error_key)
  73. if error_key in DOCKER_CONFIG_HINTS:
  74. msg += " (did you mean '{}'?)".format(DOCKER_CONFIG_HINTS[error_key])
  75. return msg
  76. def process_errors(errors):
  77. """
  78. jsonschema gives us an error tree full of information to explain what has
  79. gone wrong. Process each error and pull out relevant information and re-write
  80. helpful error messages that are relevant.
  81. """
  82. def _parse_key_from_error_msg(error):
  83. return error.message.split("'")[1]
  84. def _clean_error_message(message):
  85. return message.replace("u'", "'")
  86. def _parse_valid_types_from_schema(schema):
  87. """
  88. Our defined types using $ref in the schema require some extra parsing
  89. retrieve a helpful type for error message display.
  90. """
  91. if '$ref' in schema:
  92. return schema['$ref'].replace("#/definitions/", "").replace("_", " ")
  93. else:
  94. return str(schema['type'])
  95. root_msgs = []
  96. invalid_keys = []
  97. required = []
  98. type_errors = []
  99. other_errors = []
  100. for error in errors:
  101. # handle root level errors
  102. if len(error.path) == 0:
  103. if error.validator == 'type':
  104. msg = "Top level object needs to be a dictionary. Check your .yml file that you have defined a service at the top level."
  105. root_msgs.append(msg)
  106. elif error.validator == 'additionalProperties':
  107. invalid_service_name = _parse_key_from_error_msg(error)
  108. msg = "Invalid service name '{}' - only {} characters are allowed".format(invalid_service_name, VALID_NAME_CHARS)
  109. root_msgs.append(msg)
  110. else:
  111. root_msgs.append(_clean_error_message(error.message))
  112. else:
  113. # handle service level errors
  114. service_name = error.path[0]
  115. # pop the service name off our path
  116. error.path.popleft()
  117. if error.validator == 'additionalProperties':
  118. invalid_config_key = _parse_key_from_error_msg(error)
  119. invalid_keys.append(get_unsupported_config_msg(service_name, invalid_config_key))
  120. elif error.validator == 'anyOf':
  121. if 'image' in error.instance and 'build' in error.instance:
  122. required.append(
  123. "Service '{}' has both an image and build path specified. "
  124. "A service can either be built to image or use an existing "
  125. "image, not both.".format(service_name))
  126. elif 'image' not in error.instance and 'build' not in error.instance:
  127. required.append(
  128. "Service '{}' has neither an image nor a build path "
  129. "specified. Exactly one must be provided.".format(service_name))
  130. elif 'image' in error.instance and 'dockerfile' in error.instance:
  131. required.append(
  132. "Service '{}' has both an image and alternate Dockerfile. "
  133. "A service can either be built to image or use an existing "
  134. "image, not both.".format(service_name))
  135. else:
  136. required.append(_clean_error_message(error.message))
  137. elif error.validator == 'oneOf':
  138. config_key = error.path[0]
  139. valid_types = [_parse_valid_types_from_schema(schema) for schema in error.schema['oneOf']]
  140. valid_type_msg = " or ".join(valid_types)
  141. type_errors.append("Service '{}' configuration key '{}' contains an invalid type, valid types are {}".format(
  142. service_name, config_key, valid_type_msg)
  143. )
  144. elif error.validator == 'type':
  145. msg = "a"
  146. if error.validator_value == "array":
  147. msg = "an"
  148. if len(error.path) > 0:
  149. config_key = " ".join(["'%s'" % k for k in error.path])
  150. type_errors.append(
  151. "Service '{}' configuration key {} contains an invalid "
  152. "type, it should be {} {}".format(
  153. service_name,
  154. config_key,
  155. msg,
  156. error.validator_value))
  157. else:
  158. root_msgs.append(
  159. "Service '{}' doesn\'t have any configuration options. "
  160. "All top level keys in your docker-compose.yml must map "
  161. "to a dictionary of configuration options.'".format(service_name))
  162. elif error.validator == 'required':
  163. config_key = error.path[0]
  164. required.append(
  165. "Service '{}' option '{}' is invalid, {}".format(
  166. service_name,
  167. config_key,
  168. _clean_error_message(error.message)))
  169. elif error.validator == 'dependencies':
  170. dependency_key = list(error.validator_value.keys())[0]
  171. required_keys = ",".join(error.validator_value[dependency_key])
  172. required.append("Invalid '{}' configuration for '{}' service: when defining '{}' you must set '{}' as well".format(
  173. dependency_key, service_name, dependency_key, required_keys))
  174. else:
  175. config_key = " ".join(["'%s'" % k for k in error.path])
  176. err_msg = "Service '{}' configuration key {} value {}".format(service_name, config_key, error.message)
  177. other_errors.append(err_msg)
  178. return "\n".join(root_msgs + invalid_keys + required + type_errors + other_errors)
  179. def validate_against_schema(config):
  180. config_source_dir = os.path.dirname(os.path.abspath(__file__))
  181. schema_file = os.path.join(config_source_dir, "schema.json")
  182. with open(schema_file, "r") as schema_fh:
  183. schema = json.load(schema_fh)
  184. validation_output = Draft4Validator(schema, format_checker=FormatChecker(["ports"]))
  185. errors = [error for error in sorted(validation_output.iter_errors(config), key=str)]
  186. if errors:
  187. error_msg = process_errors(errors)
  188. raise ConfigurationError("Validation failed, reason(s):\n{}".format(error_msg))