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.3KB

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