validation.py 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217
  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 get_unsupported_config_msg(service_name, error_key):
  66. msg = "Unsupported config option for '{}' service: '{}'".format(service_name, error_key)
  67. if error_key in DOCKER_CONFIG_HINTS:
  68. msg += " (did you mean '{}'?)".format(DOCKER_CONFIG_HINTS[error_key])
  69. return msg
  70. def process_errors(errors):
  71. """
  72. jsonschema gives us an error tree full of information to explain what has
  73. gone wrong. Process each error and pull out relevant information and re-write
  74. helpful error messages that are relevant.
  75. """
  76. def _parse_key_from_error_msg(error):
  77. return error.message.split("'")[1]
  78. def _clean_error_message(message):
  79. return message.replace("u'", "'")
  80. def _parse_valid_types_from_schema(schema):
  81. """
  82. Our defined types using $ref in the schema require some extra parsing
  83. retrieve a helpful type for error message display.
  84. """
  85. if '$ref' in schema:
  86. return schema['$ref'].replace("#/definitions/", "").replace("_", " ")
  87. else:
  88. return str(schema['type'])
  89. root_msgs = []
  90. invalid_keys = []
  91. required = []
  92. type_errors = []
  93. other_errors = []
  94. for error in errors:
  95. # handle root level errors
  96. if len(error.path) == 0:
  97. if error.validator == 'type':
  98. msg = "Top level object needs to be a dictionary. Check your .yml file that you have defined a service at the top level."
  99. root_msgs.append(msg)
  100. elif error.validator == 'additionalProperties':
  101. invalid_service_name = _parse_key_from_error_msg(error)
  102. msg = "Invalid service name '{}' - only {} characters are allowed".format(invalid_service_name, VALID_NAME_CHARS)
  103. root_msgs.append(msg)
  104. else:
  105. root_msgs.append(_clean_error_message(error.message))
  106. else:
  107. # handle service level errors
  108. service_name = error.path[0]
  109. # pop the service name off our path
  110. error.path.popleft()
  111. if error.validator == 'additionalProperties':
  112. invalid_config_key = _parse_key_from_error_msg(error)
  113. invalid_keys.append(get_unsupported_config_msg(service_name, invalid_config_key))
  114. elif error.validator == 'anyOf':
  115. if 'image' in error.instance and 'build' in error.instance:
  116. required.append(
  117. "Service '{}' has both an image and build path specified. "
  118. "A service can either be built to image or use an existing "
  119. "image, not both.".format(service_name))
  120. elif 'image' not in error.instance and 'build' not in error.instance:
  121. required.append(
  122. "Service '{}' has neither an image nor a build path "
  123. "specified. Exactly one must be provided.".format(service_name))
  124. elif 'image' in error.instance and 'dockerfile' in error.instance:
  125. required.append(
  126. "Service '{}' has both an image and alternate Dockerfile. "
  127. "A service can either be built to image or use an existing "
  128. "image, not both.".format(service_name))
  129. else:
  130. required.append(_clean_error_message(error.message))
  131. elif error.validator == 'oneOf':
  132. config_key = error.path[0]
  133. valid_types = [_parse_valid_types_from_schema(schema) for schema in error.schema['oneOf']]
  134. valid_type_msg = " or ".join(valid_types)
  135. type_errors.append("Service '{}' configuration key '{}' contains an invalid type, valid types are {}".format(
  136. service_name, config_key, valid_type_msg)
  137. )
  138. elif error.validator == 'type':
  139. msg = "a"
  140. if error.validator_value == "array":
  141. msg = "an"
  142. if len(error.path) > 0:
  143. config_key = " ".join(["'%s'" % k for k in error.path])
  144. type_errors.append(
  145. "Service '{}' configuration key {} contains an invalid "
  146. "type, it should be {} {}".format(
  147. service_name,
  148. config_key,
  149. msg,
  150. error.validator_value))
  151. else:
  152. root_msgs.append(
  153. "Service '{}' doesn\'t have any configuration options. "
  154. "All top level keys in your docker-compose.yml must map "
  155. "to a dictionary of configuration options.'".format(service_name))
  156. elif error.validator == 'required':
  157. config_key = error.path[0]
  158. required.append(
  159. "Service '{}' option '{}' is invalid, {}".format(
  160. service_name,
  161. config_key,
  162. _clean_error_message(error.message)))
  163. elif error.validator == 'dependencies':
  164. dependency_key = list(error.validator_value.keys())[0]
  165. required_keys = ",".join(error.validator_value[dependency_key])
  166. required.append("Invalid '{}' configuration for '{}' service: when defining '{}' you must set '{}' as well".format(
  167. dependency_key, service_name, dependency_key, required_keys))
  168. else:
  169. config_key = " ".join(["'%s'" % k for k in error.path])
  170. err_msg = "Service '{}' configuration key {} value {}".format(service_name, config_key, error.message)
  171. other_errors.append(err_msg)
  172. return "\n".join(root_msgs + invalid_keys + required + type_errors + other_errors)
  173. def validate_against_schema(config):
  174. config_source_dir = os.path.dirname(os.path.abspath(__file__))
  175. schema_file = os.path.join(config_source_dir, "schema.json")
  176. with open(schema_file, "r") as schema_fh:
  177. schema = json.load(schema_fh)
  178. validation_output = Draft4Validator(schema, format_checker=FormatChecker(["ports"]))
  179. errors = [error for error in sorted(validation_output.iter_errors(config), key=str)]
  180. if errors:
  181. error_msg = process_errors(errors)
  182. raise ConfigurationError("Validation failed, reason(s):\n{}".format(error_msg))