Açıklama Yok
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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188
  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. if keyname in sec:
  64. result = sec[keyname]['value']
  65. try:
  66. del self.__conf_sv[section + ':' + keyname]
  67. except KeyError: #allready fetched
  68. pass
  69. elif default_value is None and mandatory:
  70. msg = "Default value mandatory for option %s" % keyname
  71. expt = SettingsError( msg = msg,
  72. key_id = section+'.'+keyname,
  73. filename = sec[keyname]['file'])
  74. self.__errors_list.append(expt)
  75. return
  76. else:
  77. sec[keyname]=dict()
  78. sec[keyname]['value'] = default_value
  79. sec[keyname]['file'] = SettingsLoader.DEFAULT_FILENAME
  80. result = default_value
  81. logger.debug("Using default value for configuration key %s:%s" % (
  82. section, keyname))
  83. try:
  84. return validator(result)
  85. except Exception as e:
  86. # Generating nice exceptions
  87. if False and sec[keyname]['file'] == SettingsLoader.DEFAULT_FILENAME:
  88. expt = SettingsError( msg = 'Mandatory settings not found',
  89. key_id = section+'.'+keyname)
  90. self.__errors_list.append(expt)
  91. else:
  92. expt = SettingsValidationError(
  93. "For %s.%s : %s" %
  94. (section, keyname,e)
  95. )
  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