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.

185 lines
6.6 KiB

  1. # -*- coding: utf-8 -*-
  2. ##############################################################################
  3. #
  4. # Adapted by Nicolas Bessi. Copyright Camptocamp SA
  5. # Based on Florent Xicluna original code. Copyright Wingo SA
  6. #
  7. # This program is free software: you can redistribute it and/or modify
  8. # it under the terms of the GNU General Public License as published by
  9. # the Free Software Foundation, either version 3 of the License, or
  10. # (at your option) any later version.
  11. #
  12. # This program is distributed in the hope that it will be useful,
  13. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. # GNU General Public License for more details.
  16. #
  17. # You should have received a copy of the GNU General Public License
  18. # along with this program. If not, see <http://www.gnu.org/licenses/>.
  19. #
  20. ##############################################################################
  21. import os
  22. import ConfigParser
  23. from lxml import etree
  24. from osv import osv, fields
  25. from tools.config import config as system_base_config
  26. from .system_info import get_server_environment
  27. import server_environment_files
  28. _dir = os.path.dirname(server_environment_files.__file__)
  29. # Same dict as RawConfigParser._boolean_states
  30. _boolean_states = {'1': True, 'yes': True, 'true': True, 'on': True,
  31. '0': False, 'no': False, 'false': False, 'off': False}
  32. if not system_base_config.get('running_env', False):
  33. raise Exception(
  34. "The parameter 'running_env' has not be set neither in base config file option -c or in openerprc.\n"
  35. "We strongly recommend against using the rc file but instead use an explicit config file with this content:\n"
  36. "[options]\nrunning_env = dev"
  37. )
  38. ck_path = os.path.join(_dir, system_base_config['running_env'])
  39. if not os.path.exists(ck_path) :
  40. raise Exception(
  41. "Provided server environment does not exist, please add a folder %s" % ck_path
  42. )
  43. def setboolean(obj, attr, _bool=_boolean_states):
  44. """Replace the attribute with a boolean."""
  45. res = _bool[getattr(obj, attr).lower()]
  46. setattr(obj, attr, res)
  47. return res
  48. # Borrowed from MarkupSafe
  49. def _escape(s):
  50. """Convert the characters &<>'" in string s to HTML-safe sequences."""
  51. return (str(s).replace('&', '&amp;')
  52. .replace('>', '&gt;')
  53. .replace('<', '&lt;')
  54. .replace("'", '&#39;')
  55. .replace('"', '&#34;'))
  56. def _listconf(env_path):
  57. """List configuration files in a folder."""
  58. files = [os.path.join(env_path, name)
  59. for name in sorted(os.listdir(env_path))
  60. if name.endswith('.conf')]
  61. return files
  62. def _load_config():
  63. """Load the configuration and return a ConfigParser instance."""
  64. default = os.path.join(_dir, 'default')
  65. running_env = os.path.join(_dir, system_base_config['running_env'])
  66. if os.path.isdir(default):
  67. conf_files = _listconf(default) + _listconf(running_env)
  68. else:
  69. conf_files = _listconf(running_env)
  70. config_p = ConfigParser.SafeConfigParser()
  71. # options are case-sensitive
  72. config_p.optionxform = str
  73. try:
  74. config_p.read(conf_files)
  75. except Exception, e:
  76. raise Exception('Cannot read config files "%s": %s' % (conf_files, e))
  77. return config_p
  78. serv_config = _load_config()
  79. class _Defaults(dict):
  80. __slots__ = ()
  81. def __setitem__(self, key, value):
  82. func = lambda *a: str(value)
  83. return dict.__setitem__(self, key, func)
  84. class ServerConfiguration(osv.osv_memory):
  85. """Display server configuration."""
  86. _name = 'server.config'
  87. _columns = {}
  88. _conf_defaults = _Defaults()
  89. def __init__(self, pool, cr):
  90. res = super(ServerConfiguration, self).__init__(pool, cr)
  91. self.running_env = system_base_config['running_env']
  92. # Only show passwords in development
  93. self.show_passwords = self.running_env in ('dev',)
  94. self._build_osv()
  95. return res
  96. def _group(self, items, prefix):
  97. """Return an XML chunk which represents a group of fields."""
  98. names = []
  99. for k, v in items:
  100. key = '%s\\%s' % (prefix, k)
  101. # Mask passwords
  102. if 'passw' in k and not self.show_passwords:
  103. v = '**********'
  104. self._columns[key] = fields.char(k, size=1024)
  105. self._conf_defaults[key] = v
  106. names.append(key)
  107. return ('<group col="2" colspan="4">' +
  108. ''.join(['<field name="%s" readonly="1"/>' %
  109. _escape(name) for name in names]) +
  110. '</group>')
  111. def _build_osv(self):
  112. """Build the view for the current configuration."""
  113. arch = ('<?xml version="1.0" encoding="utf-8"?>'
  114. '<form string="Configuration Form">'
  115. '<notebook colspan="4">')
  116. # OpenERP server configuration
  117. rcfile = system_base_config.rcfile
  118. items = sorted(system_base_config.options.items())
  119. arch += '<page string="OpenERP">'
  120. arch += '<separator string="%s" colspan="4"/>' % _escape(rcfile)
  121. arch += self._group(items, prefix='openerp')
  122. arch += '<separator colspan="4"/></page>'
  123. arch += '<page string="Environment based configurations">'
  124. for section in sorted(serv_config.sections()):
  125. items = sorted(serv_config.items(section))
  126. arch += '<separator string="[%s]" colspan="4"/>' % _escape(section)
  127. arch += self._group(items, prefix=section)
  128. arch += '<separator colspan="4"/></page>'
  129. # System information
  130. arch += '<page string="System">'
  131. arch += '<separator string="Server Environment" colspan="4"/>'
  132. arch += self._group(get_server_environment(), prefix='system')
  133. arch += '<separator colspan="4"/></page>'
  134. arch += '</notebook></form>'
  135. self._arch = etree.fromstring(arch)
  136. def fields_view_get(self, cr, uid, view_id=None, view_type='form', context=None, toolbar=False, submenu=False):
  137. """Overwrite the default method to render the custom view."""
  138. res = super(ServerConfiguration, self).fields_view_get(cr, uid, view_id, view_type, context, toolbar)
  139. if view_type == 'form':
  140. arch_node = self._arch
  141. xarch, xfields = self._view_look_dom_arch(cr, uid, arch_node, view_id, context=context)
  142. res['arch'] = xarch
  143. res['fields'] = xfields
  144. return res
  145. def default_get(self, cr, uid, fields_list, context=None):
  146. res = {}
  147. for key in self._conf_defaults:
  148. res[key] = self._conf_defaults[key]()
  149. return res
  150. ServerConfiguration()