validation.py 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134
  1. import os
  2. import json
  3. from jsonschema import Draft4Validator, FormatChecker, ValidationError
  4. from .errors import ConfigurationError
  5. DOCKER_CONFIG_HINTS = {
  6. 'cpu_share': 'cpu_shares',
  7. 'add_host': 'extra_hosts',
  8. 'hosts': 'extra_hosts',
  9. 'extra_host': 'extra_hosts',
  10. 'device': 'devices',
  11. 'link': 'links',
  12. 'memory_swap': 'memswap_limit',
  13. 'port': 'ports',
  14. 'privilege': 'privileged',
  15. 'priviliged': 'privileged',
  16. 'privilige': 'privileged',
  17. 'volume': 'volumes',
  18. 'workdir': 'working_dir',
  19. }
  20. VALID_NAME_CHARS = '[a-zA-Z0-9\._\-]'
  21. @FormatChecker.cls_checks(format="ports", raises=ValidationError("Ports is incorrectly formatted."))
  22. def format_ports(instance):
  23. def _is_valid(port):
  24. if ':' in port or '/' in port:
  25. return True
  26. try:
  27. int(port)
  28. return True
  29. except ValueError:
  30. return False
  31. return False
  32. if isinstance(instance, list):
  33. for port in instance:
  34. if not _is_valid(port):
  35. return False
  36. return True
  37. elif isinstance(instance, str):
  38. return _is_valid(instance)
  39. return False
  40. def get_unsupported_config_msg(service_name, error_key):
  41. msg = "Unsupported config option for '{}' service: '{}'".format(service_name, error_key)
  42. if error_key in DOCKER_CONFIG_HINTS:
  43. msg += " (did you mean '{}'?)".format(DOCKER_CONFIG_HINTS[error_key])
  44. return msg
  45. def process_errors(errors):
  46. """
  47. jsonschema gives us an error tree full of information to explain what has
  48. gone wrong. Process each error and pull out relevant information and re-write
  49. helpful error messages that are relevant.
  50. """
  51. def _parse_key_from_error_msg(error):
  52. return error.message.split("'")[1]
  53. root_msgs = []
  54. invalid_keys = []
  55. required = []
  56. type_errors = []
  57. for error in errors:
  58. # handle root level errors
  59. if len(error.path) == 0:
  60. if error.validator == 'type':
  61. msg = "Top level object needs to be a dictionary. Check your .yml file that you have defined a service at the top level."
  62. root_msgs.append(msg)
  63. elif error.validator == 'additionalProperties':
  64. invalid_service_name = _parse_key_from_error_msg(error)
  65. msg = "Invalid service name '{}' - only {} characters are allowed".format(invalid_service_name, VALID_NAME_CHARS)
  66. root_msgs.append(msg)
  67. else:
  68. root_msgs.append(error.message)
  69. else:
  70. # handle service level errors
  71. service_name = error.path[0]
  72. if error.validator == 'additionalProperties':
  73. invalid_config_key = _parse_key_from_error_msg(error)
  74. invalid_keys.append(get_unsupported_config_msg(service_name, invalid_config_key))
  75. elif error.validator == 'anyOf':
  76. if 'image' in error.instance and 'build' in error.instance:
  77. 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))
  78. elif 'image' not in error.instance and 'build' not in error.instance:
  79. required.append("Service '{}' has neither an image nor a build path specified. Exactly one must be provided.".format(service_name))
  80. else:
  81. required.append(error.message)
  82. elif error.validator == 'type':
  83. msg = "a"
  84. if error.validator_value == "array":
  85. msg = "an"
  86. try:
  87. config_key = error.path[1]
  88. type_errors.append("Service '{}' has an invalid value for '{}', it should be {} {}".format(service_name, config_key, msg, error.validator_value))
  89. except IndexError:
  90. config_key = error.path[0]
  91. 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(config_key))
  92. elif error.validator == 'required':
  93. config_key = error.path[1]
  94. required.append("Service '{}' option '{}' is invalid, {}".format(service_name, config_key, error.message))
  95. elif error.validator == 'dependencies':
  96. dependency_key = error.validator_value.keys()[0]
  97. required_keys = ",".join(error.validator_value[dependency_key])
  98. required.append("Invalid '{}' configuration for '{}' service: when defining '{}' you must set '{}' as well".format(
  99. dependency_key, service_name, dependency_key, required_keys))
  100. return "\n".join(root_msgs + invalid_keys + required + type_errors)
  101. def validate_against_schema(config):
  102. config_source_dir = os.path.dirname(os.path.abspath(__file__))
  103. schema_file = os.path.join(config_source_dir, "schema.json")
  104. with open(schema_file, "r") as schema_fh:
  105. schema = json.load(schema_fh)
  106. validation_output = Draft4Validator(schema, format_checker=FormatChecker(["ports"]))
  107. errors = [error for error in sorted(validation_output.iter_errors(config), key=str)]
  108. if errors:
  109. error_msg = process_errors(errors)
  110. raise ConfigurationError("Validation failed, reason(s):\n{}".format(error_msg))