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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254
  1. #-*- coding: utf-8 -*-
  2. import sys
  3. import os.path
  4. import re
  5. import inspect
  6. import copy
  7. ## @package lodel.settings.validator Lodel2 settings validators/cast module
  8. #
  9. # Validator are registered in the SettingValidator class.
  10. # @note to get a list of registered default validators just run
  11. # <pre>$ python scripts/settings_validator.py</pre>
  12. ##@brief Exception class that should be raised when a validation fails
  13. class SettingsValidationError(Exception):
  14. pass
  15. ##@brief Handles settings validators
  16. #
  17. # Class instance are callable objects that takes a value argument (the value to validate). It raises
  18. # a SettingsValidationError if validation fails, else it returns a properly
  19. # casted value.
  20. class SettingValidator(object):
  21. _validators = dict()
  22. _description = dict()
  23. ##@brief Instanciate a validator
  24. def __init__(self, name, none_is_valid = False):
  25. if name is not None and name not in self._validators:
  26. raise NameError("No validator named '%s'" % name)
  27. self.__name = name
  28. ##@brief Call the validator
  29. # @param value *
  30. # @return properly casted value
  31. # @throw SettingsValidationError
  32. def __call__(self, value):
  33. if self.__name is None:
  34. return value
  35. try:
  36. return self._validators[self.__name](value)
  37. except Exception as e:
  38. raise SettingsValidationError(e)
  39. ##@brief Register a new validator
  40. # @param name str : validator name
  41. # @param callback callable : the function that will validate a value
  42. @classmethod
  43. def register_validator(cls, name, callback, description=None):
  44. if name in cls._validators:
  45. raise NameError("A validator named '%s' allready exists" % name)
  46. # Broken test for callable
  47. if not inspect.isfunction(callback) and not inspect.ismethod(callback) and not hasattr(callback, '__call__'):
  48. raise TypeError("Callable expected but got %s" % type(callback))
  49. cls._validators[name] = callback
  50. cls._description[name] = description
  51. ##@brief Get the validator list associated with description
  52. @classmethod
  53. def validators_list(cls):
  54. return copy.copy(cls._description)
  55. ##@brief Create and register a list validator
  56. # @param elt_validator callable : The validator that will be used for validate each elt value
  57. # @param validator_name str
  58. # @param description None | str
  59. # @param separator str : The element separator
  60. # @return A SettingValidator instance
  61. @classmethod
  62. def create_list_validator(cls, validator_name, elt_validator, description = None, separator = ','):
  63. def list_validator(value):
  64. res = list()
  65. errors = list()
  66. for elt in value.split(separator):
  67. res.append(elt_validator(elt))
  68. return res
  69. description = "Convert value to an array" if description is None else description
  70. cls.register_validator(
  71. validator_name,
  72. list_validator,
  73. description)
  74. return cls(validator_name)
  75. ##@brief Create and register a regular expression validator
  76. # @param pattern str : regex pattern
  77. # @param validator_name str : The validator name
  78. # @param description str : Validator description
  79. # @return a SettingValidator instance
  80. @classmethod
  81. def create_re_validator(cls, pattern, validator_name, description = None):
  82. def re_validator(value):
  83. if not re.match(pattern, value):
  84. raise SettingsValidationError("The value '%s' doesn't match the following pattern '%s'" % pattern)
  85. return value
  86. #registering the validator
  87. cls.register_validator(
  88. validator_name,
  89. re_validator,
  90. ("Match value to '%s'" % pattern) if description is None else description)
  91. return cls(validator_name)
  92. ## @return a list of registered validators
  93. @classmethod
  94. def validators_list_str(cls):
  95. result = ''
  96. for name in sorted(cls._validators.keys()):
  97. result += "\t%016s" % name
  98. if name in cls._description and cls._description[name] is not None:
  99. result += ": %s" % cls._description[name]
  100. result += "\n"
  101. return result
  102. ##@brief Integer value validator callback
  103. def int_val(value):
  104. return int(value)
  105. ##@brief Output file validator callback
  106. # @return A file object (if filename is '-' return sys.stderr)
  107. def file_err_output(value):
  108. if not isinstance(value, str):
  109. raise SettingsValidationError("A string was expected but got '%s' " % value)
  110. if value == '-':
  111. return None
  112. return value
  113. ##@brief Boolean value validator callback
  114. def boolean_val(value):
  115. if value.strip().lower() == 'true' or value.strip() == '1':
  116. value = True
  117. elif value.strip().lower() == 'false' or value.strip() == '0':
  118. value = False
  119. else:
  120. raise SettingsValidationError("A boolean was expected but got '%s' " % value)
  121. return bool(value)
  122. def directory_val(value):
  123. res = SettingValidator('strip')(value)
  124. if not os.path.isdir(res):
  125. raise SettingsValidationError("Folowing path don't exists or is not a directory : '%s'"%res)
  126. return res
  127. def loglevel_val(value):
  128. valids = ['DEBUG', 'INFO', 'SECURITY', 'ERROR', 'CRITICAL']
  129. if value.upper() not in valids:
  130. raise SettingsValidationError("The value '%s' is not a valid loglevel")
  131. return value.upper()
  132. def path_val(value):
  133. if not os.path.exists(value):
  134. raise SettingsValidationError("The value '%s' is not a valid path")
  135. return value
  136. #
  137. # Default validators registration
  138. #
  139. SettingValidator.register_validator(
  140. 'strip',
  141. str.strip,
  142. 'String trim')
  143. SettingValidator.register_validator(
  144. 'int',
  145. int_val,
  146. 'Integer value validator')
  147. SettingValidator.register_validator(
  148. 'bool',
  149. boolean_val,
  150. 'Boolean value validator')
  151. SettingValidator.register_validator(
  152. 'errfile',
  153. file_err_output,
  154. 'Error output file validator (return stderr if filename is "-")')
  155. SettingValidator.register_validator(
  156. 'directory',
  157. directory_val,
  158. 'Directory path validator')
  159. SettingValidator.register_validator(
  160. 'loglevel',
  161. loglevel_val,
  162. 'Loglevel validator')
  163. SettingValidator.register_validator(
  164. 'path',
  165. path_val,
  166. 'path validator')
  167. SettingValidator.create_list_validator(
  168. 'list',
  169. SettingValidator('strip'),
  170. description = "Simple list validator. Validate a list of values separated by ','",
  171. separator = ',')
  172. SettingValidator.create_list_validator(
  173. 'directory_list',
  174. SettingValidator('directory'),
  175. description = "Validator for a list of directory path separated with ','",
  176. separator = ',')
  177. SettingValidator.create_re_validator(
  178. r'^https?://[^\./]+.[^\./]+/?.*$',
  179. 'http_url',
  180. 'Url validator')
  181. #
  182. # Lodel 2 configuration specification
  183. #
  184. ##@brief Global specifications for lodel2 settings
  185. LODEL2_CONF_SPECS = {
  186. 'lodel2': {
  187. 'debug': ( True,
  188. SettingValidator('bool')),
  189. 'plugins_path': ( None,
  190. SettingValidator('list')),
  191. 'plugins': ( "",
  192. SettingValidator('list')),
  193. 'sitename': ( 'noname',
  194. SettingValidator('strip')),
  195. 'lib_path': ( None,
  196. SettingValidator('path')),
  197. },
  198. 'lodel2.logging.*' : {
  199. 'level': ( 'ERROR',
  200. SettingValidator('loglevel')),
  201. 'context': ( False,
  202. SettingValidator('bool')),
  203. 'filename': ( None,
  204. SettingValidator('errfile', none_is_valid = True)),
  205. 'backupcount': ( None,
  206. SettingValidator('int', none_is_valid = True)),
  207. 'maxbytes': ( None,
  208. SettingValidator('int', none_is_valid = True)),
  209. },
  210. 'lodel2.editorialmodel': {
  211. 'emfile': ( 'em.pickle',
  212. SettingValidator('strip')),
  213. 'emtranslator': ( 'picklefile',
  214. SettingValidator('strip')),
  215. 'dyncode': ( 'leapi_dyncode.py',
  216. SettingValidator('strip')),
  217. 'groups': ( '',
  218. SettingValidator('list')),
  219. 'editormode': ( False,
  220. SettingValidator('bool')),
  221. }
  222. }