validation.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541
  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 validate_credential_spec(service_config):
  196. credential_spec = service_config.config.get('credential_spec')
  197. if not credential_spec:
  198. return
  199. if 'registry' not in credential_spec and 'file' not in credential_spec:
  200. raise ConfigurationError(
  201. "Service '{s.name}' is missing 'credential_spec.file' or "
  202. "credential_spec.registry'".format(s=service_config)
  203. )
  204. def get_unsupported_config_msg(path, error_key):
  205. msg = "Unsupported config option for {}: '{}'".format(path_string(path), error_key)
  206. if error_key in DOCKER_CONFIG_HINTS:
  207. msg += " (did you mean '{}'?)".format(DOCKER_CONFIG_HINTS[error_key])
  208. return msg
  209. def anglicize_json_type(json_type):
  210. if json_type.startswith(('a', 'e', 'i', 'o', 'u')):
  211. return 'an ' + json_type
  212. return 'a ' + json_type
  213. def is_service_dict_schema(schema_id):
  214. return schema_id in ('config_schema_v1.json', '#/properties/services')
  215. def handle_error_for_schema_with_id(error, path):
  216. schema_id = error.schema['id']
  217. if is_service_dict_schema(schema_id) and error.validator == 'additionalProperties':
  218. return "Invalid service name '{}' - only {} characters are allowed".format(
  219. # The service_name is one of the keys in the json object
  220. [i for i in list(error.instance) if not i or any(filter(
  221. lambda c: not re.match(VALID_NAME_CHARS, c), i
  222. ))][0],
  223. VALID_NAME_CHARS
  224. )
  225. if error.validator == 'additionalProperties':
  226. if schema_id == '#/definitions/service':
  227. invalid_config_key = parse_key_from_error_msg(error)
  228. return get_unsupported_config_msg(path, invalid_config_key)
  229. if schema_id.startswith('config_schema_v'):
  230. invalid_config_key = parse_key_from_error_msg(error)
  231. return ('Invalid top-level property "{key}". Valid top-level '
  232. 'sections for this Compose file are: {properties}, and '
  233. 'extensions starting with "x-".\n\n{explanation}').format(
  234. key=invalid_config_key,
  235. properties=', '.join(error.schema['properties'].keys()),
  236. explanation=VERSION_EXPLANATION
  237. )
  238. if not error.path:
  239. return '{}\n\n{}'.format(error.message, VERSION_EXPLANATION)
  240. def handle_generic_error(error, path):
  241. msg_format = None
  242. error_msg = error.message
  243. if error.validator == 'oneOf':
  244. msg_format = "{path} {msg}"
  245. config_key, error_msg = _parse_oneof_validator(error)
  246. if config_key:
  247. path.append(config_key)
  248. elif error.validator == 'type':
  249. msg_format = "{path} contains an invalid type, it should be {msg}"
  250. error_msg = _parse_valid_types_from_validator(error.validator_value)
  251. elif error.validator == 'required':
  252. error_msg = ", ".join(error.validator_value)
  253. msg_format = "{path} is invalid, {msg} is required."
  254. elif error.validator == 'dependencies':
  255. config_key = list(error.validator_value.keys())[0]
  256. required_keys = ",".join(error.validator_value[config_key])
  257. msg_format = "{path} is invalid: {msg}"
  258. path.append(config_key)
  259. error_msg = "when defining '{}' you must set '{}' as well".format(
  260. config_key,
  261. required_keys)
  262. elif error.cause:
  263. error_msg = six.text_type(error.cause)
  264. msg_format = "{path} is invalid: {msg}"
  265. elif error.path:
  266. msg_format = "{path} value {msg}"
  267. if msg_format:
  268. return msg_format.format(path=path_string(path), msg=error_msg)
  269. return error.message
  270. def parse_key_from_error_msg(error):
  271. try:
  272. return error.message.split("'")[1]
  273. except IndexError:
  274. return error.message.split('(')[1].split(' ')[0].strip("'")
  275. def path_string(path):
  276. return ".".join(c for c in path if isinstance(c, six.string_types))
  277. def _parse_valid_types_from_validator(validator):
  278. """A validator value can be either an array of valid types or a string of
  279. a valid type. Parse the valid types and prefix with the correct article.
  280. """
  281. if not isinstance(validator, list):
  282. return anglicize_json_type(validator)
  283. if len(validator) == 1:
  284. return anglicize_json_type(validator[0])
  285. return "{}, or {}".format(
  286. ", ".join([anglicize_json_type(validator[0])] + validator[1:-1]),
  287. anglicize_json_type(validator[-1]))
  288. def _parse_oneof_validator(error):
  289. """oneOf has multiple schemas, so we need to reason about which schema, sub
  290. schema or constraint the validation is failing on.
  291. Inspecting the context value of a ValidationError gives us information about
  292. which sub schema failed and which kind of error it is.
  293. """
  294. types = []
  295. for context in error.context:
  296. if context.validator == 'oneOf':
  297. _, error_msg = _parse_oneof_validator(context)
  298. return path_string(context.path), error_msg
  299. if context.validator == 'required':
  300. return (None, context.message)
  301. if context.validator == 'additionalProperties':
  302. invalid_config_key = parse_key_from_error_msg(context)
  303. return (None, "contains unsupported option: '{}'".format(invalid_config_key))
  304. if context.validator == 'uniqueItems':
  305. return (
  306. path_string(context.path) if context.path else None,
  307. "contains non-unique items, please remove duplicates from {}".format(
  308. context.instance),
  309. )
  310. if context.path:
  311. return (
  312. path_string(context.path),
  313. "contains {}, which is an invalid type, it should be {}".format(
  314. json.dumps(context.instance),
  315. _parse_valid_types_from_validator(context.validator_value)),
  316. )
  317. if context.validator == 'type':
  318. types.append(context.validator_value)
  319. valid_types = _parse_valid_types_from_validator(types)
  320. return (None, "contains an invalid type, it should be {}".format(valid_types))
  321. def process_service_constraint_errors(error, service_name, version):
  322. if version == V1:
  323. if 'image' in error.instance and 'build' in error.instance:
  324. return (
  325. "Service {} has both an image and build path specified. "
  326. "A service can either be built to image or use an existing "
  327. "image, not both.".format(service_name))
  328. if 'image' in error.instance and 'dockerfile' in error.instance:
  329. return (
  330. "Service {} has both an image and alternate Dockerfile. "
  331. "A service can either be built to image or use an existing "
  332. "image, not both.".format(service_name))
  333. if 'image' not in error.instance and 'build' not in error.instance:
  334. return (
  335. "Service {} has neither an image nor a build context specified. "
  336. "At least one must be provided.".format(service_name))
  337. def process_config_schema_errors(error):
  338. path = list(error.path)
  339. if 'id' in error.schema:
  340. error_msg = handle_error_for_schema_with_id(error, path)
  341. if error_msg:
  342. return error_msg
  343. return handle_generic_error(error, path)
  344. def validate_against_config_schema(config_file):
  345. schema = load_jsonschema(config_file)
  346. format_checker = FormatChecker(["ports", "expose", "subnet_ip_address"])
  347. validator = Draft4Validator(
  348. schema,
  349. resolver=RefResolver(get_resolver_path(), schema),
  350. format_checker=format_checker)
  351. handle_errors(
  352. validator.iter_errors(config_file.config),
  353. process_config_schema_errors,
  354. config_file.filename)
  355. def validate_service_constraints(config, service_name, config_file):
  356. def handler(errors):
  357. return process_service_constraint_errors(
  358. errors, service_name, config_file.version)
  359. schema = load_jsonschema(config_file)
  360. validator = Draft4Validator(schema['definitions']['constraints']['service'])
  361. handle_errors(validator.iter_errors(config), handler, None)
  362. def validate_cpu(service_config):
  363. cpus = service_config.config.get('cpus')
  364. if not cpus:
  365. return
  366. nano_cpus = cpus * NANOCPUS_SCALE
  367. if isinstance(nano_cpus, float) and not nano_cpus.is_integer():
  368. raise ConfigurationError(
  369. "cpus must have nine or less digits after decimal point")
  370. def get_schema_path():
  371. return os.path.dirname(os.path.abspath(__file__))
  372. def load_jsonschema(config_file):
  373. filename = os.path.join(
  374. get_schema_path(),
  375. "config_schema_v{0}.json".format(config_file.version))
  376. if not os.path.exists(filename):
  377. raise ConfigurationError(
  378. 'Version in "{}" is unsupported. {}'
  379. .format(config_file.filename, VERSION_EXPLANATION))
  380. with open(filename, "r") as fh:
  381. return json.load(fh)
  382. def get_resolver_path():
  383. schema_path = get_schema_path()
  384. if sys.platform == "win32":
  385. scheme = "///"
  386. # TODO: why is this necessary?
  387. schema_path = schema_path.replace('\\', '/')
  388. else:
  389. scheme = "//"
  390. return "file:{}{}/".format(scheme, schema_path)
  391. def handle_errors(errors, format_error_func, filename):
  392. """jsonschema returns an error tree full of information to explain what has
  393. gone wrong. Process each error and pull out relevant information and re-write
  394. helpful error messages that are relevant.
  395. """
  396. errors = list(sorted(errors, key=str))
  397. if not errors:
  398. return
  399. error_msg = '\n'.join(format_error_func(error) for error in errors)
  400. raise ConfigurationError(
  401. "The Compose file{file_msg} is invalid because:\n{error_msg}".format(
  402. file_msg=" '{}'".format(filename) if filename else "",
  403. error_msg=error_msg))
  404. def validate_healthcheck(service_config):
  405. healthcheck = service_config.config.get('healthcheck', {})
  406. if 'test' in healthcheck and isinstance(healthcheck['test'], list):
  407. if len(healthcheck['test']) == 0:
  408. raise ConfigurationError(
  409. 'Service "{}" defines an invalid healthcheck: '
  410. '"test" is an empty list'
  411. .format(service_config.name))
  412. # when disable is true config.py::process_healthcheck adds "test: ['NONE']" to service_config
  413. elif healthcheck['test'][0] == 'NONE' and len(healthcheck) > 1:
  414. raise ConfigurationError(
  415. 'Service "{}" defines an invalid healthcheck: '
  416. '"disable: true" cannot be combined with other options'
  417. .format(service_config.name))
  418. elif healthcheck['test'][0] not in ('NONE', 'CMD', 'CMD-SHELL'):
  419. raise ConfigurationError(
  420. 'Service "{}" defines an invalid healthcheck: '
  421. 'when "test" is a list the first item must be either NONE, CMD or CMD-SHELL'
  422. .format(service_config.name))