1
0

validation.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537
  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. VALID_IPV4_SEG = r'(\d{1,2}|1\d{2}|2[0-4]\d|25[0-5])'
  38. VALID_REGEX_IPV4_CIDR = r'^(\d|[1-2]\d|3[0-2])$'
  39. VALID_IPV4_ADDR = "({IPV4_SEG}\.){{3}}{IPV4_SEG}".format(IPV4_SEG=VALID_IPV4_SEG)
  40. VALID_REGEX_IPV4_ADDR = "^{IPV4_ADDR}$".format(IPV4_ADDR=VALID_IPV4_ADDR)
  41. VALID_IPV6_SEG = r'[0-9a-fA-F]{1,4}'
  42. VALID_REGEX_IPV6_CIDR = r'^(\d|[1-9]\d|1[0-1]\d|12[0-8])$'
  43. VALID_REGEX_IPV6_ADDR = "".join("""
  44. ^
  45. (
  46. (({IPV6_SEG}:){{7}}{IPV6_SEG})|
  47. (({IPV6_SEG}:){{1,7}}:)|
  48. (({IPV6_SEG}:){{1,6}}(:{IPV6_SEG}){{1,1}})|
  49. (({IPV6_SEG}:){{1,5}}(:{IPV6_SEG}){{1,2}})|
  50. (({IPV6_SEG}:){{1,4}}(:{IPV6_SEG}){{1,3}})|
  51. (({IPV6_SEG}:){{1,3}}(:{IPV6_SEG}){{1,4}})|
  52. (({IPV6_SEG}:){{1,2}}(:{IPV6_SEG}){{1,5}})|
  53. (({IPV6_SEG}:){{1,1}}(:{IPV6_SEG}){{1,6}})|
  54. (:((:{IPV6_SEG}){{1,7}}|:))|
  55. (fe80:(:{IPV6_SEG}){{0,4}}%[0-9a-zA-Z]{{1,}})|
  56. (::(ffff(:0{{1,4}}){{0,1}}:){{0,1}}{IPV4_ADDR})|
  57. (({IPV6_SEG}:){{1,4}}:{IPV4_ADDR})
  58. )
  59. $
  60. """.format(IPV6_SEG=VALID_IPV6_SEG, IPV4_ADDR=VALID_IPV4_ADDR).split())
  61. @FormatChecker.cls_checks(format="ports", raises=ValidationError)
  62. def format_ports(instance):
  63. try:
  64. split_port(instance)
  65. except ValueError as e:
  66. raise ValidationError(six.text_type(e))
  67. return True
  68. @FormatChecker.cls_checks(format="expose", raises=ValidationError)
  69. def format_expose(instance):
  70. if isinstance(instance, six.string_types):
  71. if not re.match(VALID_EXPOSE_FORMAT, instance):
  72. raise ValidationError(
  73. "should be of the format 'PORT[/PROTOCOL]'")
  74. return True
  75. @FormatChecker.cls_checks("subnet_ip_address", raises=ValidationError)
  76. def format_subnet_ip_address(instance):
  77. if isinstance(instance, six.string_types):
  78. if '/' not in instance:
  79. raise ValidationError("should be of the format 'IP_ADDRESS/CIDR'")
  80. ip_address, cidr = instance.split('/')
  81. if re.match(VALID_REGEX_IPV4_ADDR, ip_address):
  82. if not re.match(VALID_REGEX_IPV4_CIDR, cidr):
  83. raise ValidationError("should be of the format 'IP_ADDRESS/CIDR'")
  84. elif re.match(VALID_REGEX_IPV6_ADDR, ip_address):
  85. if not re.match(VALID_REGEX_IPV6_CIDR, cidr):
  86. raise ValidationError("should be of the format 'IP_ADDRESS/CIDR'")
  87. else:
  88. raise ValidationError("should be of the format 'IP_ADDRESS/CIDR'")
  89. return True
  90. def match_named_volumes(service_dict, project_volumes):
  91. service_volumes = service_dict.get('volumes', [])
  92. for volume_spec in service_volumes:
  93. if volume_spec.is_named_volume and volume_spec.external not in project_volumes:
  94. raise ConfigurationError(
  95. 'Named volume "{0}" is used in service "{1}" but no'
  96. ' declaration was found in the volumes section.'.format(
  97. volume_spec.repr(), service_dict.get('name')
  98. )
  99. )
  100. def python_type_to_yaml_type(type_):
  101. type_name = type(type_).__name__
  102. return {
  103. 'dict': 'mapping',
  104. 'list': 'array',
  105. 'int': 'number',
  106. 'float': 'number',
  107. 'bool': 'boolean',
  108. 'unicode': 'string',
  109. 'str': 'string',
  110. 'bytes': 'string',
  111. }.get(type_name, type_name)
  112. def validate_config_section(filename, config, section):
  113. """Validate the structure of a configuration section. This must be done
  114. before interpolation so it's separate from schema validation.
  115. """
  116. if not isinstance(config, dict):
  117. raise ConfigurationError(
  118. "In file '{filename}', {section} must be a mapping, not "
  119. "{type}.".format(
  120. filename=filename,
  121. section=section,
  122. type=anglicize_json_type(python_type_to_yaml_type(config))))
  123. for key, value in config.items():
  124. if not isinstance(key, six.string_types):
  125. raise ConfigurationError(
  126. "In file '{filename}', the {section} name {name} must be a "
  127. "quoted string, i.e. '{name}'.".format(
  128. filename=filename,
  129. section=section,
  130. name=key))
  131. if not isinstance(value, (dict, type(None))):
  132. raise ConfigurationError(
  133. "In file '{filename}', {section} '{name}' must be a mapping not "
  134. "{type}.".format(
  135. filename=filename,
  136. section=section,
  137. name=key,
  138. type=anglicize_json_type(python_type_to_yaml_type(value))))
  139. def validate_top_level_object(config_file):
  140. if not isinstance(config_file.config, dict):
  141. raise ConfigurationError(
  142. "Top level object in '{}' needs to be an object not '{}'.".format(
  143. config_file.filename,
  144. type(config_file.config)))
  145. def validate_ulimits(service_config):
  146. ulimit_config = service_config.config.get('ulimits', {})
  147. for limit_name, soft_hard_values in six.iteritems(ulimit_config):
  148. if isinstance(soft_hard_values, dict):
  149. if not soft_hard_values['soft'] <= soft_hard_values['hard']:
  150. raise ConfigurationError(
  151. "Service '{s.name}' has invalid ulimit '{ulimit}'. "
  152. "'soft' value can not be greater than 'hard' value ".format(
  153. s=service_config,
  154. ulimit=ulimit_config))
  155. def validate_extends_file_path(service_name, extends_options, filename):
  156. """
  157. The service to be extended must either be defined in the config key 'file',
  158. or within 'filename'.
  159. """
  160. error_prefix = "Invalid 'extends' configuration for %s:" % service_name
  161. if 'file' not in extends_options and filename is None:
  162. raise ConfigurationError(
  163. "%s you need to specify a 'file', e.g. 'file: something.yml'" % error_prefix
  164. )
  165. def validate_network_mode(service_config, service_names):
  166. network_mode = service_config.config.get('network_mode')
  167. if not network_mode:
  168. return
  169. if 'networks' in service_config.config:
  170. raise ConfigurationError("'network_mode' and 'networks' cannot be combined")
  171. dependency = get_service_name_from_network_mode(network_mode)
  172. if not dependency:
  173. return
  174. if dependency not in service_names:
  175. raise ConfigurationError(
  176. "Service '{s.name}' uses the network stack of service '{dep}' which "
  177. "is undefined.".format(s=service_config, dep=dependency))
  178. def validate_pid_mode(service_config, service_names):
  179. pid_mode = service_config.config.get('pid')
  180. if not pid_mode:
  181. return
  182. dependency = get_service_name_from_network_mode(pid_mode)
  183. if not dependency:
  184. return
  185. if dependency not in service_names:
  186. raise ConfigurationError(
  187. "Service '{s.name}' uses the PID namespace of service '{dep}' which "
  188. "is undefined.".format(s=service_config, dep=dependency)
  189. )
  190. def validate_links(service_config, service_names):
  191. for link in service_config.config.get('links', []):
  192. if link.split(':')[0] not in service_names:
  193. raise ConfigurationError(
  194. "Service '{s.name}' has a link to service '{link}' which is "
  195. "undefined.".format(s=service_config, link=link))
  196. def validate_depends_on(service_config, service_names):
  197. deps = service_config.config.get('depends_on', {})
  198. for dependency in deps.keys():
  199. if dependency not in service_names:
  200. raise ConfigurationError(
  201. "Service '{s.name}' depends on service '{dep}' which is "
  202. "undefined.".format(s=service_config, dep=dependency)
  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. return error.message.split("'")[1]
  272. def path_string(path):
  273. return ".".join(c for c in path if isinstance(c, six.string_types))
  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))