[FIX] openerp-server: start cron jobs in their own threads
[odoo/odoo.git] / openerp-server
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 import time
43
44 import openerp
45 __author__ = openerp.release.author
46 __version__ = openerp.release.version
47
48 if os.name == 'posix':
49     import pwd
50     # We DON't log this using the standard logger, because we might mess
51     # with the logfile's permissions. Just do a quick exit here.
52     if pwd.getpwuid(os.getuid())[0] == 'root' :
53         sys.stderr.write("Attempted to run OpenERP server as root. This is not good, aborting.\n")
54         sys.exit(1)
55
56 #-----------------------------------------------------------------------
57 # parse the command line
58 #-----------------------------------------------------------------------
59 openerp.tools.config.parse_config(sys.argv[1:])
60 config = openerp.tools.config
61
62 #----------------------------------------------------------
63 # get logger
64 #----------------------------------------------------------
65 openerp.netsvc.init_logger()
66 logger = logging.getLogger('server')
67
68 logger.info("OpenERP version - %s", __version__)
69 for name, value in [('addons_path', config['addons_path']),
70                     ('database hostname', config['db_host'] or 'localhost'),
71                     ('database port', config['db_port'] or '5432'),
72                     ('database user', config['db_user'])]:
73     logger.info("%s - %s", name, value)
74
75 # Don't allow if the connection to PostgreSQL done by postgres user
76 if config['db_user'] == 'postgres':
77     logger.error("Connecting to the database as 'postgres' user is forbidden, as it present major security issues. Shutting down.")
78     sys.exit(1)
79
80 #----------------------------------------------------------
81 # init net service
82 #----------------------------------------------------------
83 logger.info('initialising distributed objects services')
84
85 #----------------------------------------------------------
86 # Load and update databases if requested
87 #----------------------------------------------------------
88
89 if not ( config["stop_after_init"] or \
90     config["translate_in"] or \
91     config["translate_out"] ):
92     openerp.osv.osv.start_object_proxy()
93     openerp.service.web_services.start_web_services()
94     http_server = openerp.service.http_server
95     netrpc_server = openerp.service.netrpc_server
96     http_server.init_servers()
97     http_server.init_xmlrpc()
98     http_server.init_static_http()
99     netrpc_server.init_servers()
100
101 if config['db_name']:
102     for dbname in config['db_name'].split(','):
103         db, pool = openerp.pooler.get_db_and_pool(dbname, update_module=config['init'] or config['update'], pooljobs=False)
104         cr = db.cursor()
105
106         if config["test_file"]:
107             logger.info('loading test file %s', config["test_file"])
108             openerp.tools.convert_yaml_import(cr, 'base', file(config["test_file"]), {}, 'test', True)
109             cr.rollback()
110
111         pool.get('ir.cron').restart(db.dbname)
112
113         cr.close()
114
115 #----------------------------------------------------------
116 # translation stuff
117 #----------------------------------------------------------
118 if config["translate_out"]:
119     if config["language"]:
120         msg = "language %s" % (config["language"],)
121     else:
122         msg = "new language"
123     logger.info('writing translation file for %s to %s', msg, config["translate_out"])
124
125     fileformat = os.path.splitext(config["translate_out"])[-1][1:].lower()
126     buf = file(config["translate_out"], "w")
127     dbname = config['db_name']
128     cr = openerp.pooler.get_db(dbname).cursor()
129     openerp.tools.trans_export(config["language"], config["translate_modules"] or ["all"], buf, fileformat, cr)
130     cr.close()
131     buf.close()
132
133     logger.info('translation file written successfully')
134     sys.exit(0)
135
136 if config["translate_in"]:
137     context = {'overwrite': config["overwrite_existing_translations"]}
138     dbname = config['db_name']
139     cr = openerp.pooler.get_db(dbname).cursor()
140     openerp.tools.trans_load(cr,
141                      config["translate_in"], 
142                      config["language"],
143                      context=context)
144     openerp.tools.trans_update_res_ids(cr)
145     cr.commit()
146     cr.close()
147     sys.exit(0)
148
149 #----------------------------------------------------------------------------------
150 # if we don't want the server to continue to run after initialization, we quit here
151 #----------------------------------------------------------------------------------
152 if config["stop_after_init"]:
153     sys.exit(0)
154
155 openerp.netsvc.start_agent()
156
157 #----------------------------------------------------------
158 # Launch Servers
159 #----------------------------------------------------------
160
161 LST_SIGNALS = ['SIGINT', 'SIGTERM']
162
163 SIGNALS = dict(
164     [(getattr(signal, sign), sign) for sign in LST_SIGNALS]
165 )
166
167 quit_signals_received = 0
168
169 def handler(signum, frame):
170     """
171     :param signum: the signal number
172     :param frame: the interrupted stack frame or None
173     """
174     global quit_signals_received
175     quit_signals_received += 1
176     if quit_signals_received > 1:
177         sys.stderr.write("Forced shutdown.\n")
178         os._exit(0)
179
180 def dumpstacks(signum, frame):
181     # code from http://stackoverflow.com/questions/132058/getting-stack-trace-from-a-running-python-application#answer-2569696
182     # modified for python 2.5 compatibility
183     thread_map = dict(threading._active, **threading._limbo)
184     id2name = dict([(threadId, thread.getName()) for threadId, thread in thread_map.items()])
185     code = []
186     for threadId, stack in sys._current_frames().items():
187         code.append("\n# Thread: %s(%d)" % (id2name[threadId], threadId))
188         for filename, lineno, name, line in traceback.extract_stack(stack):
189             code.append('File: "%s", line %d, in %s' % (filename, lineno, name))
190             if line:
191                 code.append("  %s" % (line.strip()))
192     logging.getLogger('dumpstacks').info("\n".join(code))
193
194 for signum in SIGNALS:
195     signal.signal(signum, handler)
196
197 if os.name == 'posix':
198     signal.signal(signal.SIGQUIT, dumpstacks)
199
200 def quit():
201     openerp.netsvc.Agent.quit()
202     openerp.netsvc.Server.quitAll()
203     if config['pidfile']:
204         os.unlink(config['pidfile'])
205     logger = logging.getLogger('shutdown')
206     logger.info("Initiating OpenERP Server shutdown")
207     logger.info("Hit CTRL-C again or send a second signal to immediately terminate the server...")
208     logging.shutdown()
209
210     # manually join() all threads before calling sys.exit() to allow a second signal
211     # to trigger _force_quit() in case some non-daemon threads won't exit cleanly.
212     # threading.Thread.join() should not mask signals (at least in python 2.5)
213     for thread in threading.enumerate():
214         if thread != threading.currentThread() and not thread.isDaemon():
215             while thread.isAlive():
216                 # need a busyloop here as thread.join() masks signals
217                 # and would present the forced shutdown
218                 thread.join(0.05)
219                 time.sleep(0.05)
220     sys.exit(0)
221
222 if config['pidfile']:
223     fd = open(config['pidfile'], 'w')
224     pidtext = "%d" % (os.getpid())
225     fd.write(pidtext)
226     fd.close()
227
228 openerp.netsvc.Server.startAll()
229
230 logger.info('OpenERP server is running, waiting for connections...')
231
232 while quit_signals_received == 0:
233     time.sleep(60)
234
235 quit()
236
237 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: