PageRenderTime 186ms CodeModel.GetById 7ms RepoModel.GetById 0ms app.codeStats 0ms

/indra/lib/python/indra/base/config.py

https://bitbucket.org/lindenlab/viewer-beta/
Python | 266 lines | 257 code | 0 blank | 9 comment | 0 complexity | c2113a28d11612bb16115a02e125c337 MD5 | raw file
Possible License(s): LGPL-2.1
  1. """\
  2. @file config.py
  3. @brief Utility module for parsing and accessing the indra.xml config file.
  4. $LicenseInfo:firstyear=2006&license=mit$
  5. Copyright (c) 2006-2009, Linden Research, Inc.
  6. Permission is hereby granted, free of charge, to any person obtaining a copy
  7. of this software and associated documentation files (the "Software"), to deal
  8. in the Software without restriction, including without limitation the rights
  9. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  10. copies of the Software, and to permit persons to whom the Software is
  11. furnished to do so, subject to the following conditions:
  12. The above copyright notice and this permission notice shall be included in
  13. all copies or substantial portions of the Software.
  14. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. THE SOFTWARE.
  21. $/LicenseInfo$
  22. """
  23. import copy
  24. import errno
  25. import os
  26. import traceback
  27. import time
  28. import types
  29. from os.path import dirname, getmtime, join, realpath
  30. from indra.base import llsd
  31. _g_config = None
  32. class IndraConfig(object):
  33. """
  34. IndraConfig loads a 'indra' xml configuration file
  35. and loads into memory. This representation in memory
  36. can get updated to overwrite values or add new values.
  37. The xml configuration file is considered a live file and changes
  38. to the file are checked and reloaded periodically. If a value had
  39. been overwritten via the update or set method, the loaded values
  40. from the file are ignored (the values from the update/set methods
  41. override)
  42. """
  43. def __init__(self, indra_config_file):
  44. self._indra_config_file = indra_config_file
  45. self._reload_check_interval = 30 # seconds
  46. self._last_check_time = 0
  47. self._last_mod_time = 0
  48. self._config_overrides = {}
  49. self._config_file_dict = {}
  50. self._combined_dict = {}
  51. self._load()
  52. def _load(self):
  53. # if you initialize the IndraConfig with None, no attempt
  54. # is made to load any files
  55. if self._indra_config_file is None:
  56. return
  57. config_file = open(self._indra_config_file)
  58. self._config_file_dict = llsd.parse(config_file.read())
  59. self._combine_dictionaries()
  60. config_file.close()
  61. self._last_mod_time = self._get_last_modified_time()
  62. self._last_check_time = time.time() # now
  63. def _get_last_modified_time(self):
  64. """
  65. Returns the mtime (last modified time) of the config file,
  66. if such exists.
  67. """
  68. if self._indra_config_file is not None:
  69. return os.path.getmtime(self._indra_config_file)
  70. return 0
  71. def _combine_dictionaries(self):
  72. self._combined_dict = {}
  73. self._combined_dict.update(self._config_file_dict)
  74. self._combined_dict.update(self._config_overrides)
  75. def _reload_if_necessary(self):
  76. now = time.time()
  77. if (now - self._last_check_time) > self._reload_check_interval:
  78. self._last_check_time = now
  79. try:
  80. modtime = self._get_last_modified_time()
  81. if modtime > self._last_mod_time:
  82. self._load()
  83. except OSError, e:
  84. if e.errno == errno.ENOENT: # file not found
  85. # someone messed with our internal state
  86. # or removed the file
  87. print 'WARNING: Configuration file has been removed ' + (self._indra_config_file)
  88. print 'Disabling reloading of configuration file.'
  89. traceback.print_exc()
  90. self._indra_config_file = None
  91. self._last_check_time = 0
  92. self._last_mod_time = 0
  93. else:
  94. raise # pass the exception along to the caller
  95. def __getitem__(self, key):
  96. self._reload_if_necessary()
  97. return self._combined_dict[key]
  98. def get(self, key, default = None):
  99. try:
  100. return self.__getitem__(key)
  101. except KeyError:
  102. return default
  103. def __setitem__(self, key, value):
  104. """
  105. Sets the value of the config setting of key to be newval
  106. Once any key/value pair is changed via the set method,
  107. that key/value pair will remain set with that value until
  108. change via the update or set method
  109. """
  110. self._config_overrides[key] = value
  111. self._combine_dictionaries()
  112. def set(self, key, newval):
  113. return self.__setitem__(key, newval)
  114. def update(self, new_conf):
  115. """
  116. Load an XML file and apply its map as overrides or additions
  117. to the existing config. Update can be a file or a dict.
  118. Once any key/value pair is changed via the update method,
  119. that key/value pair will remain set with that value until
  120. change via the update or set method
  121. """
  122. if isinstance(new_conf, dict):
  123. overrides = new_conf
  124. else:
  125. # assuming that it is a filename
  126. config_file = open(new_conf)
  127. overrides = llsd.parse(config_file.read())
  128. config_file.close()
  129. self._config_overrides.update(overrides)
  130. self._combine_dictionaries()
  131. def as_dict(self):
  132. """
  133. Returns immutable copy of the IndraConfig as a dictionary
  134. """
  135. return copy.deepcopy(self._combined_dict)
  136. def load(config_xml_file = None):
  137. global _g_config
  138. load_default_files = config_xml_file is None
  139. if load_default_files:
  140. ## going from:
  141. ## "/opt/linden/indra/lib/python/indra/base/config.py"
  142. ## to:
  143. ## "/opt/linden/etc/indra.xml"
  144. config_xml_file = realpath(
  145. dirname(realpath(__file__)) + "../../../../../../etc/indra.xml")
  146. try:
  147. _g_config = IndraConfig(config_xml_file)
  148. except IOError:
  149. # Failure to load passed in file
  150. # or indra.xml default file
  151. if load_default_files:
  152. try:
  153. config_xml_file = realpath(
  154. dirname(realpath(__file__)) + "../../../../../../etc/globals.xml")
  155. _g_config = IndraConfig(config_xml_file)
  156. return
  157. except IOError:
  158. # Failure to load globals.xml
  159. # fall to code below
  160. pass
  161. # Either failed to load passed in file
  162. # or failed to load all default files
  163. _g_config = IndraConfig(None)
  164. def dump(indra_xml_file, indra_cfg = None, update_in_mem=False):
  165. '''
  166. Dump config contents into a file
  167. Kindof reverse of load.
  168. Optionally takes a new config to dump.
  169. Does NOT update global config unless requested.
  170. '''
  171. global _g_config
  172. if not indra_cfg:
  173. if _g_config is None:
  174. return
  175. indra_cfg = _g_config.as_dict()
  176. if not indra_cfg:
  177. return
  178. config_file = open(indra_xml_file, 'w')
  179. _config_xml = llsd.format_xml(indra_cfg)
  180. config_file.write(_config_xml)
  181. config_file.close()
  182. if update_in_mem:
  183. update(indra_cfg)
  184. def update(new_conf):
  185. global _g_config
  186. if _g_config is None:
  187. # To keep with how this function behaved
  188. # previously, a call to update
  189. # before the global is defined
  190. # make a new global config which does not
  191. # load data from a file.
  192. _g_config = IndraConfig(None)
  193. return _g_config.update(new_conf)
  194. def get(key, default = None):
  195. global _g_config
  196. if _g_config is None:
  197. load()
  198. return _g_config.get(key, default)
  199. def set(key, newval):
  200. """
  201. Sets the value of the config setting of key to be newval
  202. Once any key/value pair is changed via the set method,
  203. that key/value pair will remain set with that value until
  204. change via the update or set method or program termination
  205. """
  206. global _g_config
  207. if _g_config is None:
  208. _g_config = IndraConfig(None)
  209. _g_config.set(key, newval)
  210. def get_config():
  211. global _g_config
  212. return _g_config