validation.py 19 KB

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