validation.py 7.2 KB

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