f50aeefd423a1aac0b60a52317f6976e7ab77341
[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 db_name = tools.config["db_name"]
97
98 # test whether it is needed to initialize the db (the db is empty)
99 #try:
100 #    cr = pooler.get_db_only(db_name).cursor()
101 #except psycopg.OperationalError:
102 #    logger.notifyChannel("init", netsvc.LOG_INFO, "could not connect to database '%s'!" % db_name,)
103 #    cr = None
104 #if cr:
105 #    cr.execute("SELECT relname FROM pg_class WHERE relkind='r' AND relname='ir_ui_menu'")
106 #    if len(cr.fetchall())==0:
107 ##if False:
108 #        logger.notifyChannel("init", netsvc.LOG_INFO, "init db")
109 #        tools.init_db(cr)
110 #        # in that case, force --init=all
111 #        tools.config["init"]["all"] = 1
112 #        tools.config['update']['all'] = 1
113 #        if not tools.config['without_demo']:
114 #            tools.config["demo"]['all'] = 1
115 #    cr.close()
116
117 #----------------------------------------------------------
118 # launch modules install/upgrade/removes if needed
119 #----------------------------------------------------------
120 if tools.config['upgrade']:
121     print 'Upgrading new modules...'
122     import tools.upgrade
123     (toinit, toupdate) = tools.upgrade.upgrade()
124     for m in toinit:
125         tools.config['init'][m] = 1
126     for m in toupdate:
127         tools.config['update'][m] = 1
128
129 #----------------------------------------------------------
130 # import basic modules
131 #----------------------------------------------------------
132 import osv, workflow, report, service
133
134 #----------------------------------------------------------
135 # import addons
136 #----------------------------------------------------------
137 import addons
138
139 addons.register_classes()
140 if tools.config['init'] or tools.config['update']:
141     pooler.get_db_and_pool(tools.config['db_name'], update_module=True)
142
143 #----------------------------------------------------------
144 # translation stuff
145 #----------------------------------------------------------
146 if tools.config["translate_out"]:
147     import csv
148
149     if tools.config["language"]:
150         msg = "language %s" % (tools.config["language"],)
151     else:
152         msg = "new language"
153     logger.notifyChannel("init", netsvc.LOG_INFO, 'writing translation file for %s to %s' % (msg, tools.config["translate_out"]))
154
155     fileformat = os.path.splitext(tools.config["translate_out"])[-1][1:].lower()
156     buf = file(tools.config["translate_out"], "w")
157     tools.trans_export(tools.config["language"], tools.config["translate_modules"], buf, fileformat)
158     buf.close()
159
160     logger.notifyChannel("init", netsvc.LOG_INFO, 'translation file written succesfully')
161     sys.exit(0)
162
163 if tools.config["translate_in"]:
164     tools.trans_load(tools.config["db_name"], tools.config["translate_in"], tools.config["language"])
165     sys.exit(0)
166
167 #----------------------------------------------------------------------------------
168 # if we don't want the server to continue to run after initialization, we quit here
169 #----------------------------------------------------------------------------------
170 if tools.config["stop_after_init"]:
171     sys.exit(0)
172
173
174 #----------------------------------------------------------
175 # Launch Server
176 #----------------------------------------------------------
177
178 if tools.config['xmlrpc']:
179     try:
180         port = int(tools.config["port"])
181     except Exception:
182         logger.notifyChannel("init", netsvc.LOG_ERROR, "invalid port '%s'!" % (tools.config["port"],))
183         sys.exit(1)
184     interface = tools.config["interface"]
185     secure = tools.config["secure"]
186
187     httpd = netsvc.HttpDaemon(interface, port, secure)
188
189     if tools.config["xmlrpc"]:
190         xml_gw = netsvc.xmlrpc.RpcGateway('web-services')
191         httpd.attach("/xmlrpc", xml_gw)
192         logger.notifyChannel("web-services", netsvc.LOG_INFO,
193                 "starting XML-RPC" + \
194                         (tools.config['secure'] and ' Secure' or '') + \
195                         " services, port " + str(port))
196
197     #
198     #if tools.config["soap"]:
199     #   soap_gw = netsvc.xmlrpc.RpcGateway('web-services')
200     #   httpd.attach("/soap", soap_gw )
201     #   logger.notifyChannel("web-services", netsvc.LOG_INFO, 'starting SOAP services, port '+str(port))
202     #
203
204 if tools.config['netrpc']:
205     try:
206         netport = int(tools.config["netport"])
207     except Exception:
208         logger.notifyChannel("init", netsvc.LOG_ERROR, "invalid port '%s'!" % (tools.config["netport"],))
209         sys.exit(1)
210     netinterface = tools.config["netinterface"]
211
212     tinySocket = netsvc.TinySocketServerThread(netinterface, netport, False)
213     logger.notifyChannel("web-services", netsvc.LOG_INFO, "starting netrpc service, port "+str(netport))
214
215
216 def handler(signum, frame):
217     from tools import config
218     if tools.config['netrpc']:
219         tinySocket.stop()
220     if tools.config['xmlrpc']:
221         httpd.stop()
222     netsvc.Agent.quit()
223     if config['pidfile']:
224         os.unlink(config['pidfile'])
225     sys.exit(0)
226
227 from tools import config
228 if config['pidfile']:
229     fd = open(config['pidfile'], 'w')
230     pidtext = "%d" % (os.getpid())
231     fd.write(pidtext)
232     fd.close()
233
234 signal.signal(signal.SIGINT, handler)
235 signal.signal(signal.SIGTERM, handler)
236
237 logger.notifyChannel("web-services", netsvc.LOG_INFO, 'the server is running, waiting for connections...')
238 if tools.config['netrpc']:
239     tinySocket.start()
240 if tools.config['xmlrpc']:
241     httpd.start()
242 #dispatcher.run()
243
244 while True:
245     time.sleep(1)
246
247 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
248