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