validation.py 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177
  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(format="ports", raises=ValidationError("Invalid port formatting, it should be '[[remote_ip:]remote_port:]port[/protocol]'"))
  26. def format_ports(instance):
  27. try:
  28. split_port(instance)
  29. except ValueError:
  30. return False
  31. return True
  32. def validate_service_names(func):
  33. @wraps(func)
  34. def func_wrapper(config):
  35. for service_name in config.keys():
  36. if type(service_name) is int:
  37. raise ConfigurationError(
  38. "Service name: {} needs to be a string, eg '{}'".format(service_name, service_name)
  39. )
  40. return func(config)
  41. return func_wrapper
  42. def validate_top_level_object(func):
  43. @wraps(func)
  44. def func_wrapper(config):
  45. if not isinstance(config, dict):
  46. raise ConfigurationError(
  47. "Top level object needs to be a dictionary. Check your .yml file that you have defined a service at the top level."
  48. )
  49. return func(config)
  50. return func_wrapper
  51. def get_unsupported_config_msg(service_name, error_key):
  52. msg = "Unsupported config option for '{}' service: '{}'".format(service_name, error_key)
  53. if error_key in DOCKER_CONFIG_HINTS:
  54. msg += " (did you mean '{}'?)".format(DOCKER_CONFIG_HINTS[error_key])
  55. return msg
  56. def process_errors(errors):
  57. """
  58. jsonschema gives us an error tree full of information to explain what has
  59. gone wrong. Process each error and pull out relevant information and re-write
  60. helpful error messages that are relevant.
  61. """
  62. def _parse_key_from_error_msg(error):
  63. return error.message.split("'")[1]
  64. def _clean_error_message(message):
  65. return message.replace("u'", "'")
  66. def _parse_valid_types_from_schema(schema):
  67. """
  68. Our defined types using $ref in the schema require some extra parsing
  69. retrieve a helpful type for error message display.
  70. """
  71. if '$ref' in schema:
  72. return schema['$ref'].replace("#/definitions/", "").replace("_", " ")
  73. else:
  74. return str(schema['type'])
  75. root_msgs = []
  76. invalid_keys = []
  77. required = []
  78. type_errors = []
  79. other_errors = []
  80. for error in errors:
  81. # handle root level errors
  82. if len(error.path) == 0:
  83. if error.validator == 'type':
  84. msg = "Top level object needs to be a dictionary. Check your .yml file that you have defined a service at the top level."
  85. root_msgs.append(msg)
  86. elif error.validator == 'additionalProperties':
  87. invalid_service_name = _parse_key_from_error_msg(error)
  88. msg = "Invalid service name '{}' - only {} characters are allowed".format(invalid_service_name, VALID_NAME_CHARS)
  89. root_msgs.append(msg)
  90. else:
  91. root_msgs.append(_clean_error_message(error.message))
  92. else:
  93. # handle service level errors
  94. service_name = error.path[0]
  95. # pop the service name off our path
  96. error.path.popleft()
  97. if error.validator == 'additionalProperties':
  98. invalid_config_key = _parse_key_from_error_msg(error)
  99. invalid_keys.append(get_unsupported_config_msg(service_name, invalid_config_key))
  100. elif error.validator == 'anyOf':
  101. if 'image' in error.instance and 'build' in error.instance:
  102. required.append("Service '{}' has both an image and build path specified. A service can either be built to image or use an existing image, not both.".format(service_name))
  103. elif 'image' not in error.instance and 'build' not in error.instance:
  104. required.append("Service '{}' has neither an image nor a build path specified. Exactly one must be provided.".format(service_name))
  105. else:
  106. required.append(_clean_error_message(error.message))
  107. elif error.validator == 'oneOf':
  108. config_key = error.path[0]
  109. valid_types = [_parse_valid_types_from_schema(schema) for schema in error.schema['oneOf']]
  110. valid_type_msg = " or ".join(valid_types)
  111. type_errors.append("Service '{}' configuration key '{}' contains an invalid type, valid types are {}".format(
  112. service_name, config_key, valid_type_msg)
  113. )
  114. elif error.validator == 'type':
  115. msg = "a"
  116. if error.validator_value == "array":
  117. msg = "an"
  118. if len(error.path) > 0:
  119. config_key = " ".join(["'%s'" % k for k in error.path])
  120. type_errors.append("Service '{}' configuration key {} contains an invalid type, it should be {} {}".format(service_name, config_key, msg, error.validator_value))
  121. else:
  122. root_msgs.append("Service '{}' doesn\'t have any configuration options. All top level keys in your docker-compose.yml must map to a dictionary of configuration options.'".format(service_name))
  123. elif error.validator == 'required':
  124. config_key = error.path[0]
  125. required.append("Service '{}' option '{}' is invalid, {}".format(service_name, config_key, _clean_error_message(error.message)))
  126. elif error.validator == 'dependencies':
  127. dependency_key = list(error.validator_value.keys())[0]
  128. required_keys = ",".join(error.validator_value[dependency_key])
  129. required.append("Invalid '{}' configuration for '{}' service: when defining '{}' you must set '{}' as well".format(
  130. dependency_key, service_name, dependency_key, required_keys))
  131. else:
  132. config_key = " ".join(["'%s'" % k for k in error.path])
  133. err_msg = "Service '{}' configuration key {} value {}".format(service_name, config_key, error.message)
  134. other_errors.append(err_msg)
  135. return "\n".join(root_msgs + invalid_keys + required + type_errors + other_errors)
  136. def validate_against_schema(config):
  137. config_source_dir = os.path.dirname(os.path.abspath(__file__))
  138. schema_file = os.path.join(config_source_dir, "schema.json")
  139. with open(schema_file, "r") as schema_fh:
  140. schema = json.load(schema_fh)
  141. validation_output = Draft4Validator(schema, format_checker=FormatChecker(["ports"]))
  142. errors = [error for error in sorted(validation_output.iter_errors(config), key=str)]
  143. if errors:
  144. error_msg = process_errors(errors)
  145. raise ConfigurationError("Validation failed, reason(s):\n{}".format(error_msg))