validation.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458
  1. from __future__ import absolute_import
  2. from __future__ import unicode_literals
  3. import json
  4. import logging
  5. import os
  6. import re
  7. import sys
  8. import six
  9. from docker.utils.ports import split_port
  10. from jsonschema import Draft4Validator
  11. from jsonschema import FormatChecker
  12. from jsonschema import RefResolver
  13. from jsonschema import ValidationError
  14. from ..const import COMPOSEFILE_V1 as V1
  15. from ..const import NANOCPUS_SCALE
  16. from .errors import ConfigurationError
  17. from .errors import VERSION_EXPLANATION
  18. from .sort_services import get_service_name_from_network_mode
  19. log = logging.getLogger(__name__)
  20. DOCKER_CONFIG_HINTS = {
  21. 'cpu_share': 'cpu_shares',
  22. 'add_host': 'extra_hosts',
  23. 'hosts': 'extra_hosts',
  24. 'extra_host': 'extra_hosts',
  25. 'device': 'devices',
  26. 'link': 'links',
  27. 'memory_swap': 'memswap_limit',
  28. 'port': 'ports',
  29. 'privilege': 'privileged',
  30. 'priviliged': 'privileged',
  31. 'privilige': 'privileged',
  32. 'volume': 'volumes',
  33. 'workdir': 'working_dir',
  34. }
  35. VALID_NAME_CHARS = '[a-zA-Z0-9\._\-]'
  36. VALID_EXPOSE_FORMAT = r'^\d+(\-\d+)?(\/[a-zA-Z]+)?$'
  37. @FormatChecker.cls_checks(format="ports", raises=ValidationError)
  38. def format_ports(instance):
  39. try:
  40. split_port(instance)
  41. except ValueError as e:
  42. raise ValidationError(six.text_type(e))
  43. return True
  44. @FormatChecker.cls_checks(format="expose", raises=ValidationError)
  45. def format_expose(instance):
  46. if isinstance(instance, six.string_types):
  47. if not re.match(VALID_EXPOSE_FORMAT, instance):
  48. raise ValidationError(
  49. "should be of the format 'PORT[/PROTOCOL]'")
  50. return True
  51. def match_named_volumes(service_dict, project_volumes):
  52. service_volumes = service_dict.get('volumes', [])
  53. for volume_spec in service_volumes:
  54. if volume_spec.is_named_volume and volume_spec.external not in project_volumes:
  55. raise ConfigurationError(
  56. 'Named volume "{0}" is used in service "{1}" but no'
  57. ' declaration was found in the volumes section.'.format(
  58. volume_spec.repr(), service_dict.get('name')
  59. )
  60. )
  61. def python_type_to_yaml_type(type_):
  62. type_name = type(type_).__name__
  63. return {
  64. 'dict': 'mapping',
  65. 'list': 'array',
  66. 'int': 'number',
  67. 'float': 'number',
  68. 'bool': 'boolean',
  69. 'unicode': 'string',
  70. 'str': 'string',
  71. 'bytes': 'string',
  72. }.get(type_name, type_name)
  73. def validate_config_section(filename, config, section):
  74. """Validate the structure of a configuration section. This must be done
  75. before interpolation so it's separate from schema validation.
  76. """
  77. if not isinstance(config, dict):
  78. raise ConfigurationError(
  79. "In file '{filename}', {section} must be a mapping, not "
  80. "{type}.".format(
  81. filename=filename,
  82. section=section,
  83. type=anglicize_json_type(python_type_to_yaml_type(config))))
  84. for key, value in config.items():
  85. if not isinstance(key, six.string_types):
  86. raise ConfigurationError(
  87. "In file '{filename}', the {section} name {name} must be a "
  88. "quoted string, i.e. '{name}'.".format(
  89. filename=filename,
  90. section=section,
  91. name=key))
  92. if not isinstance(value, (dict, type(None))):
  93. raise ConfigurationError(
  94. "In file '{filename}', {section} '{name}' must be a mapping not "
  95. "{type}.".format(
  96. filename=filename,
  97. section=section,
  98. name=key,
  99. type=anglicize_json_type(python_type_to_yaml_type(value))))
  100. def validate_top_level_object(config_file):
  101. if not isinstance(config_file.config, dict):
  102. raise ConfigurationError(
  103. "Top level object in '{}' needs to be an object not '{}'.".format(
  104. config_file.filename,
  105. type(config_file.config)))
  106. def validate_ulimits(service_config):
  107. ulimit_config = service_config.config.get('ulimits', {})
  108. for limit_name, soft_hard_values in six.iteritems(ulimit_config):
  109. if isinstance(soft_hard_values, dict):
  110. if not soft_hard_values['soft'] <= soft_hard_values['hard']:
  111. raise ConfigurationError(
  112. "Service '{s.name}' has invalid ulimit '{ulimit}'. "
  113. "'soft' value can not be greater than 'hard' value ".format(
  114. s=service_config,
  115. ulimit=ulimit_config))
  116. def validate_extends_file_path(service_name, extends_options, filename):
  117. """
  118. The service to be extended must either be defined in the config key 'file',
  119. or within 'filename'.
  120. """
  121. error_prefix = "Invalid 'extends' configuration for %s:" % service_name
  122. if 'file' not in extends_options and filename is None:
  123. raise ConfigurationError(
  124. "%s you need to specify a 'file', e.g. 'file: something.yml'" % error_prefix
  125. )
  126. def validate_network_mode(service_config, service_names):
  127. network_mode = service_config.config.get('network_mode')
  128. if not network_mode:
  129. return
  130. if 'networks' in service_config.config:
  131. raise ConfigurationError("'network_mode' and 'networks' cannot be combined")
  132. dependency = get_service_name_from_network_mode(network_mode)
  133. if not dependency:
  134. return
  135. if dependency not in service_names:
  136. raise ConfigurationError(
  137. "Service '{s.name}' uses the network stack of service '{dep}' which "
  138. "is undefined.".format(s=service_config, dep=dependency))
  139. def validate_pid_mode(service_config, service_names):
  140. pid_mode = service_config.config.get('pid')
  141. if not pid_mode:
  142. return
  143. dependency = get_service_name_from_network_mode(pid_mode)
  144. if not dependency:
  145. return
  146. if dependency not in service_names:
  147. raise ConfigurationError(
  148. "Service '{s.name}' uses the PID namespace of service '{dep}' which "
  149. "is undefined.".format(s=service_config, dep=dependency)
  150. )
  151. def validate_links(service_config, service_names):
  152. for link in service_config.config.get('links', []):
  153. if link.split(':')[0] not in service_names:
  154. raise ConfigurationError(
  155. "Service '{s.name}' has a link to service '{link}' which is "
  156. "undefined.".format(s=service_config, link=link))
  157. def validate_depends_on(service_config, service_names):
  158. deps = service_config.config.get('depends_on', {})
  159. for dependency in deps.keys():
  160. if dependency not in service_names:
  161. raise ConfigurationError(
  162. "Service '{s.name}' depends on service '{dep}' which is "
  163. "undefined.".format(s=service_config, dep=dependency)
  164. )
  165. def get_unsupported_config_msg(path, error_key):
  166. msg = "Unsupported config option for {}: '{}'".format(path_string(path), error_key)
  167. if error_key in DOCKER_CONFIG_HINTS:
  168. msg += " (did you mean '{}'?)".format(DOCKER_CONFIG_HINTS[error_key])
  169. return msg
  170. def anglicize_json_type(json_type):
  171. if json_type.startswith(('a', 'e', 'i', 'o', 'u')):
  172. return 'an ' + json_type
  173. return 'a ' + json_type
  174. def is_service_dict_schema(schema_id):
  175. return schema_id in ('config_schema_v1.json', '#/properties/services')
  176. def handle_error_for_schema_with_id(error, path):
  177. schema_id = error.schema['id']
  178. if is_service_dict_schema(schema_id) and error.validator == 'additionalProperties':
  179. return "Invalid service name '{}' - only {} characters are allowed".format(
  180. # The service_name is one of the keys in the json object
  181. [i for i in list(error.instance) if not i or any(filter(
  182. lambda c: not re.match(VALID_NAME_CHARS, c), i
  183. ))][0],
  184. VALID_NAME_CHARS
  185. )
  186. if error.validator == 'additionalProperties':
  187. if schema_id == '#/definitions/service':
  188. invalid_config_key = parse_key_from_error_msg(error)
  189. return get_unsupported_config_msg(path, invalid_config_key)
  190. if not error.path:
  191. return '{}\n\n{}'.format(error.message, VERSION_EXPLANATION)
  192. def handle_generic_error(error, path):
  193. msg_format = None
  194. error_msg = error.message
  195. if error.validator == 'oneOf':
  196. msg_format = "{path} {msg}"
  197. config_key, error_msg = _parse_oneof_validator(error)
  198. if config_key:
  199. path.append(config_key)
  200. elif error.validator == 'type':
  201. msg_format = "{path} contains an invalid type, it should be {msg}"
  202. error_msg = _parse_valid_types_from_validator(error.validator_value)
  203. elif error.validator == 'required':
  204. error_msg = ", ".join(error.validator_value)
  205. msg_format = "{path} is invalid, {msg} is required."
  206. elif error.validator == 'dependencies':
  207. config_key = list(error.validator_value.keys())[0]
  208. required_keys = ",".join(error.validator_value[config_key])
  209. msg_format = "{path} is invalid: {msg}"
  210. path.append(config_key)
  211. error_msg = "when defining '{}' you must set '{}' as well".format(
  212. config_key,
  213. required_keys)
  214. elif error.cause:
  215. error_msg = six.text_type(error.cause)
  216. msg_format = "{path} is invalid: {msg}"
  217. elif error.path:
  218. msg_format = "{path} value {msg}"
  219. if msg_format:
  220. return msg_format.format(path=path_string(path), msg=error_msg)
  221. return error.message
  222. def parse_key_from_error_msg(error):
  223. return error.message.split("'")[1]
  224. def path_string(path):
  225. return ".".join(c for c in path if isinstance(c, six.string_types))
  226. def _parse_valid_types_from_validator(validator):
  227. """A validator value can be either an array of valid types or a string of
  228. a valid type. Parse the valid types and prefix with the correct article.
  229. """
  230. if not isinstance(validator, list):
  231. return anglicize_json_type(validator)
  232. if len(validator) == 1:
  233. return anglicize_json_type(validator[0])
  234. return "{}, or {}".format(
  235. ", ".join([anglicize_json_type(validator[0])] + validator[1:-1]),
  236. anglicize_json_type(validator[-1]))
  237. def _parse_oneof_validator(error):
  238. """oneOf has multiple schemas, so we need to reason about which schema, sub
  239. schema or constraint the validation is failing on.
  240. Inspecting the context value of a ValidationError gives us information about
  241. which sub schema failed and which kind of error it is.
  242. """
  243. types = []
  244. for context in error.context:
  245. if context.validator == 'oneOf':
  246. _, error_msg = _parse_oneof_validator(context)
  247. return path_string(context.path), error_msg
  248. if context.validator == 'required':
  249. return (None, context.message)
  250. if context.validator == 'additionalProperties':
  251. invalid_config_key = parse_key_from_error_msg(context)
  252. return (None, "contains unsupported option: '{}'".format(invalid_config_key))
  253. if context.path:
  254. return (
  255. path_string(context.path),
  256. "contains {}, which is an invalid type, it should be {}".format(
  257. json.dumps(context.instance),
  258. _parse_valid_types_from_validator(context.validator_value)),
  259. )
  260. if context.validator == 'uniqueItems':
  261. return (
  262. None,
  263. "contains non unique items, please remove duplicates from {}".format(
  264. context.instance),
  265. )
  266. if context.validator == 'type':
  267. types.append(context.validator_value)
  268. valid_types = _parse_valid_types_from_validator(types)
  269. return (None, "contains an invalid type, it should be {}".format(valid_types))
  270. def process_service_constraint_errors(error, service_name, version):
  271. if version == V1:
  272. if 'image' in error.instance and 'build' in error.instance:
  273. return (
  274. "Service {} has both an image and build path specified. "
  275. "A service can either be built to image or use an existing "
  276. "image, not both.".format(service_name))
  277. if 'image' in error.instance and 'dockerfile' in error.instance:
  278. return (
  279. "Service {} has both an image and alternate Dockerfile. "
  280. "A service can either be built to image or use an existing "
  281. "image, not both.".format(service_name))
  282. if 'image' not in error.instance and 'build' not in error.instance:
  283. return (
  284. "Service {} has neither an image nor a build context specified. "
  285. "At least one must be provided.".format(service_name))
  286. def process_config_schema_errors(error):
  287. path = list(error.path)
  288. if 'id' in error.schema:
  289. error_msg = handle_error_for_schema_with_id(error, path)
  290. if error_msg:
  291. return error_msg
  292. return handle_generic_error(error, path)
  293. def validate_against_config_schema(config_file):
  294. schema = load_jsonschema(config_file)
  295. format_checker = FormatChecker(["ports", "expose"])
  296. validator = Draft4Validator(
  297. schema,
  298. resolver=RefResolver(get_resolver_path(), schema),
  299. format_checker=format_checker)
  300. handle_errors(
  301. validator.iter_errors(config_file.config),
  302. process_config_schema_errors,
  303. config_file.filename)
  304. def validate_service_constraints(config, service_name, config_file):
  305. def handler(errors):
  306. return process_service_constraint_errors(
  307. errors, service_name, config_file.version)
  308. schema = load_jsonschema(config_file)
  309. validator = Draft4Validator(schema['definitions']['constraints']['service'])
  310. handle_errors(validator.iter_errors(config), handler, None)
  311. def validate_cpu(service_config):
  312. cpus = service_config.config.get('cpus')
  313. if not cpus:
  314. return
  315. nano_cpus = cpus * NANOCPUS_SCALE
  316. if isinstance(nano_cpus, float) and not nano_cpus.is_integer():
  317. raise ConfigurationError(
  318. "cpus must have nine or less digits after decimal point")
  319. def get_schema_path():
  320. return os.path.dirname(os.path.abspath(__file__))
  321. def load_jsonschema(config_file):
  322. filename = os.path.join(
  323. get_schema_path(),
  324. "config_schema_v{0}.json".format(config_file.version))
  325. if not os.path.exists(filename):
  326. raise ConfigurationError(
  327. 'Version in "{}" is unsupported. {}'
  328. .format(config_file.filename, VERSION_EXPLANATION))
  329. with open(filename, "r") as fh:
  330. return json.load(fh)
  331. def get_resolver_path():
  332. schema_path = get_schema_path()
  333. if sys.platform == "win32":
  334. scheme = "///"
  335. # TODO: why is this necessary?
  336. schema_path = schema_path.replace('\\', '/')
  337. else:
  338. scheme = "//"
  339. return "file:{}{}/".format(scheme, schema_path)
  340. def handle_errors(errors, format_error_func, filename):
  341. """jsonschema returns an error tree full of information to explain what has
  342. gone wrong. Process each error and pull out relevant information and re-write
  343. helpful error messages that are relevant.
  344. """
  345. errors = list(sorted(errors, key=str))
  346. if not errors:
  347. return
  348. error_msg = '\n'.join(format_error_func(error) for error in errors)
  349. raise ConfigurationError(
  350. "The Compose file{file_msg} is invalid because:\n{error_msg}".format(
  351. file_msg=" '{}'".format(filename) if filename else "",
  352. error_msg=error_msg))