validation.py 6.1 KB

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