validation.py 19 KB

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