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.

245 lines
8.6 KiB

10 years ago
10 years ago
  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 itertools import chain
  25. from openerp import models, fields
  26. from openerp.tools.config import config as system_base_config
  27. from .system_info import get_server_environment
  28. from openerp.addons import server_environment_files
  29. _dir = os.path.dirname(server_environment_files.__file__)
  30. # Same dict as RawConfigParser._boolean_states
  31. _boolean_states = {'1': True, 'yes': True, 'true': True, 'on': True,
  32. '0': False, 'no': False, 'false': False, 'off': False}
  33. if not system_base_config.get('running_env', False):
  34. raise Exception(
  35. "The parameter 'running_env' has not be set neither in base config "
  36. "file option -c or in openerprc.\n"
  37. "We strongly recommend against using the rc file but instead use an "
  38. "explicit config file with this content:\n"
  39. "[options]\nrunning_env = dev"
  40. )
  41. ck_path = os.path.join(_dir, system_base_config['running_env'])
  42. if not os.path.exists(ck_path):
  43. raise Exception(
  44. "Provided server environment does not exist, "
  45. "please add a folder %s" % ck_path
  46. )
  47. def setboolean(obj, attr, _bool=None):
  48. """Replace the attribute with a boolean."""
  49. if _bool is None:
  50. _bool = dict(_boolean_states)
  51. res = _bool[getattr(obj, attr).lower()]
  52. setattr(obj, attr, res)
  53. return res
  54. # Borrowed from MarkupSafe
  55. def _escape(s):
  56. """Convert the characters &<>'" in string s to HTML-safe sequences."""
  57. return (str(s).replace('&', '&amp;')
  58. .replace('>', '&gt;')
  59. .replace('<', '&lt;')
  60. .replace("'", '&#39;')
  61. .replace('"', '&#34;'))
  62. def _listconf(env_path):
  63. """List configuration files in a folder."""
  64. files = [os.path.join(env_path, name)
  65. for name in sorted(os.listdir(env_path))
  66. if name.endswith('.conf')]
  67. return files
  68. def _load_config():
  69. """Load the configuration and return a ConfigParser instance."""
  70. default = os.path.join(_dir, 'default')
  71. running_env = os.path.join(_dir,
  72. system_base_config['running_env'])
  73. if os.path.isdir(default):
  74. conf_files = _listconf(default) + _listconf(running_env)
  75. else:
  76. conf_files = _listconf(running_env)
  77. config_p = ConfigParser.SafeConfigParser()
  78. # options are case-sensitive
  79. config_p.optionxform = str
  80. try:
  81. config_p.read(conf_files)
  82. except Exception as e:
  83. raise Exception('Cannot read config files "%s": %s' % (conf_files, e))
  84. config_p.read(system_base_config.rcfile)
  85. config_p.remove_section('options')
  86. return config_p
  87. serv_config = _load_config()
  88. class _Defaults(dict):
  89. __slots__ = ()
  90. def __setitem__(self, key, value):
  91. def func(*a):
  92. return str(value)
  93. return dict.__setitem__(self, key, func)
  94. class ServerConfiguration(models.TransientModel):
  95. """Display server configuration."""
  96. _name = 'server.config'
  97. _conf_defaults = _Defaults()
  98. def __init__(self, pool, cr):
  99. """Add columns to model dynamically
  100. and init some properties
  101. """
  102. self._add_columns()
  103. super(ServerConfiguration, self).__init__(pool, cr)
  104. self.running_env = system_base_config['running_env']
  105. # Only show passwords in development
  106. self.show_passwords = self.running_env in ('dev',)
  107. self._arch = None
  108. self._build_osv()
  109. def _format_key(self, section, key):
  110. return '%s | %s' % (section, key)
  111. def _add_columns(self):
  112. """Add columns to model dynamically"""
  113. cols = chain(
  114. self._get_base_cols().items(),
  115. self._get_env_cols().items(),
  116. self._get_system_cols().items()
  117. )
  118. for col, value in cols:
  119. col_name = col.replace('.', '_')
  120. setattr(ServerConfiguration,
  121. col_name,
  122. fields.Char(string=col, readonly=True))
  123. self._conf_defaults[col_name] = value
  124. def _get_base_cols(self):
  125. """ Compute base fields"""
  126. res = {}
  127. for col, item in system_base_config.options.items():
  128. key = self._format_key('openerp', col)
  129. res[key] = item
  130. return res
  131. def _get_env_cols(self, sections=None):
  132. """ Compute base fields"""
  133. res = {}
  134. sections = sections if sections else serv_config.sections()
  135. for section in sections:
  136. for col, item in serv_config.items(section):
  137. key = self._format_key(section, col)
  138. res[key] = item
  139. return res
  140. def _get_system_cols(self):
  141. """ Compute system fields"""
  142. res = {}
  143. for col, item in get_server_environment():
  144. key = self._format_key('system', col)
  145. res[key] = item
  146. return res
  147. def _group(self, items):
  148. """Return an XML chunk which represents a group of fields."""
  149. names = []
  150. for key in sorted(items):
  151. names.append(key.replace('.', '_'))
  152. return ('<group col="2" colspan="4">' +
  153. ''.join(['<field name="%s" readonly="1"/>' %
  154. _escape(name) for name in names]) +
  155. '</group>')
  156. def _build_osv(self):
  157. """Build the view for the current configuration."""
  158. arch = ('<?xml version="1.0" encoding="utf-8"?>'
  159. '<form string="Configuration Form">'
  160. '<notebook colspan="4">')
  161. # OpenERP server configuration
  162. rcfile = system_base_config.rcfile
  163. items = self._get_base_cols()
  164. arch += '<page string="OpenERP">'
  165. arch += '<separator string="%s" colspan="4"/>' % _escape(rcfile)
  166. arch += self._group(items)
  167. arch += '<separator colspan="4"/></page>'
  168. arch += '<page string="Environment based configurations">'
  169. for section in sorted(serv_config.sections()):
  170. items = self._get_env_cols(sections=[section])
  171. arch += '<separator string="[%s]" colspan="4"/>' % _escape(section)
  172. arch += self._group(items)
  173. arch += '<separator colspan="4"/></page>'
  174. # System information
  175. arch += '<page string="System">'
  176. arch += '<separator string="Server Environment" colspan="4"/>'
  177. arch += self._group(self._get_system_cols())
  178. arch += '<separator colspan="4"/></page>'
  179. arch += '</notebook></form>'
  180. self._arch = etree.fromstring(arch)
  181. def fields_view_get(self, cr, uid, view_id=None, view_type='form',
  182. context=None, toolbar=False, submenu=False):
  183. """Overwrite the default method to render the custom view."""
  184. res = super(ServerConfiguration, self).fields_view_get(cr, uid,
  185. view_id,
  186. view_type,
  187. context,
  188. toolbar)
  189. if view_type == 'form':
  190. arch_node = self._arch
  191. xarch, xfields = self._view_look_dom_arch(cr, uid,
  192. arch_node,
  193. view_id,
  194. context=context)
  195. res['arch'] = xarch
  196. res['fields'] = xfields
  197. return res
  198. def default_get(self, cr, uid, fields_list, context=None):
  199. res = {}
  200. for key in self._conf_defaults:
  201. if 'passw' in key and not self.show_passwords:
  202. res[key] = '**********'
  203. else:
  204. res[key] = self._conf_defaults[key]()
  205. return res