[FIX]account:[trunk] accounting - GL report (and others) - repeat column headers
[odoo/odoo.git] / bin / openerp-server.py
1 #!/usr/bin/env python
2 # -*- coding: utf-8 -*-
3 ##############################################################################
4 #
5 #    OpenERP, Open Source Management Solution
6 #    Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>).
7 #
8 #    This program is free software: you can redistribute it and/or modify
9 #    it under the terms of the GNU Affero General Public License as
10 #    published by the Free Software Foundation, either version 3 of the
11 #    License, or (at your option) any later version.
12 #
13 #    This program is distributed in the hope that it will be useful,
14 #    but WITHOUT ANY WARRANTY; without even the implied warranty of
15 #    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 #    GNU Affero General Public License for more details.
17 #
18 #    You should have received a copy of the GNU Affero General Public License
19 #    along with this program.  If not, see <http://www.gnu.org/licenses/>.
20 #
21 ##############################################################################
22
23 """
24 OpenERP - Server
25 OpenERP is an ERP+CRM program for small and medium businesses.
26
27 The whole source code is distributed under the terms of the
28 GNU Public Licence.
29
30 (c) 2003-TODAY, Fabien Pinckaers - OpenERP s.a.
31 """
32
33 #----------------------------------------------------------
34 # python imports
35 #----------------------------------------------------------
36 import logging
37 import os
38 import signal
39 import sys
40 import threading
41 import traceback
42
43 import release
44 __author__ = release.author
45 __version__ = release.version
46
47 if os.name == 'posix':
48     import pwd
49     # We DON't log this using the standard logger, because we might mess
50     # with the logfile's permissions. Just do a quick exit here.
51     if pwd.getpwuid(os.getuid())[0] == 'root' :
52         sys.stderr.write("Attempted to run OpenERP server as root. This is not good, aborting.\n")
53         sys.exit(1)
54
55 #----------------------------------------------------------
56 # get logger
57 #----------------------------------------------------------
58 import netsvc
59 logger = logging.getLogger('server')
60
61 #-----------------------------------------------------------------------
62 # import the tools module so that the commandline parameters are parsed
63 #-----------------------------------------------------------------------
64 import tools
65 logger.info("OpenERP version - %s", release.version)
66 for name, value in [('addons_path', tools.config['addons_path']),
67                     ('database hostname', tools.config['db_host'] or 'localhost'),
68                     ('database port', tools.config['db_port'] or '5432'),
69                     ('database user', tools.config['db_user'])]:
70     logger.info("%s - %s", name, value)
71
72 # Don't allow if the connection to PostgreSQL done by postgres user
73 if tools.config['db_user'] == 'postgres':
74     logger.error("Connecting to the database as 'postgres' user is forbidden, as it present major security issues. Shutting down.")
75     sys.exit(1)
76
77 import time
78
79 #----------------------------------------------------------
80 # init net service
81 #----------------------------------------------------------
82 logger.info('initialising distributed objects services')
83
84 #---------------------------------------------------------------
85 # connect to the database and initialize it with base if needed
86 #---------------------------------------------------------------
87 import pooler
88
89 #----------------------------------------------------------
90 # import basic modules
91 #----------------------------------------------------------
92 import osv
93 import workflow
94 import report
95 import service
96
97 #----------------------------------------------------------
98 # import addons
99 #----------------------------------------------------------
100
101 import addons
102
103 #----------------------------------------------------------
104 # Load and update databases if requested
105 #----------------------------------------------------------
106
107 import service.http_server
108
109 if not ( tools.config["stop_after_init"] or \
110     tools.config["translate_in"] or \
111     tools.config["translate_out"] ):
112     service.http_server.init_servers()
113     service.http_server.init_xmlrpc()
114     service.http_server.init_static_http()
115
116     import service.netrpc_server
117     service.netrpc_server.init_servers()
118
119 if tools.config['db_name']:
120     for dbname in tools.config['db_name'].split(','):
121         db,pool = pooler.get_db_and_pool(dbname, update_module=tools.config['init'] or tools.config['update'], pooljobs=False)
122         if tools.config["test_file"]:
123             logger.info('loading test file %s', tools.config["test_file"])
124             cr = db.cursor()
125             tools.convert_yaml_import(cr, 'base', file(tools.config["test_file"]), {}, 'test', True)
126             cr.rollback()
127         pool.get('ir.cron')._poolJobs(db.dbname)
128
129 #----------------------------------------------------------
130 # translation stuff
131 #----------------------------------------------------------
132 if tools.config["translate_out"]:
133     import csv
134
135     if tools.config["language"]:
136         msg = "language %s" % (tools.config["language"],)
137     else:
138         msg = "new language"
139     logger.info('writing translation file for %s to %s', msg, tools.config["translate_out"])
140
141     fileformat = os.path.splitext(tools.config["translate_out"])[-1][1:].lower()
142     buf = file(tools.config["translate_out"], "w")
143     tools.trans_export(tools.config["language"], tools.config["translate_modules"], buf, fileformat)
144     buf.close()
145
146     logger.info('translation file written successfully')
147     sys.exit(0)
148
149 if tools.config["translate_in"]:
150     tools.trans_load(tools.config["db_name"], 
151                      tools.config["translate_in"], 
152                      tools.config["language"])
153     sys.exit(0)
154
155 #----------------------------------------------------------------------------------
156 # if we don't want the server to continue to run after initialization, we quit here
157 #----------------------------------------------------------------------------------
158 if tools.config["stop_after_init"]:
159     sys.exit(0)
160
161
162 #----------------------------------------------------------
163 # Launch Servers
164 #----------------------------------------------------------
165
166 LST_SIGNALS = ['SIGINT', 'SIGTERM']
167
168 SIGNALS = dict(
169     [(getattr(signal, sign), sign) for sign in LST_SIGNALS]
170 )
171
172 netsvc.quit_signals_received = 0
173
174 def handler(signum, frame):
175     """
176     :param signum: the signal number
177     :param frame: the interrupted stack frame or None
178     """
179     netsvc.quit_signals_received += 1
180     if netsvc.quit_signals_received > 1:
181         sys.stderr.write("Forced shutdown.\n")
182         os._exit(0)
183
184 def dumpstacks(signum, frame):
185     # code from http://stackoverflow.com/questions/132058/getting-stack-trace-from-a-running-python-application#answer-2569696
186     # modified for python 2.5 compatibility
187     thread_map = dict(threading._active, **threading._limbo)
188     id2name = dict([(threadId, thread.getName()) for threadId, thread in thread_map.items()])
189     code = []
190     for threadId, stack in sys._current_frames().items():
191         code.append("\n# Thread: %s(%d)" % (id2name[threadId], threadId))
192         for filename, lineno, name, line in traceback.extract_stack(stack):
193             code.append('File: "%s", line %d, in %s' % (filename, lineno, name))
194             if line:
195                 code.append("  %s" % (line.strip()))
196     logging.getLogger('dumpstacks').info("\n".join(code))
197
198 for signum in SIGNALS:
199     signal.signal(signum, handler)
200
201 if os.name == 'posix':
202     signal.signal(signal.SIGQUIT, dumpstacks)
203
204 def quit():
205     netsvc.Agent.quit()
206     netsvc.Server.quitAll()
207     if tools.config['pidfile']:
208         os.unlink(tools.config['pidfile'])
209     logger = logging.getLogger('shutdown')
210     logger.info("Initiating OpenERP Server shutdown")
211     logger.info("Hit CTRL-C again or send a second signal to immediately terminate the server...")
212     logging.shutdown()
213
214     # manually join() all threads before calling sys.exit() to allow a second signal
215     # to trigger _force_quit() in case some non-daemon threads won't exit cleanly.
216     # threading.Thread.join() should not mask signals (at least in python 2.5)
217     for thread in threading.enumerate():
218         if thread != threading.currentThread() and not thread.isDaemon():
219             while thread.isAlive():
220                 # need a busyloop here as thread.join() masks signals
221                 # and would present the forced shutdown
222                 thread.join(0.05)
223                 time.sleep(0.05)
224     sys.exit(0)
225
226 if tools.config['pidfile']:
227     fd = open(tools.config['pidfile'], 'w')
228     pidtext = "%d" % (os.getpid())
229     fd.write(pidtext)
230     fd.close()
231
232 netsvc.Server.startAll()
233
234 logger.info('OpenERP server is running, waiting for connections...')
235
236 while netsvc.quit_signals_received == 0:
237     time.sleep(60)
238
239 quit()
240
241 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: