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

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