55e2e858e9d0d2032ff188f93848bccdc73c5635
[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 OpenERP - Server
33 OpenERP 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 #----------------------------------------------------------
45 # python imports
46 #----------------------------------------------------------
47 import sys, os, signal
48 #----------------------------------------------------------
49 # ubuntu 8.04 has obsoleted `pyxml` package and installs here.
50 # the path needs to be updated before any `import xml`
51 # TODO: remove PyXML dependencies, use lxml instead.
52 #----------------------------------------------------------
53 _oldxml = '/usr/lib/python%s/site-packages/oldxml' % sys.version[:3]
54 if os.path.exists(_oldxml):
55     sys.path.append(_oldxml)
56
57 #----------------------------------------------------------
58 # get logger
59 #----------------------------------------------------------
60 import netsvc
61
62 netsvc.init_logger()
63
64 logger = netsvc.Logger()
65
66 #-----------------------------------------------------------------------
67 # import the tools module so that the commandline parameters are parsed
68 #-----------------------------------------------------------------------
69 import tools
70 import time
71
72 if sys.platform == 'win32':
73     import mx.DateTime
74     mx.DateTime.strptime = lambda x, y: mx.DateTime.mktime(time.strptime(x, y))
75
76 #os.chdir(tools.file_path_root)
77
78 #----------------------------------------------------------
79 # init net service
80 #----------------------------------------------------------
81 logger.notifyChannel("objects", netsvc.LOG_INFO, 'initialising distributed objects services')
82
83 dispatcher = netsvc.Dispatcher()
84 dispatcher.monitor(signal.SIGINT)
85
86 #---------------------------------------------------------------
87 # connect to the database and initialize it with base if needed
88 #---------------------------------------------------------------
89 logger.notifyChannel("init", netsvc.LOG_INFO, 'connecting to database')
90
91 import psycopg
92 import pooler
93
94 # try to connect to the database
95 try:
96 #   pooler.init()
97     pass
98 except psycopg.OperationalError, err:
99     logger.notifyChannel("init", netsvc.LOG_ERROR, "could not connect to database '%s'!" % (tools.config["db_name"],))
100
101     msg = str(err).replace("FATAL:", "").strip()
102     db_msg = "database \"%s\" does not exist" % (tools.config["db_name"],)
103
104     # Note: this is ugly but since psycopg only uses one exception for all errors
105     # I don't think it's possible to do differently
106     if msg == db_msg:
107         print """
108     this database does not exist
109
110 You need to create it using the command:
111
112     createdb --encoding=UNICODE '%s'
113
114 When you run openerp-server for the first time it will initialise the
115 database. You may force this behaviour at a later time by using the command:
116
117     ./openerp-server --init=all
118
119 Two accounts will be created by default:
120     1. login: admin      password : admin
121     2. login: demo       password : demo
122
123 """ % (tools.config["db_name"])
124     else:
125         print "\n    "+msg+"\n"
126     sys.exit(1)
127
128 db_name = tools.config["db_name"]
129
130 # test whether it is needed to initialize the db (the db is empty)
131 try:
132     cr = pooler.get_db_only(db_name).cursor()
133 except psycopg.OperationalError:
134     logger.notifyChannel("init", netsvc.LOG_INFO, "could not connect to database '%s'!" % db_name,)
135     cr = None
136 if cr:
137     cr.execute("SELECT relname FROM pg_class WHERE relkind='r' AND relname='ir_ui_menu'")
138     if len(cr.fetchall())==0:
139 #if False:
140         logger.notifyChannel("init", netsvc.LOG_INFO, "init db")
141         tools.init_db(cr)
142         # in that case, force --init=all
143         tools.config["init"]["all"] = 1
144         tools.config['update']['all'] = 1
145         if not tools.config['without_demo']:
146             tools.config["demo"]['all'] = 1
147     cr.close()
148
149 #----------------------------------------------------------
150 # launch modules install/upgrade/removes if needed
151 #----------------------------------------------------------
152 if tools.config['upgrade']:
153     print 'Upgrading new modules...'
154     import tools.upgrade
155     (toinit, toupdate) = tools.upgrade.upgrade()
156     for m in toinit:
157         tools.config['init'][m] = 1
158     for m in toupdate:
159         tools.config['update'][m] = 1
160
161 #----------------------------------------------------------
162 # import basic modules
163 #----------------------------------------------------------
164 import osv, workflow, report, service
165
166 #----------------------------------------------------------
167 # import addons
168 #----------------------------------------------------------
169 import addons
170
171 addons.register_classes()
172 if tools.config['init'] or tools.config['update']:
173     pooler.get_db_and_pool(tools.config['db_name'], update_module=True)
174
175 #----------------------------------------------------------
176 # translation stuff
177 #----------------------------------------------------------
178 if tools.config["translate_out"]:
179     import csv
180
181     if tools.config["language"]:
182         msg = "language %s" % (tools.config["language"],)
183     else:
184         msg = "new language"
185     logger.notifyChannel("init", netsvc.LOG_INFO, 'writing translation file for %s to %s' % (msg, tools.config["translate_out"]))
186
187     fileformat = os.path.splitext(tools.config["translate_out"])[-1][1:].lower()
188     buf = file(tools.config["translate_out"], "w")
189     tools.trans_export(tools.config["language"], tools.config["translate_modules"], buf, fileformat)
190     buf.close()
191
192     logger.notifyChannel("init", netsvc.LOG_INFO, 'translation file written succesfully')
193     sys.exit(0)
194
195 if tools.config["translate_in"]:
196     tools.trans_load(tools.config["db_name"], tools.config["translate_in"], tools.config["language"])
197     sys.exit(0)
198
199 #----------------------------------------------------------------------------------
200 # if we don't want the server to continue to run after initialization, we quit here
201 #----------------------------------------------------------------------------------
202 if tools.config["stop_after_init"]:
203     sys.exit(0)
204
205
206 #----------------------------------------------------------
207 # Launch Server
208 #----------------------------------------------------------
209
210 if tools.config['xmlrpc']:
211     try:
212         port = int(tools.config["port"])
213     except Exception:
214         logger.notifyChannel("init", netsvc.LOG_ERROR, "invalid port '%s'!" % (tools.config["port"],))
215         sys.exit(1)
216     interface = tools.config["interface"]
217     secure = tools.config["secure"]
218
219     httpd = netsvc.HttpDaemon(interface, port, secure)
220
221     if tools.config["xmlrpc"]:
222         xml_gw = netsvc.xmlrpc.RpcGateway('web-services')
223         httpd.attach("/xmlrpc", xml_gw)
224         logger.notifyChannel("web-services", netsvc.LOG_INFO,
225                 "starting XML-RPC" + \
226                         (tools.config['secure'] and ' Secure' or '') + \
227                         " services, port " + str(port))
228
229     #
230     #if tools.config["soap"]:
231     #   soap_gw = netsvc.xmlrpc.RpcGateway('web-services')
232     #   httpd.attach("/soap", soap_gw )
233     #   logger.notifyChannel("web-services", netsvc.LOG_INFO, 'starting SOAP services, port '+str(port))
234     #
235
236 if tools.config['netrpc']:
237     try:
238         netport = int(tools.config["netport"])
239     except Exception:
240         logger.notifyChannel("init", netsvc.LOG_ERROR, "invalid port '%s'!" % (tools.config["netport"],))
241         sys.exit(1)
242     netinterface = tools.config["netinterface"]
243
244     tinySocket = netsvc.TinySocketServerThread(netinterface, netport, False)
245     logger.notifyChannel("web-services", netsvc.LOG_INFO, "starting netrpc service, port "+str(netport))
246
247
248 def handler(signum, frame):
249     from tools import config
250     if tools.config['netrpc']:
251         tinySocket.stop()
252     if tools.config['xmlrpc']:
253         httpd.stop()
254     netsvc.Agent.quit()
255     if config['pidfile']:
256         os.unlink(config['pidfile'])
257     sys.exit(0)
258
259 from tools import config
260 if config['pidfile']:
261     fd = open(config['pidfile'], 'w')
262     pidtext = "%d" % (os.getpid())
263     fd.write(pidtext)
264     fd.close()
265
266 signal.signal(signal.SIGINT, handler)
267 signal.signal(signal.SIGTERM, handler)
268
269 logger.notifyChannel("web-services", netsvc.LOG_INFO, 'the server is running, waiting for connections...')
270 if tools.config['netrpc']:
271     tinySocket.start()
272 if tools.config['xmlrpc']:
273     httpd.start()
274 #dispatcher.run()
275
276 while True:
277     time.sleep(1)
278
279 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
280