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 6.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173
  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.validator.validator': ['ValidationError']})
  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(
  35. default_section = self.DEFAULT_SECTION ,interpolation=None)
  36. config.read(f_ini)
  37. for section in [s for s in config if s != self.DEFAULT_SECTION]:
  38. if section not in conf:
  39. conf[section] = dict()
  40. for param in config[section]:
  41. if param not in conf[section]:
  42. conf[section][param] = dict()
  43. conf[section][param]['value'] = config[section][param]
  44. conf[section][param]['file'] = f_ini
  45. self.__conf_sv[section + ':' + param] = f_ini
  46. else:
  47. raise SettingsError("Error redeclaration of key %s \
  48. in section %s. Found in %s and %s" % (\
  49. section, param, f_ini, 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. # @return the option
  57. def getoption(self,section,keyname,validator,default_value=None):
  58. conf=self.__conf
  59. if section not in conf:
  60. conf[section] = dict()
  61. sec = conf[section]
  62. if keyname in sec:
  63. result = sec[keyname]['value']
  64. try:
  65. del self.__conf_sv[section + ':' + keyname]
  66. except KeyError: #allready fetched
  67. pass
  68. else:
  69. #default values
  70. sec[keyname] = dict()
  71. result = sec[keyname]['value'] = default_value
  72. sec[keyname]['file'] = SettingsLoader.DEFAULT_FILENAME
  73. try:
  74. return validator(result)
  75. except Exception as e:
  76. # Generating nice exceptions
  77. if False and sec[keyname]['file'] == SettingsLoader.DEFAULT_FILENAME:
  78. expt = SettingsError(msg='Mandatory settings not found', \
  79. key_id=section+'.'+keyname)
  80. self.__errors_list.append(expt)
  81. else:
  82. expt = ValidationError("For %s.%s : %s" % (section, keyname, e))
  83. expt2 = SettingsError(msg=str(expt), \
  84. key_id=section+'.'+keyname, \
  85. filename=sec[keyname]['file'])
  86. self.__errors_list.append(expt2)
  87. return
  88. ##@brief Sets option in a config section. Writes in the conf file
  89. # @param section str : name of the section
  90. # @param keyname str
  91. # @param value str
  92. # @param validator callable : takes one argument value and raises validation fail
  93. # @return the option
  94. def setoption(self, section, keyname, value, validator):
  95. f_conf = copy.copy(self.__conf[section][keyname]['file'])
  96. if f_conf == SettingsLoader.DEFAULT_FILENAME:
  97. f_conf = self.__conf_path + '/generated.ini'
  98. conf = self.__conf
  99. conf[section][keyname] = value
  100. config = configparser.ConfigParser()
  101. config.read(f_conf)
  102. if section not in config:
  103. config[section] = {}
  104. config[section][keyname] = validator(value)
  105. with open(f_conf, 'w') as configfile:
  106. config.write(configfile)
  107. ##@brief Saves new partial configuration. Writes in the conf files corresponding
  108. # @param sections dict
  109. # @param validators dict of callable : takes one argument value and raises validation fail
  110. def saveconf(self, sections, validators):
  111. for sec in sections:
  112. for kname in sections[sec]:
  113. self.setoption(sec, kname, sections[sec][kname], validators[sec][kname])
  114. ##@brief Returns the section to be configured
  115. # @param section_prefix str
  116. # @param default_section str
  117. # @return the section as dict()
  118. def getsection(self, section_prefix, default_section=None):
  119. conf = copy.copy(self.__conf)
  120. sections = []
  121. if section_prefix in conf:
  122. sections.append(section_prefix)
  123. for sect_names in conf:
  124. if sect_names in sections:
  125. pass
  126. elif sect_names.startswith(section_prefix + '.'):
  127. sections.append(sect_names)
  128. if sections == [] and default_section:
  129. sections.append(section_prefix + '.' + default_section)
  130. elif sections == []:
  131. raise NameError("Not existing settings section : %s" % section_prefix)
  132. return sections
  133. ##@brief Returns invalid settings
  134. #
  135. # This method returns all the settings that was not fecthed by
  136. # getsection() method. For the Settings object it allows to know
  137. # the list of invalids settings keys
  138. # @return a dict with SECTION_NAME+":"+KEY_NAME as key and the filename
  139. # where the settings was found as value
  140. def getremains(self):
  141. return self.__conf_sv
  142. ##@brief Raise a SettingsErrors exception if some confs remains
  143. #@note typically used at the end of Settings bootstrap
  144. def raise_errors(self):
  145. remains = self.getremains()
  146. err_l = self.__errors_list
  147. for key_id, filename in remains.items():
  148. err_l.append(SettingsError(msg="Invalid configuration key", \
  149. key_id=key_id, \
  150. filename =filename))
  151. if len(err_l) > 0:
  152. raise SettingsErrors(err_l)
  153. else:
  154. return