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 14KB

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