validation.py 18 KB

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