validation.py 8.0 KB

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