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.

settings.py 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  1. #-*- coding: utf-8 -*-
  2. import sys
  3. import os
  4. import configparser
  5. import copy
  6. import warnings
  7. import types # for dynamic bindings
  8. from collections import namedtuple
  9. from lodel.context import LodelContext
  10. LodelContext.expose_modules(globals(),{
  11. 'lodel.logger': 'logger',
  12. 'lodel.settings.utils': ['SettingsError', 'SettingsErrors'],
  13. 'lodel.settings.validator': ['SettingValidator', 'LODEL2_CONF_SPECS',
  14. 'confspec_append'],
  15. 'lodel.settings.settings_loader':['SettingsLoader']})
  16. ## @package lodel.settings.settings Lodel2 settings module
  17. #
  18. # Contains the class that handles the namedtuple tree of settings
  19. ##@brief A default python system lib path
  20. PYTHON_SYS_LIB_PATH = '/usr/local/lib/python{major}.{minor}/'.format(
  21. major = sys.version_info.major,
  22. minor = sys.version_info.minor)
  23. class MetaSettings(type):
  24. @property
  25. def s(self):
  26. self.singleton_assert(True)
  27. return self.instance.settings
  28. ##@brief Handles configuration load etc.
  29. #
  30. # To see howto bootstrap Settings and use it in lodel instance see
  31. # @ref lodel.settings
  32. #
  33. # @par Basic instance usage
  34. # For example if a file defines confs like :
  35. # <pre>
  36. # [super_section]
  37. # super_conf = super_value
  38. # </pre>
  39. # You can access it with :
  40. # <pre> settings_instance.confs.super_section.super_conf </pre>
  41. #
  42. # @par Init sequence
  43. # The initialization sequence is a bit tricky. In fact, plugins adds allowed
  44. # configuration sections/values, but the list of plugins to load are in... the
  45. # settings.
  46. # Here is the conceptual presentation of Settings class initialization stages :
  47. # -# Preloading (sets values like lodel2 library path or the plugins path)
  48. # -# Ask a @ref lodel.settings.setting_loader.SettingsLoader to load all
  49. #configurations files
  50. # -# Fetch the list of plugins in the loaded settings
  51. # -# Merge plugins settings specification with the global lodel settings
  52. #specs ( see @ref lodel.plugin )
  53. # -# Fetch all settings from the merged settings specs
  54. #
  55. # @par Init sequence in practical
  56. # In practice those steps are done by calling a succession of private methods :
  57. # -# @ref Settings.__bootstrap() ( steps 1 to 3 )
  58. # -# @ref Settings.__merge_specs() ( step 4 )
  59. # -# @ref Settings.__populate_from_specs() (step 5)
  60. # -# And finally @ref Settings.__confs_to_namedtuple()
  61. #
  62. # @todo handles default sections for variable sections (sections ending with
  63. # '.*')
  64. # @todo delete the first stage, the lib path HAVE TO BE HARDCODED. In fact
  65. #when we will run lodel in production the lodel2 lib will be in the python path
  66. #@todo add log messages (now we can)
  67. class Settings(object, metaclass=MetaSettings):
  68. ## @brief Stores the singleton instance
  69. instance = None
  70. ## @brief Instanciate the Settings singleton
  71. # @param conf_dir str : The configuration directory
  72. def __init__(self, conf_dir):
  73. self.singleton_assert() # check that it is the only instance
  74. Settings.instance = self
  75. ## @brief Configuration specification
  76. #
  77. # Initialized by Settings.__bootstrap() method
  78. self.__conf_specs = None
  79. ## @brief Stores the configurations in namedtuple tree
  80. self.__confs = None
  81. self.__conf_dir = conf_dir
  82. self.__started = False
  83. self.__bootstrap()
  84. ## @brief Get the named tuple representing configuration
  85. @property
  86. def settings(self):
  87. return self.__confs.lodel2
  88. ## @brief Delete the singleton instance
  89. @classmethod
  90. def stop(cls):
  91. del(cls.instance)
  92. cls.instance = None
  93. @classmethod
  94. def started(cls):
  95. return cls.instance is not None and cls.instance.__started
  96. ##@brief An utility method that raises if the singleton is not in a good
  97. # state
  98. #@param expect_instanciated bool : if True we expect that the class is
  99. # allready instanciated, else not
  100. # @throw RuntimeError
  101. @classmethod
  102. def singleton_assert(cls, expect_instanciated=False):
  103. if expect_instanciated:
  104. if not cls.started():
  105. raise RuntimeError("The Settings class is not started yet")
  106. else:
  107. if cls.started():
  108. raise RuntimeError("The Settings class is already started")
  109. ##@brief Saves a new configuration for section confname
  110. #@param confname is the name of the modified section
  111. #@param confvalue is a dict with variables to save
  112. #@param validator is a dict with adapted validator
  113. @classmethod
  114. def set(cls, confname, confvalue,validator):
  115. loader = SettingsLoader(cls.instance.__conf_dir)
  116. confkey=confname.rpartition('.')
  117. loader.setoption(confkey[0], confkey[2], confvalue, validator)
  118. ##@brief This method handles Settings instance bootstraping
  119. def __bootstrap(self):
  120. LodelContext.expose_modules(globals(), {
  121. 'lodel.plugin.plugins': ['Plugin', 'PluginError']})
  122. logger.debug("Settings bootstraping")
  123. lodel2_specs = LODEL2_CONF_SPECS
  124. loader = SettingsLoader(self.__conf_dir)
  125. plugin_list = []
  126. for ptype_name,ptype in Plugin.plugin_types().items():
  127. pls = ptype.plist_confspecs()
  128. lodel2_specs = confspec_append(lodel2_specs, **pls)
  129. cur_list = loader.getoption(
  130. pls['section'],
  131. pls['key'],
  132. pls['validator'],
  133. pls['default'])
  134. if cur_list is None:
  135. continue
  136. try:
  137. if isinstance(cur_list, str):
  138. cur_list = [cur_list]
  139. plugin_list += cur_list
  140. except TypeError:
  141. plugin_list += [cur_list]
  142. #Checking confspecs
  143. for section in lodel2_specs:
  144. if section.lower() != section:
  145. raise SettingsError("Only lower case are allowed in section name (thank's ConfigParser...)")
  146. for kname in lodel2_specs[section]:
  147. if kname.lower() != kname:
  148. raise SettingsError("Only lower case are allowed in section name (thank's ConfigParser...)")
  149. # Starting the Plugins class
  150. logger.debug("Starting lodel.plugin.Plugin class")
  151. Plugin.start(plugin_list)
  152. # Fetching conf specs from plugins
  153. specs = [lodel2_specs]
  154. errors = list()
  155. for plugin_name in plugin_list:
  156. try:
  157. specs.append(Plugin.get(plugin_name).confspecs)
  158. except PluginError as e:
  159. errors.append(SettingsError(msg=str(e)))
  160. if len(errors) > 0: #Raise all plugins import errors
  161. raise SettingsErrors(errors)
  162. self.__conf_specs = self.__merge_specs(specs)
  163. self.__populate_from_specs(self.__conf_specs, loader)
  164. self.__started = True
  165. ##@brief Produce a configuration specification dict by merging all specifications
  166. #
  167. # Merges global lodel2 conf spec from @ref lodel.settings.validator.LODEL2_CONF_SPECS
  168. # and configuration specifications from loaded plugins
  169. # @param specs list : list of specifications dict
  170. # @return a specification dict
  171. def __merge_specs(self, specs):
  172. res = copy.copy(specs.pop())
  173. for spec in specs:
  174. for section in spec:
  175. if section.lower() != section:
  176. raise SettingsError("Only lower case are allowed in section name (thank's ConfigParser...)")
  177. if section not in res:
  178. res[section] = dict()
  179. for kname in spec[section]:
  180. if kname.lower() != kname:
  181. raise SettingsError("Only lower case are allowed in section name (thank's ConfigParser...)")
  182. if kname in res[section]:
  183. raise SettingsError("Duplicated key '%s' in section '%s'" % (kname, section))
  184. res[section.lower()][kname] = copy.copy(spec[section][kname])
  185. return res
  186. ##@brief Populate the Settings instance with options values fetched with the loader from merged specs
  187. #
  188. # Populate the __confs attribute
  189. # @param specs dict : Settings specification dictionnary as returned by __merge_specs
  190. # @param loader SettingsLoader : A SettingsLoader instance
  191. def __populate_from_specs(self, specs, loader):
  192. self.__confs = dict()
  193. specs = copy.copy(specs) #Avoid destroying original specs dict (may be useless)
  194. # Construct final specs dict replacing variable sections
  195. # by the actual existing sections
  196. variable_sections = [ section for section in specs if section.endswith('.*') ]
  197. for vsec in variable_sections:
  198. preffix = vsec[:-2]
  199. for section in loader.getsection(preffix, 'default'): #WARNING : hardcoded default section
  200. specs[section] = copy.copy(specs[vsec])
  201. del(specs[vsec])
  202. # Fetching values for sections
  203. for section in specs:
  204. for kname in specs[section]:
  205. validator = specs[section][kname][1]
  206. default = specs[section][kname][0]
  207. if section not in self.__confs:
  208. self.__confs[section] = dict()
  209. self.__confs[section][kname] = loader.getoption(section, kname, validator, default)
  210. # Checking unfectched values
  211. loader.raise_errors()
  212. self.__confs_to_namedtuple()
  213. pass
  214. ##@brief Transform the __confs attribute into imbricated namedtuple
  215. #
  216. # For example an option named "foo" in a section named "hello.world" will
  217. # be acessible with self.__confs.hello.world.foo
  218. def __confs_to_namedtuple(self):
  219. res = None
  220. end = False
  221. splits = list()
  222. for section in self.__confs:
  223. splits.append(section.split('.'))
  224. max_len = max([len(spl) for spl in splits])
  225. # building a tree from sections splits
  226. section_tree = dict()
  227. for spl in splits:
  228. section_name = ""
  229. cur = section_tree
  230. for sec_part in spl:
  231. section_name += sec_part+'.'
  232. if sec_part not in cur:
  233. cur[sec_part] = dict()
  234. cur = cur[sec_part]
  235. section_name = section_name[:-1]
  236. for kname, kval in self.__confs[section_name].items():
  237. if kname in cur:
  238. raise SettingsError("Duplicated key for '%s.%s'" % (section_name, kname))
  239. cur[kname] = kval
  240. path = [ ('root', section_tree) ]
  241. visited = set()
  242. curname = 'root'
  243. nodename = 'Lodel2Settings'
  244. cur = section_tree
  245. while True:
  246. visited.add(nodename)
  247. left = [ (kname, cur[kname])
  248. for kname in cur
  249. if nodename+'.'+kname.title() not in visited and isinstance(cur[kname], dict)
  250. ]
  251. if len(left) == 0:
  252. name, leaf = path.pop()
  253. typename = nodename.replace('.', '')
  254. if len(path) == 0:
  255. # END
  256. self.__confs = self.__tree2namedtuple(leaf,typename)
  257. break
  258. else:
  259. path[-1][1][name] = self.__tree2namedtuple(leaf,typename)
  260. nodename = '.'.join(nodename.split('.')[:-1])
  261. cur = path[-1][1]
  262. else:
  263. curname, cur = left[0]
  264. path.append( (curname, cur) )
  265. nodename += '.' + curname.title()
  266. ##@brief Forge a named tuple given a conftree node
  267. # @param conftree dict : A conftree node
  268. # @param name str
  269. # @return a named tuple with fieldnames corresponding to conftree keys
  270. def __tree2namedtuple(self, conftree, name):
  271. ResNamedTuple = namedtuple(name, conftree.keys())
  272. return ResNamedTuple(**conftree)
  273. class MetaSettingsRO(type):
  274. def __getattr__(self, name):
  275. return getattr(Settings.s, name)
  276. ## @brief A class that provide . notation read only access to configurations
  277. class SettingsRO(object, metaclass=MetaSettingsRO):
  278. pass