validation.py 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122
  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. root_msgs = []
  43. invalid_keys = []
  44. required = []
  45. type_errors = []
  46. for error in errors:
  47. # handle root level errors
  48. if len(error.path) == 0:
  49. if error.validator == 'type':
  50. msg = "Top level object needs to be a dictionary. Check your .yml file that you have defined a service at the top level."
  51. root_msgs.append(msg)
  52. elif error.validator == 'additionalProperties':
  53. invalid_service_name = _parse_key_from_error_msg(error)
  54. msg = "Invalid service name '{}' - only {} characters are allowed".format(invalid_service_name, VALID_NAME_CHARS)
  55. root_msgs.append(msg)
  56. else:
  57. root_msgs.append(error.message)
  58. else:
  59. # handle service level errors
  60. service_name = error.path[0]
  61. if error.validator == 'additionalProperties':
  62. invalid_config_key = _parse_key_from_error_msg(error)
  63. invalid_keys.append(get_unsupported_config_msg(service_name, invalid_config_key))
  64. elif error.validator == 'anyOf':
  65. if 'image' in error.instance and 'build' in error.instance:
  66. 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))
  67. elif 'image' not in error.instance and 'build' not in error.instance:
  68. required.append("Service '{}' has neither an image nor a build path specified. Exactly one must be provided.".format(service_name))
  69. else:
  70. required.append(error.message)
  71. elif error.validator == 'type':
  72. msg = "a"
  73. if error.validator_value == "array":
  74. msg = "an"
  75. try:
  76. config_key = error.path[1]
  77. type_errors.append("Service '{}' has an invalid value for '{}', it should be {} {}".format(service_name, config_key, msg, error.validator_value))
  78. except IndexError:
  79. config_key = error.path[0]
  80. 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))
  81. elif error.validator == 'required':
  82. config_key = error.path[1]
  83. required.append("Service '{}' option '{}' is invalid, {}".format(service_name, config_key, error.message))
  84. elif error.validator == 'dependencies':
  85. dependency_key = error.validator_value.keys()[0]
  86. required_keys = ",".join(error.validator_value[dependency_key])
  87. required.append("Invalid '{}' configuration for '{}' service: when defining '{}' you must set '{}' as well".format(
  88. dependency_key, service_name, dependency_key, required_keys))
  89. return "\n".join(root_msgs + invalid_keys + required + type_errors)
  90. def validate_against_schema(config):
  91. config_source_dir = os.path.dirname(os.path.abspath(__file__))
  92. schema_file = os.path.join(config_source_dir, "schema.json")
  93. with open(schema_file, "r") as schema_fh:
  94. schema = json.load(schema_fh)
  95. validation_output = Draft4Validator(schema, format_checker=FormatChecker(["ports"]))
  96. errors = [error for error in sorted(validation_output.iter_errors(config), key=str)]
  97. if errors:
  98. error_msg = process_errors(errors)
  99. raise ConfigurationError("Validation failed, reason(s):\n{}".format(error_msg))