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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194
  1. #-*- coding: utf-8 -*-
  2. import configparser
  3. import os
  4. import glob
  5. import copy
  6. from lodel import logger
  7. from lodel.settings.utils import *
  8. from lodel.settings.validator import SettingsValidationError
  9. from lodel.settings.utils import 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 in section %s. Found in %s and %s" % (
  46. section,
  47. param,
  48. f_ini,
  49. conf[section][param]['file']))
  50. return conf
  51. ##@brief Returns option if exists default_value else and validates
  52. # @param section str : name of the section
  53. # @param keyname str
  54. # @param validator callable : takes one argument value and raises validation fail
  55. # @param default_value *
  56. # @param mandatory bool
  57. # @return the option
  58. def getoption(self,section,keyname,validator,default_value=None,mandatory=False):
  59. conf=self.__conf
  60. if section not in conf:
  61. conf[section] = dict()
  62. sec = conf[section]
  63. result = None
  64. if keyname in sec:
  65. result = sec[keyname]['value']
  66. if result is not None:
  67. result = result.strip()
  68. if len(result) == 0:
  69. result = None
  70. try:
  71. del self.__conf_sv[section + ':' + keyname]
  72. except KeyError: #allready fetched
  73. pass
  74. if result is None:
  75. if default_value is None and mandatory:
  76. msg = "Default value mandatory for option %s" % keyname
  77. expt = SettingsError( msg = msg,
  78. key_id = section+'.'+keyname,
  79. filename = sec[keyname]['file'])
  80. self.__errors_list.append(expt)
  81. return
  82. else:
  83. sec[keyname]=dict()
  84. sec[keyname]['value'] = default_value
  85. sec[keyname]['file'] = SettingsLoader.DEFAULT_FILENAME
  86. result = default_value
  87. logger.debug("Using default value for configuration key %s:%s" % (
  88. section, keyname))
  89. try:
  90. return validator(result)
  91. except Exception as e:
  92. # Generating nice exceptions
  93. if False and sec[keyname]['file'] == SettingsLoader.DEFAULT_FILENAME:
  94. expt = SettingsError( msg = 'Mandatory settings not found',
  95. key_id = section+'.'+keyname)
  96. self.__errors_list.append(expt)
  97. else:
  98. expt = SettingsValidationError(
  99. "For %s.%s : %s" %
  100. (section, keyname,e)
  101. )
  102. expt2 = SettingsError( msg = str(expt),
  103. key_id = section+'.'+keyname,
  104. filename = sec[keyname]['file'])
  105. self.__errors_list.append(expt2)
  106. return
  107. ##@brief Sets option in a config section. Writes in the conf file
  108. # @param section str : name of the section
  109. # @param keyname str
  110. # @param value str
  111. # @param validator callable : takes one argument value and raises validation fail
  112. # @return the option
  113. def setoption(self,section,keyname,value,validator):
  114. f_conf=copy.copy(self.__conf[section][keyname]['file'])
  115. if f_conf == SettingsLoader.DEFAULT_FILENAME:
  116. f_conf = self.__conf_path + '/generated.ini'
  117. conf=self.__conf
  118. conf[section][keyname] = value
  119. config = configparser.ConfigParser()
  120. config.read(f_conf)
  121. if section not in config:
  122. config[section]={}
  123. config[section][keyname] = validator(value)
  124. with open(f_conf, 'w') as configfile:
  125. config.write(configfile)
  126. ##@brief Saves new partial configuration. Writes in the conf files corresponding
  127. # @param sections dict
  128. # @param validators dict of callable : takes one argument value and raises validation fail
  129. def saveconf(self, sections, validators):
  130. for sec in sections:
  131. for kname in sections[sec]:
  132. self.setoption(sec,kname,sections[sec][kname],validators[sec][kname])
  133. ##@brief Returns the section to be configured
  134. # @param section_prefix str
  135. # @param default_section str
  136. # @return the section as dict()
  137. def getsection(self,section_prefix,default_section=None):
  138. conf=copy.copy(self.__conf)
  139. sections=[]
  140. if section_prefix in conf:
  141. sections.append(section_prefix)
  142. for sect_names in conf:
  143. if sect_names in sections:
  144. pass
  145. elif sect_names.startswith(section_prefix + '.'):
  146. sections.append(sect_names)
  147. if sections == [] and default_section:
  148. sections.append(section_prefix + '.' + default_section)
  149. elif sections == []:
  150. raise NameError("Not existing settings section : %s" % section_prefix)
  151. return sections
  152. ##@brief Returns invalid settings
  153. #
  154. # This method returns all the settings that was not fecthed by
  155. # getsection() method. For the Settings object it allows to know
  156. # the list of invalids settings keys
  157. # @return a dict with SECTION_NAME+":"+KEY_NAME as key and the filename
  158. # where the settings was found as value
  159. def getremains(self):
  160. return self.__conf_sv
  161. ##@brief Raise a SettingsErrors exception if some confs remains
  162. #@note typically used at the end of Settings bootstrap
  163. def raise_errors(self):
  164. remains = self.getremains()
  165. err_l = self.__errors_list
  166. for key_id, filename in remains.items():
  167. err_l.append(SettingsError( msg = "Invalid configuration key",
  168. key_id = key_id,
  169. filename = filename))
  170. if len(err_l) > 0:
  171. raise SettingsErrors(err_l)
  172. else:
  173. return