f4a3674e67ebfa5f7ee4671e43689389d282a2c6
[odoo/odoo.git] / bin / tools / config.py
1 # -*- encoding: utf-8 -*-
2 ##############################################################################
3 #
4 # Copyright (c) 2004-2008 Tiny SPRL (http://tiny.be) All Rights Reserved.
5 #
6 # $Id$
7 #
8 # WARNING: This program as such is intended to be used by professional
9 # programmers who take the whole responsability of assessing all potential
10 # consequences resulting from its eventual inadequacies and bugs
11 # End users who are looking for a ready-to-use solution with commercial
12 # garantees and support are strongly adviced to contract a Free Software
13 # Service Company
14 #
15 # This program is Free Software; you can redistribute it and/or
16 # modify it under the terms of the GNU General Public License
17 # as published by the Free Software Foundation; either version 2
18 # of the License, or (at your option) any later version.
19 #
20 # This program is distributed in the hope that it will be useful,
21 # but WITHOUT ANY WARRANTY; without even the implied warranty of
22 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
23 # GNU General Public License for more details.
24 #
25 # You should have received a copy of the GNU General Public License
26 # along with this program; if not, write to the Free Software
27 # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
28 ###############################################################################
29
30 import ConfigParser,optparse,os,sys
31 import netsvc,logging
32
33
34 class configmanager(object):
35     def __init__(self, fname=None):
36         self.options = {
37             'email_from':False,
38             'verbose': False,
39             'interface': '',    # this will bind the server to all interfaces
40             'port': '8069',
41             'netinterface': '',
42             'netport': '8070',
43             'db_host': False,
44             'db_port': False,
45             'db_name': 'terp',
46             'db_user': False,
47             'db_password': False,
48             'db_maxconn': 64,
49             'reportgz': False,
50             'netrpc': True,
51             'xmlrpc': True,
52             'soap': False,
53             'translate_in': None,
54             'translate_out': None,
55             'language': None,
56             'pg_path': None,
57             'admin_passwd': 'admin',
58             'addons_path': None,
59             'root_path': None,
60             'debug_mode': False,
61             'commit_mode': False,
62             'pidfile': None,
63             'logfile': None,
64             'secure': False,
65             'smtp_server': 'localhost',
66             'smtp_user': False,
67             'smtp_password': False,
68             'stop_after_init': False,   # this will stop the server after initialization
69             'price_accuracy': 2,
70             
71             'assert_exit_level': logging.WARNING, # level above which a failed assert will 
72         }
73         
74         assert_exit_levels = (netsvc.LOG_CRITICAL, netsvc.LOG_ERROR, netsvc.LOG_WARNING, netsvc.LOG_INFO, netsvc.LOG_DEBUG)
75
76         parser = optparse.OptionParser(version=tinyerp_version_string)
77         
78         parser.add_option("-c", "--config", dest="config", help="specify alternate config file")
79         parser.add_option("-s", "--save", action="store_true", dest="save", default=False, help="save configuration to ~/.terp_serverrc")
80         parser.add_option("-v", "--verbose", action="store_true", dest="verbose", default=False, help="enable debugging")
81         parser.add_option("--pidfile", dest="pidfile", help="file where the server pid will be stored")
82         parser.add_option("--logfile", dest="logfile", help="file where the server log will be stored")
83         
84         parser.add_option("-n", "--interface", dest="interface", help="specify the TCP IP address")
85         parser.add_option("-p", "--port", dest="port", help="specify the TCP port")
86         parser.add_option("--net_interface", dest="netinterface", help="specify the TCP IP address for netrpc")
87         parser.add_option("--net_port", dest="netport", help="specify the TCP port for netrpc")
88         parser.add_option("--no-netrpc", dest="netrpc", action="store_false", default=True, help="disable netrpc")
89         parser.add_option("--no-xmlrpc", dest="xmlrpc", action="store_false", default=True, help="disable xmlrpc")
90         
91         parser.add_option("-i", "--init", dest="init", help="init a module (use \"all\" for all modules)")
92         parser.add_option("--without-demo", dest="without_demo", help="load demo data for a module (use \"all\" for all modules)", default=False)
93         parser.add_option("-u", "--update", dest="update", help="update a module (use \"all\" for all modules)")
94         # stops the server from launching after initialization
95         parser.add_option("--stop-after-init", action="store_true", dest="stop_after_init", default=False, help="stop the server after it initializes")
96         parser.add_option('--debug', dest='debug_mode', action='store_true', default=False, help='enable debug mode')
97         parser.add_option("--assert-exit-level", dest='assert_exit_level', help="specify the level at which a failed assertion will stop the server " + str(assert_exit_levels))
98         parser.add_option("-S", "--secure", dest="secure", action="store_true", help="launch server over https instead of http", default=False)
99         parser.add_option('--email-from', dest='email_from', default='', help='specify the SMTP email address for sending email')
100         parser.add_option('--smtp', dest='smtp_server', default='', help='specify the SMTP server for sending email')
101         parser.add_option('--smtp-ssl', dest='smtp_ssl', default='', help='specify the SMTP server support SSL or not')
102         parser.add_option('--smtp-user', dest='smtp_user', default='', help='specify the SMTP username for sending email')
103         parser.add_option('--smtp-password', dest='smtp_password', default='', help='specify the SMTP password for sending email')
104         parser.add_option('--price_accuracy', dest='price_accuracy', default='2', help='specify the price accuracy')
105         
106         group = optparse.OptionGroup(parser, "Modules related options")
107         group.add_option("-g", "--upgrade", action="store_true", dest="upgrade", default=False, help="Upgrade/install/uninstall modules")
108
109         group = optparse.OptionGroup(parser, "Database related options")
110         group.add_option("-d", "--database", dest="db_name", help="specify the database name")
111         group.add_option("-r", "--db_user", dest="db_user", help="specify the database user name")
112         group.add_option("-w", "--db_password", dest="db_password", help="specify the database password") 
113         group.add_option("--pg_path", dest="pg_path", help="specify the pg executable path") 
114         group.add_option("--db_host", dest="db_host", help="specify the database host") 
115         group.add_option("--db_port", dest="db_port", help="specify the database port") 
116         group.add_option("--db_maxconn", dest="db_maxconn", default='64', help="specify the the maximum number of physical connections to posgresql")
117         group.add_option("-C", "--commit-mode", dest="commit_mode", action="store_true", help="Several commit during one file importation. Use this for big data importation.", default=False)
118         parser.add_option_group(group)
119
120         group = optparse.OptionGroup(parser, "Internationalisation options",
121             "Use these options to translate Tiny ERP to another language."
122             "See i18n section of the user manual. Options '-l' and '-d' are mandatory.")
123
124         group.add_option('-l', "--language", dest="language", help="specify the language of the translation file. Use it with --i18n-export and --i18n-import")
125         group.add_option("--i18n-export", dest="translate_out", help="export all sentences to be translated to a CSV or a PO file and exit")
126         group.add_option("--i18n-import", dest="translate_in", help="import a CSV or a PO file with translations and exit")
127         group.add_option("--modules", dest="translate_modules", help="specify modules to export. Use in combination with --i18n-export")
128         group.add_option("--addons-path", dest="addons_path", help="specify an alternative addons path.")
129         parser.add_option_group(group)
130
131         (opt, args) = parser.parse_args()
132
133         assert not ((opt.translate_in or opt.translate_out) and (not opt.language or not opt.db_name)), "the i18n-import and i18n-export options cannot be used without the language (-l) and database (-d) options"
134
135         # place/search the config file on Win32 near the server installation
136         # (../etc from the server)
137         # if the server is run by an unprivileged user, he has to specify location of a config file where he has the rights to write,
138         # else he won't be able to save the configurations, or even to start the server...
139         if os.name == 'nt':
140             rcfilepath = os.path.join(os.path.abspath(os.path.dirname(sys.argv[0])), 'tinyerp-server.conf')
141         else:
142             rcfilepath = os.path.expanduser('~/.terp_serverrc')
143
144         self.rcfile = fname or opt.config or os.environ.get('TERP_SERVER') or rcfilepath
145         self.load()
146         
147
148         # Verify that we want to log or not, if not the output will go to stdout
149         if self.options['logfile'] in ('None', 'False'):
150             self.options['logfile'] = False
151         # the same for the pidfile
152         if self.options['pidfile'] in ('None', 'False'):
153             self.options['pidfile'] = False
154         
155         for arg in ('interface', 'port', 'db_name', 'db_user', 'db_password', 'db_host',
156                 'db_port', 'logfile', 'pidfile', 'secure', 'smtp_ssl', 'email_from', 'smtp_server', 'smtp_user', 'smtp_password', 'price_accuracy', 'netinterface', 'netport', 'db_maxconn', 'commit_mode', 'addons_path'):
157             if getattr(opt, arg):
158                 self.options[arg] = getattr(opt, arg)
159
160         for arg in ('language', 'translate_out', 'translate_in', 
161             'upgrade', 'verbose', 'debug_mode', 
162             'stop_after_init', 'without_demo', 'netrpc', 'xmlrpc'):
163             self.options[arg] = getattr(opt, arg)
164         
165         if opt.assert_exit_level:
166             assert opt.assert_exit_level in assert_exit_levels, 'ERROR: The assert-exit-level must be one of those values: '+str(assert_exit_levels)
167             self.options['assert_exit_level'] = getattr(logging, opt.assert_exit_level.upper())
168             
169         if not self.options['root_path'] or self.options['root_path']=='None':
170             self.options['root_path'] = os.path.abspath(os.path.dirname(sys.argv[0]))
171         if not self.options['addons_path'] or self.options['addons_path']=='None':
172             self.options['addons_path'] = os.path.join(self.options['root_path'], 'addons')
173
174         init = {}
175         if opt.init:
176             for i in opt.init.split(','):
177                 init[i] = 1
178         self.options['init'] = init
179         self.options["demo"] = not opt.without_demo and self.options['init'] or {}
180
181         update = {}
182         if opt.update:
183             for i in opt.update.split(','):
184                 update[i] = 1
185         self.options['update'] = update
186
187         self.options['translate_modules'] = opt.translate_modules and map(lambda m: m.strip(), opt.translate_modules.split(',')) or ['all']
188         self.options['translate_modules'].sort()
189         
190         if opt.pg_path:
191             self.options['pg_path'] = opt.pg_path
192
193         if self.options.get('language', False):
194             assert len(self.options['language'])<=5, 'ERROR: The Lang name must take max 5 chars, Eg: -lfr_BE'
195         if opt.save:
196             self.save()
197
198     def load(self):
199         p = ConfigParser.ConfigParser()
200         try:
201             p.read([self.rcfile])
202             for (name,value) in p.items('options'):
203                 if value=='True' or value=='true':
204                     value = True
205                 if value=='False' or value=='false':
206                     value = False
207                 self.options[name] = value
208         except IOError:
209             pass
210         except ConfigParser.NoSectionError:
211             pass
212
213     def save(self):
214         p = ConfigParser.ConfigParser()
215         p.add_section('options')
216         for o in [opt for opt in self.options.keys() if opt not in ('version','language','translate_out','translate_in','init','update')]:
217             p.set('options', o, self.options[o])
218
219         # try to create the directories and write the file
220         try:
221             if not os.path.exists(os.path.dirname(self.rcfile)):
222                 os.makedirs(os.path.dirname(self.rcfile))
223             try:
224                 p.write(file(self.rcfile, 'w'))
225             except IOError:
226                 sys.stderr.write("ERROR: couldn't write the config file\n")
227
228         except OSError:
229             # what to do if impossible?
230             sys.stderr.write("ERROR: couldn't create the config directory\n")
231
232     def get(self, key, default=None):
233         return self.options.get(key, default)
234
235     def __setitem__(self, key, value):
236         self.options[key] = value
237
238     def __getitem__(self, key):
239         return self.options[key]
240
241 config = configmanager()
242
243
244
245 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
246