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_loader.py 7.6KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195
  1. #-*- coding: utf-8 -*-
  2. import configparser
  3. import os
  4. import glob
  5. import copy
  6. from lodel.context import LodelContext
  7. LodelContext.expose_modules(globals(), {
  8. 'lodel.logger': 'logger',
  9. 'lodel.settings.utils': ['SettingsError', 'SettingsErrors'],
  10. 'lodel.settings.validator': ['SettingsValidationError']})
  11. ##@brief Merges and loads configuration files
  12. class SettingsLoader(object):
  13. ## To avoid the DEFAULT section whose values are found in all sections, we
  14. # have to give it an unsual name
  15. DEFAULT_SECTION = 'lodel2_default_passaway_tip'
  16. ## @brief Virtual filename when default value is used
  17. DEFAULT_FILENAME = 'default_value'
  18. ##@brief Constructor
  19. # @param conf_path str : conf.d path
  20. def __init__(self,conf_path):
  21. self.__conf_path=conf_path
  22. self.__conf_sv=dict()
  23. self.__conf=self.__merge()
  24. # Stores errors
  25. self.__errors_list = []
  26. ##@brief Lists and merges files in settings_loader.conf_path
  27. # @return dict()
  28. def __merge(self):
  29. conf = dict()
  30. l_dir = glob.glob(self.__conf_path+'/*.ini')
  31. logger.debug("SettingsLoader found those settings files : %s" % (
  32. ', '.join(l_dir)))
  33. for f_ini in l_dir:
  34. config = configparser.ConfigParser(default_section = self.DEFAULT_SECTION ,interpolation=None)
  35. config.read(f_ini)
  36. for section in [ s for s in config if s != self.DEFAULT_SECTION ]:
  37. if section not in conf:
  38. conf[section] = dict()
  39. for param in config[section]:
  40. if param not in conf[section]:
  41. conf[section][param]=dict()
  42. conf[section][param]['value'] = config[section][param]
  43. conf[section][param]['file'] = f_ini
  44. self.__conf_sv[section + ':' + param]=f_ini
  45. else:
  46. raise SettingsError("Error redeclaration of key %s in section %s. Found in %s and %s" % (
  47. section,
  48. param,
  49. f_ini,
  50. conf[section][param]['file']))
  51. return conf
  52. ##@brief Returns option if exists default_value else and validates
  53. # @param section str : name of the section
  54. # @param keyname str
  55. # @param validator callable : takes one argument value and raises validation fail
  56. # @param default_value *
  57. # @param mandatory bool
  58. # @return the option
  59. def getoption(self,section,keyname,validator,default_value=None,mandatory=False):
  60. conf=self.__conf
  61. if section not in conf:
  62. conf[section] = dict()
  63. sec = conf[section]
  64. result = None
  65. if keyname in sec:
  66. result = sec[keyname]['value']
  67. if result is not None:
  68. result = result.strip()
  69. if len(result) == 0:
  70. result = None
  71. try:
  72. del self.__conf_sv[section + ':' + keyname]
  73. except KeyError: #allready fetched
  74. pass
  75. if result is None:
  76. if default_value is None and mandatory:
  77. msg = "Default value mandatory for option %s" % keyname
  78. expt = SettingsError( msg = msg,
  79. key_id = section+'.'+keyname,
  80. filename = sec[keyname]['file'])
  81. self.__errors_list.append(expt)
  82. return
  83. else:
  84. sec[keyname]=dict()
  85. sec[keyname]['value'] = default_value
  86. sec[keyname]['file'] = SettingsLoader.DEFAULT_FILENAME
  87. result = default_value
  88. logger.debug("Using default value for configuration key %s:%s" % (
  89. section, keyname))
  90. try:
  91. return validator(result)
  92. except Exception as e:
  93. # Generating nice exceptions
  94. if False and sec[keyname]['file'] == SettingsLoader.DEFAULT_FILENAME:
  95. expt = SettingsError( msg = 'Mandatory settings not found',
  96. key_id = section+'.'+keyname)
  97. self.__errors_list.append(expt)
  98. else:
  99. expt = SettingsValidationError(
  100. "For %s.%s : %s" %
  101. (section, keyname,e)
  102. )
  103. expt2 = SettingsError( msg = str(expt),
  104. key_id = section+'.'+keyname,
  105. filename = sec[keyname]['file'])
  106. self.__errors_list.append(expt2)
  107. return
  108. ##@brief Sets option in a config section. Writes in the conf file
  109. # @param section str : name of the section
  110. # @param keyname str
  111. # @param value str
  112. # @param validator callable : takes one argument value and raises validation fail
  113. # @return the option
  114. def setoption(self,section,keyname,value,validator):
  115. f_conf=copy.copy(self.__conf[section][keyname]['file'])
  116. if f_conf == SettingsLoader.DEFAULT_FILENAME:
  117. f_conf = self.__conf_path + '/generated.ini'
  118. conf=self.__conf
  119. conf[section][keyname] = value
  120. config = configparser.ConfigParser()
  121. config.read(f_conf)
  122. if section not in config:
  123. config[section]={}
  124. config[section][keyname] = validator(value)
  125. with open(f_conf, 'w') as configfile:
  126. config.write(configfile)
  127. ##@brief Saves new partial configuration. Writes in the conf files corresponding
  128. # @param sections dict
  129. # @param validators dict of callable : takes one argument value and raises validation fail
  130. def saveconf(self, sections, validators):
  131. for sec in sections:
  132. for kname in sections[sec]:
  133. self.setoption(sec,kname,sections[sec][kname],validators[sec][kname])
  134. ##@brief Returns the section to be configured
  135. # @param section_prefix str
  136. # @param default_section str
  137. # @return the section as dict()
  138. def getsection(self,section_prefix,default_section=None):
  139. conf=copy.copy(self.__conf)
  140. sections=[]
  141. if section_prefix in conf:
  142. sections.append(section_prefix)
  143. for sect_names in conf:
  144. if sect_names in sections:
  145. pass
  146. elif sect_names.startswith(section_prefix + '.'):
  147. sections.append(sect_names)
  148. if sections == [] and default_section:
  149. sections.append(section_prefix + '.' + default_section)
  150. elif sections == []:
  151. raise NameError("Not existing settings section : %s" % section_prefix)
  152. return sections
  153. ##@brief Returns invalid settings
  154. #
  155. # This method returns all the settings that was not fecthed by
  156. # getsection() method. For the Settings object it allows to know
  157. # the list of invalids settings keys
  158. # @return a dict with SECTION_NAME+":"+KEY_NAME as key and the filename
  159. # where the settings was found as value
  160. def getremains(self):
  161. return self.__conf_sv
  162. ##@brief Raise a SettingsErrors exception if some confs remains
  163. #@note typically used at the end of Settings bootstrap
  164. def raise_errors(self):
  165. remains = self.getremains()
  166. err_l = self.__errors_list
  167. for key_id, filename in remains.items():
  168. err_l.append(SettingsError( msg = "Invalid configuration key",
  169. key_id = key_id,
  170. filename = filename))
  171. if len(err_l) > 0:
  172. raise SettingsErrors(err_l)
  173. else:
  174. return