No Description
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

validator.py 15KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458
  1. #-*- coding: utf-8 -*-
  2. import sys
  3. import os.path
  4. import re
  5. import socket
  6. import inspect
  7. import copy
  8. from lodel.context import LodelContext
  9. LodelContext.expose_modules(globals(), {
  10. 'lodel.exceptions': ['LodelException', 'LodelExceptions',
  11. 'LodelFatalError', 'FieldValidationError']})
  12. ## @package lodel.settings.validator Lodel2 settings validators/cast module
  13. #
  14. # Validator are registered in the SettingValidator class.
  15. # @note to get a list of registered default validators just run
  16. # <pre>$ python scripts/settings_validator.py</pre>
  17. ##@brief Exception class that should be raised when a validation fails
  18. class SettingsValidationError(Exception):
  19. pass
  20. ##@brief Handles settings validators
  21. #
  22. # Class instance are callable objects that takes a value argument (the value to validate). It raises
  23. # a SettingsValidationError if validation fails, else it returns a properly
  24. # casted value.
  25. #@todo implement an IP validator and use it in multisite confspec
  26. class SettingValidator(object):
  27. _validators = dict()
  28. _description = dict()
  29. ##@brief Instanciate a validator
  30. #@param name str : validator name
  31. #@param none_is_valid bool : if True None will be validated
  32. #@param **kwargs : more arguement for the validator
  33. def __init__(self, name, none_is_valid = False, **kwargs):
  34. if name is not None and name not in self._validators:
  35. raise LodelFatalError("No validator named '%s'" % name)
  36. self.__none_is_valid = none_is_valid
  37. self.__name = name
  38. self._opt_args = kwargs
  39. ##@brief Call the validator
  40. # @param value *
  41. # @return properly casted value
  42. # @throw SettingsValidationError
  43. def __call__(self, value):
  44. if self.__none_is_valid and value is None:
  45. return None
  46. try:
  47. ret = self._validators[self.__name](value, **self._opt_args)
  48. return ret
  49. except Exception as e:
  50. raise SettingsValidationError(e)
  51. ##@brief Register a new validator
  52. # @param name str : validator name
  53. # @param callback callable : the function that will validate a value
  54. # @param description str
  55. @classmethod
  56. def register_validator(cls, name, callback, description=None):
  57. if name in cls._validators:
  58. raise NameError("A validator named '%s' allready exists" % name)
  59. # Broken test for callable
  60. if not inspect.isfunction(callback) and not inspect.ismethod(callback) and not hasattr(callback, '__call__'):
  61. raise TypeError("Callable expected but got %s" % type(callback))
  62. cls._validators[name] = callback
  63. cls._description[name] = description
  64. ##@brief Get the validator list associated with description
  65. @classmethod
  66. def validators_list(cls):
  67. return copy.copy(cls._description)
  68. ##@brief Create and register a list validator
  69. # @param elt_validator callable : The validator that will be used for validate each elt value
  70. # @param validator_name str
  71. # @param description None | str
  72. # @param separator str : The element separator
  73. # @return A SettingValidator instance
  74. @classmethod
  75. def create_list_validator(cls, validator_name, elt_validator, description = None, separator = ','):
  76. def list_validator(value):
  77. res = list()
  78. errors = list()
  79. for elt in value.split(separator):
  80. elt = elt_validator(elt)
  81. if len(elt) > 0:
  82. res.append(elt)
  83. return res
  84. description = "Convert value to an array" if description is None else description
  85. cls.register_validator(
  86. validator_name,
  87. list_validator,
  88. description)
  89. return cls(validator_name)
  90. ##@brief Create and register a list validator which reads an array and returns a string
  91. # @param elt_validator callable : The validator that will be used for validate each elt value
  92. # @param validator_name str
  93. # @param description None | str
  94. # @param separator str : The element separator
  95. # @return A SettingValidator instance
  96. @classmethod
  97. def create_write_list_validator(cls, validator_name, elt_validator, description = None, separator = ','):
  98. def write_list_validator(value):
  99. res = ''
  100. errors = list()
  101. for elt in value:
  102. res += elt_validator(elt) + ','
  103. return res[:len(res)-1]
  104. description = "Convert value to a string" if description is None else description
  105. cls.register_validator(
  106. validator_name,
  107. write_list_validator,
  108. description)
  109. return cls(validator_name)
  110. ##@brief Create and register a regular expression validator
  111. # @param pattern str : regex pattern
  112. # @param validator_name str : The validator name
  113. # @param description str : Validator description
  114. # @return a SettingValidator instance
  115. @classmethod
  116. def create_re_validator(cls, pattern, validator_name, description = None):
  117. def re_validator(value):
  118. if not re.match(pattern, value):
  119. raise SettingsValidationError("The value '%s' doesn't match the following pattern '%s'" % pattern)
  120. return value
  121. #registering the validator
  122. cls.register_validator(
  123. validator_name,
  124. re_validator,
  125. ("Match value to '%s'" % pattern) if description is None else description)
  126. return cls(validator_name)
  127. ## @return a list of registered validators
  128. @classmethod
  129. def validators_list_str(cls):
  130. result = ''
  131. for name in sorted(cls._validators.keys()):
  132. result += "\t%016s" % name
  133. if name in cls._description and cls._description[name] is not None:
  134. result += ": %s" % cls._description[name]
  135. result += "\n"
  136. return result
  137. ##@brief Integer value validator callback
  138. def int_val(value):
  139. return int(value)
  140. ##@brief Output file validator callback
  141. # @return A file object (if filename is '-' return sys.stderr)
  142. def file_err_output(value):
  143. if not isinstance(value, str):
  144. raise SettingsValidationError("A string was expected but got '%s' " % value)
  145. if value == '-':
  146. return None
  147. return value
  148. ##@brief Boolean value validator callback
  149. def boolean_val(value):
  150. if isinstance(value, bool):
  151. return value
  152. if value.strip().lower() == 'true' or value.strip() == '1':
  153. value = True
  154. elif value.strip().lower() == 'false' or value.strip() == '0':
  155. value = False
  156. else:
  157. raise SettingsValidationError("A boolean was expected but got '%s' " % value)
  158. return bool(value)
  159. ##@brief Validate a directory path
  160. def directory_val(value):
  161. res = SettingValidator('strip')(value)
  162. if not os.path.isdir(res):
  163. raise SettingsValidationError("Folowing path don't exists or is not a directory : '%s'"%res)
  164. return res
  165. ##@brief Validate a loglevel value
  166. def loglevel_val(value):
  167. valids = ['DEBUG', 'INFO', 'WARNING', 'SECURITY', 'ERROR', 'CRITICAL']
  168. if value.upper() not in valids:
  169. raise SettingsValidationError(
  170. "The value '%s' is not a valid loglevel" % value)
  171. return value.upper()
  172. ##@brief Validate a path
  173. def path_val(value):
  174. if value is None or not os.path.exists(value):
  175. raise SettingsValidationError(
  176. "path '%s' doesn't exists" % value)
  177. return value
  178. ##@brief Validate None
  179. def none_val(value):
  180. if value is None:
  181. return None
  182. raise SettingsValidationError("This settings cannot be set in configuration file")
  183. ##@brief Validate a string
  184. def str_val(value):
  185. try:
  186. return str(value)
  187. except Exception as e:
  188. raise SettingsValidationError("Not able to convert value to string : " + str(e))
  189. ##@brief Validate using a regex
  190. def regex_val(value, pattern):
  191. if re.match(pattern, value) is None:
  192. raise SettingsValidationError("The value '%s' is not validated by : \
  193. r\"%s\"" %(value, pattern))
  194. return value
  195. ##@brief Validate a hostname (ipv4 or ipv6)
  196. def host_val(value):
  197. if value == 'localhost':
  198. return value
  199. ok = False
  200. try:
  201. socket.inet_aton(value)
  202. return value
  203. except (TypeError,OSError):
  204. pass
  205. try:
  206. socket.inet_pton(socket.AF_INET6, value)
  207. return value
  208. except (TypeError,OSError):
  209. pass
  210. try:
  211. socket.getaddrinfo(value, 80)
  212. return value
  213. except (TypeError,socket.gaierror):
  214. msg = "The value '%s' is not a valid host"
  215. raise SettingsValidationError(msg % value)
  216. ##@brief Validator for Editorial model component
  217. #
  218. # Designed to validate a conf that indicate a class.field in an EM
  219. #@todo modified the hardcoded dyncode import (it's a warning)
  220. def emfield_val(value):
  221. LodelContext.expose_modules(globals(), {
  222. 'lodel.plugin.hooks': ['LodelHook']})
  223. spl = value.split('.')
  224. if len(spl) != 2:
  225. msg = "Expected a value in the form CLASSNAME.FIELDNAME but got : %s"
  226. raise SettingsValidationError(msg % value)
  227. value = tuple(spl)
  228. #Late validation hook
  229. @LodelHook('lodel2_dyncode_bootstraped')
  230. def emfield_conf_check(hookname, caller, payload):
  231. import leapi_dyncode as dyncode # <-- dirty & quick
  232. classnames = { cls.__name__.lower():cls for cls in dyncode.dynclasses}
  233. if value[0].lower() not in classnames:
  234. msg = "Following dynamic class do not exists in current EM : %s"
  235. raise SettingsValidationError(msg % value[0])
  236. ccls = classnames[value[0].lower()]
  237. if value[1].lower() not in ccls.fieldnames(True):
  238. msg = "Following field not found in class %s : %s"
  239. raise SettingsValidationError(msg % value)
  240. return value
  241. ##@brief Validator for plugin name & optionnaly type
  242. #
  243. #Able to check that the value is a plugin and if it is of a specific type
  244. def plugin_validator(value, ptype = None):
  245. LodelContext.expose_modules(globals(), {
  246. 'lodel.plugin.hooks': ['LodelHook']})
  247. value = copy.copy(value)
  248. @LodelHook('lodel2_dyncode_bootstraped')
  249. def plugin_type_checker(hookname, caller, payload):
  250. LodelContext.expose_modules(globals(), {
  251. 'lodel.plugin.plugins': ['Plugin'],
  252. 'lodel.plugin.exceptions': ['PluginError']})
  253. if value is None:
  254. return
  255. try:
  256. plugin = Plugin.get(value)
  257. except PluginError:
  258. msg = "No plugin named %s found"
  259. msg %= value
  260. raise SettingsValidationError(msg)
  261. if plugin._type_conf_name.lower() != ptype.lower():
  262. msg = "A plugin of type '%s' was expected but found a plugin \
  263. named '%s' that is a '%s' plugin"
  264. msg %= (ptype, value, plugin._type_conf_name)
  265. raise SettingsValidationError(msg)
  266. return value
  267. def custom_list_validator(value, validator_name, validator_kwargs = None):
  268. validator_kwargs = dict() if validator_kwargs is None else validator_kwargs
  269. validator = SettingValidator(validator_name, **validator_kwargs)
  270. for item in value.split():
  271. validator(item)
  272. return value.split()
  273. #
  274. # Default validators registration
  275. #
  276. SettingValidator.register_validator(
  277. 'plugin',
  278. plugin_validator,
  279. 'plugin name & type validator')
  280. SettingValidator.register_validator(
  281. 'custom_list',
  282. custom_list_validator,
  283. 'A list validator that takes a "validator_name" as argument')
  284. SettingValidator.register_validator(
  285. 'dummy',
  286. lambda value:value,
  287. 'Validate anything')
  288. SettingValidator.register_validator(
  289. 'none',
  290. none_val,
  291. 'Validate None')
  292. SettingValidator.register_validator(
  293. 'string',
  294. str_val,
  295. 'Validate string values')
  296. SettingValidator.register_validator(
  297. 'strip',
  298. str.strip,
  299. 'String trim')
  300. SettingValidator.register_validator(
  301. 'int',
  302. int_val,
  303. 'Integer value validator')
  304. SettingValidator.register_validator(
  305. 'bool',
  306. boolean_val,
  307. 'Boolean value validator')
  308. SettingValidator.register_validator(
  309. 'errfile',
  310. file_err_output,
  311. 'Error output file validator (return stderr if filename is "-")')
  312. SettingValidator.register_validator(
  313. 'directory',
  314. directory_val,
  315. 'Directory path validator')
  316. SettingValidator.register_validator(
  317. 'loglevel',
  318. loglevel_val,
  319. 'Loglevel validator')
  320. SettingValidator.register_validator(
  321. 'path',
  322. path_val,
  323. 'path validator')
  324. SettingValidator.register_validator(
  325. 'host',
  326. host_val,
  327. 'host validator')
  328. SettingValidator.register_validator(
  329. 'emfield',
  330. emfield_val,
  331. 'EmField name validator')
  332. SettingValidator.register_validator(
  333. 'regex',
  334. regex_val,
  335. 'RegEx name validator (take re as argument)')
  336. SettingValidator.create_list_validator(
  337. 'list',
  338. SettingValidator('strip'),
  339. description = "Simple list validator. Validate a list of values separated by ','",
  340. separator = ',')
  341. SettingValidator.create_list_validator(
  342. 'directory_list',
  343. SettingValidator('directory'),
  344. description = "Validator for a list of directory path separated with ','",
  345. separator = ',')
  346. SettingValidator.create_write_list_validator(
  347. 'write_list',
  348. SettingValidator('directory'),
  349. description = "Validator for an array of values which will be set in a string, separated by ','",
  350. separator = ',')
  351. SettingValidator.create_re_validator(
  352. r'^https?://[^\./]+.[^\./]+/?.*$',
  353. 'http_url',
  354. 'Url validator')
  355. #
  356. # Lodel 2 configuration specification
  357. #
  358. ##@brief Append a piece of confspec
  359. #@note orig is modified during the process
  360. #@param orig dict : the confspec to update
  361. #@param section str : section name
  362. #@param key str
  363. #@param validator SettingValidator : the validator to use to check this configuration key's value
  364. #@param default
  365. #@return new confspec
  366. def confspec_append(orig, section, key, validator, default):
  367. if section not in orig:
  368. orig[section] = dict()
  369. if key not in orig[section]:
  370. orig[section][key] = (default, validator)
  371. return orig
  372. ##@brief Global specifications for lodel2 settings
  373. LODEL2_CONF_SPECS = {
  374. 'lodel2': {
  375. 'debug': ( True,
  376. SettingValidator('bool')),
  377. 'sitename': ( 'noname',
  378. SettingValidator('strip')),
  379. 'runtest': ( False,
  380. SettingValidator('bool')),
  381. },
  382. 'lodel2.logging.*' : {
  383. 'level': ( 'ERROR',
  384. SettingValidator('loglevel')),
  385. 'context': ( False,
  386. SettingValidator('bool')),
  387. 'filename': ( "-",
  388. SettingValidator('errfile', none_is_valid = False)),
  389. 'backupcount': ( 5,
  390. SettingValidator('int', none_is_valid = False)),
  391. 'maxbytes': ( 1024*10,
  392. SettingValidator('int', none_is_valid = False)),
  393. },
  394. 'lodel2.editorialmodel': {
  395. 'emfile': ( 'em.pickle', SettingValidator('strip')),
  396. 'emtranslator': ( 'picklefile', SettingValidator('strip')),
  397. 'dyncode': ( 'leapi_dyncode.py', SettingValidator('strip')),
  398. 'groups': ( '', SettingValidator('list')),
  399. 'editormode': ( False, SettingValidator('bool')),
  400. },
  401. 'lodel2.datasources.*': {
  402. 'read_only': (False, SettingValidator('bool')),
  403. 'identifier': ( None, SettingValidator('string')),
  404. },
  405. 'lodel2.auth': {
  406. 'login_classfield': ('user.login', SettingValidator('emfield')),
  407. 'pass_classfield': ('user.password', SettingValidator('emfield')),
  408. },
  409. }