validation.py 18 KB

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