e5d9f2626b3169bbb2e10e0af3eb19cbe5aaf50a
[odoo/odoo.git] / bin / openerp-server.py
1 #!/usr/bin/python
2 # -*- encoding: utf-8 -*-
3 ##############################################################################
4 #
5 # Copyright (c) 2004-2008 Tiny SPRL (http://tiny.be) All Rights Reserved.
6 #
7 # $Id$
8 #
9 # WARNING: This program as such is intended to be used by professional
10 # programmers who take the whole responsability of assessing all potential
11 # consequences resulting from its eventual inadequacies and bugs
12 # End users who are looking for a ready-to-use solution with commercial
13 # garantees and support are strongly adviced to contract a Free Software
14 # Service Company
15 #
16 # This program is Free Software; you can redistribute it and/or
17 # modify it under the terms of the GNU General Public License
18 # as published by the Free Software Foundation; either version 2
19 # of the License, or (at your option) any later version.
20 #
21 # This program is distributed in the hope that it will be useful,
22 # but WITHOUT ANY WARRANTY; without even the implied warranty of
23 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
24 # GNU General Public License for more details.
25 #
26 # You should have received a copy of the GNU General Public License
27 # along with this program; if not, write to the Free Software
28 # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
29 ###############################################################################
30
31 """
32 Tiny ERP - Server
33 Tiny ERP is an ERP+CRM program for small and medium businesses.
34
35 The whole source code is distributed under the terms of the
36 GNU Public Licence.
37
38 (c) 2003-TODAY, Fabien Pinckaers - Tiny sprl
39 """
40 import release
41 __author__ = release.author
42 __version__ = release.version
43
44 import __builtin__
45 __builtin__.__dict__['tinyerp_version'] = __version__
46 __builtin__.__dict__['tinyerp_version_string'] = "Tiny ERP Server " + __version__
47
48
49
50 #----------------------------------------------------------
51 # python imports
52 #----------------------------------------------------------
53 import sys, os, signal
54 #----------------------------------------------------------
55 # ubuntu 8.04 has obsoleted `pyxml` package and installs here.
56 # the path needs to be updated before any `import xml`
57 # TODO: remove PyXML dependencies, use lxml instead.
58 #----------------------------------------------------------
59 _oldxml = '/usr/lib/python%s/site-packages/oldxml' % sys.version[:3]
60 if os.path.exists(_oldxml):
61     sys.path.append(_oldxml)
62
63 #----------------------------------------------------------
64 # get logger
65 #----------------------------------------------------------
66 import netsvc
67
68 netsvc.init_logger()
69
70 logger = netsvc.Logger()
71
72 #-----------------------------------------------------------------------
73 # import the tools module so that the commandline parameters are parsed
74 #-----------------------------------------------------------------------
75 import tools
76 import time
77
78 if sys.platform == 'win32':
79     import mx.DateTime
80     mx.DateTime.strptime = lambda x, y: mx.DateTime.mktime(time.strptime(x, y))
81
82 #os.chdir(tools.file_path_root)
83
84 #----------------------------------------------------------
85 # init net service
86 #----------------------------------------------------------
87 logger.notifyChannel("objects", netsvc.LOG_INFO, 'initialising distributed objects services')
88
89 dispatcher = netsvc.Dispatcher()
90 dispatcher.monitor(signal.SIGINT)
91
92 #---------------------------------------------------------------
93 # connect to the database and initialize it with base if needed
94 #---------------------------------------------------------------
95 logger.notifyChannel("init", netsvc.LOG_INFO, 'connecting to database')
96
97 import psycopg
98 import pooler
99
100 # try to connect to the database
101 try:
102 #   pooler.init()
103     pass
104 except psycopg.OperationalError, err:
105     logger.notifyChannel("init", netsvc.LOG_ERROR, "could not connect to database '%s'!" % (tools.config["db_name"],))
106
107     msg = str(err).replace("FATAL:", "").strip()
108     db_msg = "database \"%s\" does not exist" % (tools.config["db_name"],)
109
110     # Note: this is ugly but since psycopg only uses one exception for all errors
111     # I don't think it's possible to do differently
112     if msg == db_msg:
113         print """
114     this database does not exist
115
116 You need to create it using the command:
117
118     createdb --encoding=UNICODE '%s'
119
120 When you run tinyerp-server for the first time it will initialise the
121 database. You may force this behaviour at a later time by using the command:
122
123     ./tinyerp-server --init=all
124
125 Two accounts will be created by default:
126     1. login: admin      password : admin
127     2. login: demo       password : demo
128
129 """ % (tools.config["db_name"])
130     else:
131         print "\n    "+msg+"\n"
132     sys.exit(1)
133
134 db_name = tools.config["db_name"]
135
136 # test whether it is needed to initialize the db (the db is empty)
137 try:
138     cr = pooler.get_db_only(db_name).cursor()
139 except psycopg.OperationalError:
140     logger.notifyChannel("init", netsvc.LOG_INFO, "could not connect to database '%s'!" % db_name,)
141     cr = None
142 if cr:
143     cr.execute("SELECT relname FROM pg_class WHERE relkind='r' AND relname='ir_ui_menu'")
144     if len(cr.fetchall())==0:
145 #if False:
146         logger.notifyChannel("init", netsvc.LOG_INFO, "init db")
147         tools.init_db(cr)
148         # in that case, force --init=all
149         tools.config["init"]["all"] = 1
150         tools.config['update']['all'] = 1
151         if not tools.config['without_demo']:
152             tools.config["demo"]['all'] = 1
153     cr.close()
154
155 #----------------------------------------------------------
156 # launch modules install/upgrade/removes if needed
157 #----------------------------------------------------------
158 if tools.config['upgrade']:
159     print 'Upgrading new modules...'
160     import tools.upgrade
161     (toinit, toupdate) = tools.upgrade.upgrade()
162     for m in toinit:
163         tools.config['init'][m] = 1
164     for m in toupdate:
165         tools.config['update'][m] = 1
166
167 #----------------------------------------------------------
168 # import basic modules
169 #----------------------------------------------------------
170 import osv, workflow, report, service
171
172 #----------------------------------------------------------
173 # import addons
174 #----------------------------------------------------------
175 import addons
176
177 addons.register_classes()
178 if tools.config['init'] or tools.config['update']:
179     pooler.get_db_and_pool(tools.config['db_name'], update_module=True)
180
181 #----------------------------------------------------------
182 # translation stuff
183 #----------------------------------------------------------
184 if tools.config["translate_out"]:
185     import csv
186
187     if tools.config["language"]:
188         msg = "language %s" % (tools.config["language"],)
189     else:
190         msg = "new language"
191     logger.notifyChannel("init", netsvc.LOG_INFO, 'writing translation file for %s to %s' % (msg, tools.config["translate_out"]))
192
193     fileformat = os.path.splitext(tools.config["translate_out"])[-1][1:].lower()
194     buf = file(tools.config["translate_out"], "w")
195     tools.trans_export(tools.config["language"], tools.config["translate_modules"], buf, fileformat)
196     buf.close()
197
198     logger.notifyChannel("init", netsvc.LOG_INFO, 'translation file written succesfully')
199     sys.exit(0)
200
201 if tools.config["translate_in"]:
202     tools.trans_load(tools.config["db_name"], tools.config["translate_in"], tools.config["language"])
203     sys.exit(0)
204
205 #----------------------------------------------------------------------------------
206 # if we don't want the server to continue to run after initialization, we quit here
207 #----------------------------------------------------------------------------------
208 if tools.config["stop_after_init"]:
209     sys.exit(0)
210
211
212 #----------------------------------------------------------
213 # Launch Server
214 #----------------------------------------------------------
215
216 if tools.config['xmlrpc']:
217     try:
218         port = int(tools.config["port"])
219     except Exception:
220         logger.notifyChannel("init", netsvc.LOG_ERROR, "invalid port '%s'!" % (tools.config["port"],))
221         sys.exit(1)
222     interface = tools.config["interface"]
223     secure = tools.config["secure"]
224
225     httpd = netsvc.HttpDaemon(interface, port, secure)
226
227     if tools.config["xmlrpc"]:
228         xml_gw = netsvc.xmlrpc.RpcGateway('web-services')
229         httpd.attach("/xmlrpc", xml_gw)
230         logger.notifyChannel("web-services", netsvc.LOG_INFO,
231                 "starting XML-RPC" + \
232                         (tools.config['secure'] and ' Secure' or '') + \
233                         " services, port " + str(port))
234
235     #
236     #if tools.config["soap"]:
237     #   soap_gw = netsvc.xmlrpc.RpcGateway('web-services')
238     #   httpd.attach("/soap", soap_gw )
239     #   logger.notifyChannel("web-services", netsvc.LOG_INFO, 'starting SOAP services, port '+str(port))
240     #
241
242 if tools.config['netrpc']:
243     try:
244         netport = int(tools.config["netport"])
245     except Exception:
246         logger.notifyChannel("init", netsvc.LOG_ERROR, "invalid port '%s'!" % (tools.config["netport"],))
247         sys.exit(1)
248     netinterface = tools.config["netinterface"]
249
250     tinySocket = netsvc.TinySocketServerThread(netinterface, netport, False)
251     logger.notifyChannel("web-services", netsvc.LOG_INFO, "starting netrpc service, port "+str(netport))
252
253
254 def handler(signum, frame):
255     from tools import config
256     if tools.config['netrpc']:
257         tinySocket.stop()
258     if tools.config['xmlrpc']:
259         httpd.stop()
260     netsvc.Agent.quit()
261     if config['pidfile']:
262         os.unlink(config['pidfile'])
263     sys.exit(0)
264
265 from tools import config
266 if config['pidfile']:
267     fd = open(config['pidfile'], 'w')
268     pidtext = "%d" % (os.getpid())
269     fd.write(pidtext)
270     fd.close()
271
272 signal.signal(signal.SIGINT, handler)
273 signal.signal(signal.SIGTERM, handler)
274
275 logger.notifyChannel("web-services", netsvc.LOG_INFO, 'the server is running, waiting for connections...')
276 if tools.config['netrpc']:
277     tinySocket.start()
278 if tools.config['xmlrpc']:
279     httpd.start()
280 #dispatcher.run()
281
282 while True:
283     time.sleep(1)
284
285 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
286