validation.py 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151
  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. def _parse_valid_types_from_schema(schema):
  45. """
  46. Our defined types using $ref in the schema require some extra parsing
  47. retrieve a helpful type for error message display.
  48. """
  49. if '$ref' in schema:
  50. return schema['$ref'].replace("#/definitions/", "").replace("_", " ")
  51. else:
  52. return str(schema['type'])
  53. root_msgs = []
  54. invalid_keys = []
  55. required = []
  56. type_errors = []
  57. other_errors = []
  58. for error in errors:
  59. # handle root level errors
  60. if len(error.path) == 0:
  61. if error.validator == 'type':
  62. msg = "Top level object needs to be a dictionary. Check your .yml file that you have defined a service at the top level."
  63. root_msgs.append(msg)
  64. elif error.validator == 'additionalProperties':
  65. invalid_service_name = _parse_key_from_error_msg(error)
  66. msg = "Invalid service name '{}' - only {} characters are allowed".format(invalid_service_name, VALID_NAME_CHARS)
  67. root_msgs.append(msg)
  68. else:
  69. root_msgs.append(_clean_error_message(error.message))
  70. else:
  71. # handle service level errors
  72. service_name = error.path[0]
  73. # pop the service name off our path
  74. error.path.popleft()
  75. if error.validator == 'additionalProperties':
  76. invalid_config_key = _parse_key_from_error_msg(error)
  77. invalid_keys.append(get_unsupported_config_msg(service_name, invalid_config_key))
  78. elif error.validator == 'anyOf':
  79. if 'image' in error.instance and 'build' in error.instance:
  80. 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))
  81. elif 'image' not in error.instance and 'build' not in error.instance:
  82. required.append("Service '{}' has neither an image nor a build path specified. Exactly one must be provided.".format(service_name))
  83. else:
  84. required.append(_clean_error_message(error.message))
  85. elif error.validator == 'oneOf':
  86. config_key = error.path[0]
  87. valid_types = [_parse_valid_types_from_schema(schema) for schema in error.schema['oneOf']]
  88. valid_type_msg = " or ".join(valid_types)
  89. type_errors.append("Service '{}' configuration key '{}' contains an invalid type, valid types are {}".format(
  90. service_name, config_key, valid_type_msg)
  91. )
  92. elif error.validator == 'type':
  93. msg = "a"
  94. if error.validator_value == "array":
  95. msg = "an"
  96. if len(error.path) > 0:
  97. config_key = " ".join(["'%s'" % k for k in error.path])
  98. type_errors.append("Service '{}' configuration key {} contains an invalid type, it should be {} {}".format(service_name, config_key, msg, error.validator_value))
  99. else:
  100. 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))
  101. elif error.validator == 'required':
  102. config_key = error.path[0]
  103. required.append("Service '{}' option '{}' is invalid, {}".format(service_name, config_key, _clean_error_message(error.message)))
  104. elif error.validator == 'dependencies':
  105. dependency_key = error.validator_value.keys()[0]
  106. required_keys = ",".join(error.validator_value[dependency_key])
  107. required.append("Invalid '{}' configuration for '{}' service: when defining '{}' you must set '{}' as well".format(
  108. dependency_key, service_name, dependency_key, required_keys))
  109. else:
  110. config_key = " ".join(["'%s'" % k for k in error.path])
  111. err_msg = "Service '{}' configuration key {} value {}".format(service_name, config_key, error.message)
  112. other_errors.append(err_msg)
  113. return "\n".join(root_msgs + invalid_keys + required + type_errors + other_errors)
  114. def validate_against_schema(config):
  115. config_source_dir = os.path.dirname(os.path.abspath(__file__))
  116. schema_file = os.path.join(config_source_dir, "schema.json")
  117. with open(schema_file, "r") as schema_fh:
  118. schema = json.load(schema_fh)
  119. validation_output = Draft4Validator(schema, format_checker=FormatChecker(["ports"]))
  120. errors = [error for error in sorted(validation_output.iter_errors(config), key=str)]
  121. if errors:
  122. error_msg = process_errors(errors)
  123. raise ConfigurationError("Validation failed, reason(s):\n{}".format(error_msg))