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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324
  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.logger import logger
  10. from lodel.settings.utils import SettingsError, SettingsErrors
  11. from lodel.settings.settings_loader import SettingsLoader
  12. from lodel.validator.validator import Validator, LODEL2_CONF_SPECS, confspec_append
  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 are 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. #@todo add log messages (now we can)
  64. class Settings(object, metaclass=MetaSettings):
  65. ## @brief Stores the singleton instance
  66. instance = None
  67. ## @brief Instanciate the Settings singleton
  68. # @param conf_dir str : The configuration directory
  69. #@param custom_confspecs None | dict : if given overwrite default lodel2
  70. # confspecs
  71. def __init__(self, conf_dir, custom_confspecs=None):
  72. self.singleton_assert() # check that it is the only instance
  73. Settings.instance = self
  74. #  @brief Configuration specification
  75. #
  76. # Initialized by Settings.__bootstrap() method
  77. self.__conf_specs = custom_confspecs
  78. #  @brief Stores the configurations in namedtuple tree
  79. self.__confs = None
  80. self.__conf_dir = conf_dir
  81. self.__started = False
  82. self.__bootstrap()
  83. ## @brief Get the named tuple representing configuration
  84. @property
  85. def settings(self):
  86. return self.__confs.lodel2
  87. ## @brief Delete the singleton instance
  88. @classmethod
  89. def stop(cls):
  90. del(cls.instance)
  91. cls.instance = None
  92. @classmethod
  93. def started(cls):
  94. return cls.instance is not None and cls.instance.__started
  95. ## @brief An utility method that raises if the singleton is not in a good
  96. # state
  97. #@param expect_instanciated bool : if True we expect that the class is
  98. # allready instanciated, else not
  99. # @throw RuntimeError
  100. @classmethod
  101. def singleton_assert(cls, expect_instanciated=False):
  102. if expect_instanciated:
  103. if not cls.started():
  104. raise RuntimeError("The Settings class is not started yet")
  105. else:
  106. if cls.started():
  107. raise RuntimeError("The Settings class is already started")
  108. ## @brief Saves a new configuration for section confname
  109. #@param confname is the name of the modified section
  110. #@param confvalue is a dict with variables to save
  111. #@param validator is a dict with adapted validator
  112. @classmethod
  113. def set(cls, confname, confvalue, validator):
  114. loader = SettingsLoader(cls.instance.__conf_dir)
  115. confkey = confname.rpartition('.')
  116. loader.setoption(confkey[0], confkey[2], confvalue, validator)
  117. # @brief This method handles Settings instance bootstraping
  118. def __bootstrap(self):
  119. from lodel.plugin.plugins import Plugin, PluginError
  120. logger.debug("Settings bootstraping")
  121. if self.__conf_specs is None:
  122. lodel2_specs = LODEL2_CONF_SPECS
  123. else:
  124. lodel2_specs = self.__conf_specs
  125. self.__conf_specs = None
  126. loader = SettingsLoader(self.__conf_dir)
  127. plugin_list = []
  128. for ptype_name, ptype in Plugin.plugin_types().items():
  129. pls = ptype.plist_confspecs()
  130. lodel2_specs = confspec_append(lodel2_specs, **pls)
  131. cur_list = loader.getoption(
  132. pls['section'],
  133. pls['key'],
  134. pls['validator'],
  135. pls['default'])
  136. if cur_list is None:
  137. continue
  138. try:
  139. if isinstance(cur_list, str):
  140. cur_list = [cur_list]
  141. plugin_list += cur_list
  142. except TypeError:
  143. plugin_list += [cur_list]
  144. # Remove invalid plugin names
  145. plugin_list = [plugin for plugin in plugin_list if len(plugin) > 0]
  146. # Checking confspecs
  147. for section in lodel2_specs:
  148. if section.lower() != section:
  149. raise SettingsError(
  150. "Only lower case are allowed in section name (thank's ConfigParser...)")
  151. for kname in lodel2_specs[section]:
  152. if kname.lower() != kname:
  153. raise SettingsError(
  154. "Only lower case are allowed in section name (thank's ConfigParser...)")
  155. # Starting the Plugins class
  156. logger.debug("Starting lodel.plugin.Plugin class")
  157. Plugin.start(plugin_list)
  158. # Fetching conf specs from plugins
  159. specs = [lodel2_specs]
  160. errors = list()
  161. for plugin_name in plugin_list:
  162. try:
  163. specs.append(Plugin.get(plugin_name).confspecs)
  164. except PluginError as e:
  165. errors.append(SettingsError(msg=str(e)))
  166. if len(errors) > 0: # Raise all plugins import errors
  167. raise SettingsErrors(errors)
  168. self.__conf_specs = self.__merge_specs(specs)
  169. self.__populate_from_specs(self.__conf_specs, loader)
  170. self.__started = True
  171. ## @brief Produce a configuration specification dict by merging all specifications
  172. #
  173. # Merges global lodel2 conf spec from @ref lodel.settings.validator.LODEL2_CONF_SPECS
  174. # and configuration specifications from loaded plugins
  175. # @param specs list : list of specifications dict
  176. # @return a specification dict
  177. def __merge_specs(self, specs):
  178. res = copy.copy(specs.pop())
  179. for spec in specs:
  180. for section in spec:
  181. if section.lower() != section:
  182. raise SettingsError(
  183. "Only lower case are allowed in section name (thank's ConfigParser...)")
  184. if section not in res:
  185. res[section] = dict()
  186. for kname in spec[section]:
  187. if kname.lower() != kname:
  188. raise SettingsError(
  189. "Only lower case are allowed in section name (thank's ConfigParser...)")
  190. if kname in res[section]:
  191. raise SettingsError("Duplicated key '%s' in section '%s'" %
  192. (kname, section))
  193. res[section.lower()][kname] = copy.copy(spec[section][kname])
  194. return res
  195. ## @brief Populate the Settings instance with options values fetched with the loader from merged specs
  196. #
  197. # Populate the __confs attribute
  198. # @param specs dict : Settings specification dictionnary as returned by __merge_specs
  199. # @param loader SettingsLoader : A SettingsLoader instance
  200. def __populate_from_specs(self, specs, loader):
  201. self.__confs = dict()
  202. specs = copy.copy(specs) # Avoid destroying original specs dict (may be useless)
  203. # Construct final specs dict replacing variable sections
  204. # by the actual existing sections
  205. variable_sections = [section for section in specs if section.endswith('.*')]
  206. for vsec in variable_sections:
  207. preffix = vsec[:-2]
  208. # WARNING : hardcoded default section
  209. for section in loader.getsection(preffix, 'default'):
  210. specs[section] = copy.copy(specs[vsec])
  211. del(specs[vsec])
  212. # Fetching values for sections
  213. for section in specs:
  214. for kname in specs[section]:
  215. validator = specs[section][kname][1]
  216. default = specs[section][kname][0]
  217. if section not in self.__confs:
  218. self.__confs[section] = dict()
  219. self.__confs[section][kname] = loader.getoption(section, kname, validator, default)
  220. # Checking unfectched values
  221. loader.raise_errors()
  222. self.__confs_to_namedtuple()
  223. pass
  224. ## @brief Transform the __confs attribute into imbricated namedtuple
  225. #
  226. # For example an option named "foo" in a section named "hello.world" will
  227. # be acessible with self.__confs.hello.world.foo
  228. def __confs_to_namedtuple(self):
  229. res = None
  230. end = False
  231. splits = list()
  232. for section in self.__confs:
  233. splits.append(section.split('.'))
  234. max_len = max([len(spl) for spl in splits])
  235. # building a tree from sections splits
  236. section_tree = dict()
  237. for spl in splits:
  238. section_name = ""
  239. cur = section_tree
  240. for sec_part in spl:
  241. section_name += sec_part + '.'
  242. if sec_part not in cur:
  243. cur[sec_part] = dict()
  244. cur = cur[sec_part]
  245. section_name = section_name[:-1]
  246. for kname, kval in self.__confs[section_name].items():
  247. if kname in cur:
  248. raise SettingsError("Duplicated key for '%s.%s'" % (section_name, kname))
  249. cur[kname] = kval
  250. path = [('root', section_tree)]
  251. visited = set()
  252. curname = 'root'
  253. nodename = 'Lodel2Settings'
  254. cur = section_tree
  255. while True:
  256. visited.add(nodename)
  257. left = [(kname, cur[kname])
  258. for kname in cur
  259. if nodename + '.' + kname.title() not in visited and isinstance(cur[kname], dict)
  260. ]
  261. if len(left) == 0:
  262. name, leaf = path.pop()
  263. typename = nodename.replace('.', '')
  264. if len(path) == 0:
  265. # END
  266. self.__confs = self.__tree2namedtuple(leaf, typename)
  267. break
  268. else:
  269. path[-1][1][name] = self.__tree2namedtuple(leaf, typename)
  270. nodename = '.'.join(nodename.split('.')[:-1])
  271. cur = path[-1][1]
  272. else:
  273. curname, cur = left[0]
  274. path.append((curname, cur))
  275. nodename += '.' + curname.title()
  276. ## @brief Forge a named tuple given a conftree node
  277. # @param conftree dict : A conftree node
  278. # @param name str
  279. # @return a named tuple with fieldnames corresponding to conftree keys
  280. def __tree2namedtuple(self, conftree, name):
  281. ResNamedTuple = namedtuple(name, conftree.keys())
  282. return ResNamedTuple(**conftree)
  283. class MetaSettingsRO(type):
  284. def __getattr__(self, name):
  285. return getattr(Settings.s, name)
  286. ## @brief A class that provide . notation read only access to configurations
  287. class SettingsRO(object, metaclass=MetaSettingsRO):
  288. pass