2 # -*- coding: utf-8 -*-
3 ##############################################################################
5 # OpenERP, Open Source Management Solution
6 # Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>).
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.
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.
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/>.
21 ##############################################################################
25 OpenERP is an ERP+CRM program for small and medium businesses.
27 The whole source code is distributed under the terms of the
30 (c) 2003-TODAY, Fabien Pinckaers - OpenERP s.a.
33 #----------------------------------------------------------
35 #----------------------------------------------------------
44 __author__ = release.author
45 __version__ = release.version
47 if os.name == 'posix':
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")
55 #----------------------------------------------------------
57 #----------------------------------------------------------
59 logger = logging.getLogger('server')
61 #-----------------------------------------------------------------------
62 # import the tools module so that the commandline parameters are parsed
63 #-----------------------------------------------------------------------
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)
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.")
79 #----------------------------------------------------------
81 #----------------------------------------------------------
82 logger.info('initialising distributed objects services')
84 #---------------------------------------------------------------
85 # connect to the database and initialize it with base if needed
86 #---------------------------------------------------------------
89 #----------------------------------------------------------
90 # import basic modules
91 #----------------------------------------------------------
97 #----------------------------------------------------------
99 #----------------------------------------------------------
103 #----------------------------------------------------------
104 # Load and update databases if requested
105 #----------------------------------------------------------
107 import service.http_server
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()
116 import service.netrpc_server
117 service.netrpc_server.init_servers()
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)
124 if tools.config["test_file"]:
125 logger.info('loading test file %s', tools.config["test_file"])
126 tools.convert_yaml_import(cr, 'base', file(tools.config["test_file"]), {}, 'test', True)
129 pool.get('ir.cron')._poolJobs(db.dbname)
133 #----------------------------------------------------------
135 #----------------------------------------------------------
136 if tools.config["translate_out"]:
139 if tools.config["language"]:
140 msg = "language %s" % (tools.config["language"],)
143 logger.info('writing translation file for %s to %s', msg, tools.config["translate_out"])
145 fileformat = os.path.splitext(tools.config["translate_out"])[-1][1:].lower()
146 buf = file(tools.config["translate_out"], "w")
147 dbname = tools.config['db_name']
148 cr = pooler.get_db(dbname).cursor()
149 tools.trans_export(tools.config["language"], tools.config["translate_modules"] or ["all"], buf, fileformat, cr)
153 logger.info('translation file written successfully')
156 if tools.config["translate_in"]:
157 context = {'overwrite': tools.config["overwrite_existing_translations"]}
158 dbname = tools.config['db_name']
159 cr = pooler.get_db(dbname).cursor()
161 tools.config["translate_in"],
162 tools.config["language"],
164 tools.trans_update_res_ids(cr)
169 #----------------------------------------------------------------------------------
170 # if we don't want the server to continue to run after initialization, we quit here
171 #----------------------------------------------------------------------------------
172 if tools.config["stop_after_init"]:
176 #----------------------------------------------------------
178 #----------------------------------------------------------
180 LST_SIGNALS = ['SIGINT', 'SIGTERM']
183 [(getattr(signal, sign), sign) for sign in LST_SIGNALS]
186 netsvc.quit_signals_received = 0
188 def handler(signum, frame):
190 :param signum: the signal number
191 :param frame: the interrupted stack frame or None
193 netsvc.quit_signals_received += 1
194 if netsvc.quit_signals_received > 1:
195 sys.stderr.write("Forced shutdown.\n")
198 def dumpstacks(signum, frame):
199 # code from http://stackoverflow.com/questions/132058/getting-stack-trace-from-a-running-python-application#answer-2569696
200 # modified for python 2.5 compatibility
201 thread_map = dict(threading._active, **threading._limbo)
202 id2name = dict([(threadId, thread.getName()) for threadId, thread in thread_map.items()])
204 for threadId, stack in sys._current_frames().items():
205 code.append("\n# Thread: %s(%d)" % (id2name[threadId], threadId))
206 for filename, lineno, name, line in traceback.extract_stack(stack):
207 code.append('File: "%s", line %d, in %s' % (filename, lineno, name))
209 code.append(" %s" % (line.strip()))
210 logging.getLogger('dumpstacks').info("\n".join(code))
212 for signum in SIGNALS:
213 signal.signal(signum, handler)
215 if os.name == 'posix':
216 signal.signal(signal.SIGQUIT, dumpstacks)
220 netsvc.Server.quitAll()
221 if tools.config['pidfile']:
222 os.unlink(tools.config['pidfile'])
223 logger = logging.getLogger('shutdown')
224 logger.info("Initiating OpenERP Server shutdown")
225 logger.info("Hit CTRL-C again or send a second signal to immediately terminate the server...")
228 # manually join() all threads before calling sys.exit() to allow a second signal
229 # to trigger _force_quit() in case some non-daemon threads won't exit cleanly.
230 # threading.Thread.join() should not mask signals (at least in python 2.5)
231 for thread in threading.enumerate():
232 if thread != threading.currentThread() and not thread.isDaemon():
233 while thread.isAlive():
234 # need a busyloop here as thread.join() masks signals
235 # and would present the forced shutdown
240 if tools.config['pidfile']:
241 fd = open(tools.config['pidfile'], 'w')
242 pidtext = "%d" % (os.getpid())
246 netsvc.Server.startAll()
248 logger.info('OpenERP server is running, waiting for connections...')
250 while netsvc.quit_signals_received == 0:
255 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: