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 #----------------------------------------------------------
45 __author__ = openerp.release.author
46 __version__ = openerp.release.version
48 if os.name == 'posix':
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")
56 #-----------------------------------------------------------------------
57 # parse the command line
58 #-----------------------------------------------------------------------
59 openerp.tools.config.parse_config(sys.argv[1:])
60 config = openerp.tools.config
62 #----------------------------------------------------------
64 #----------------------------------------------------------
65 openerp.netsvc.init_logger()
66 logger = logging.getLogger('server')
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)
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.")
80 #----------------------------------------------------------
82 #----------------------------------------------------------
83 logger.info('initialising distributed objects services')
85 #----------------------------------------------------------
86 # Load and update databases if requested
87 #----------------------------------------------------------
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()
101 if config['db_name']:
102 for dbname in config['db_name'].split(','):
103 db, registry = openerp.pooler.get_db_and_pool(dbname, update_module=config['init'] or config['update'], pooljobs=False)
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)
111 # jobs will start to be processed later, when openerp.cron.start_master_thread below is called.
112 registry.schedule_cron_jobs()
116 #----------------------------------------------------------
118 #----------------------------------------------------------
119 if config["translate_out"]:
120 if config["language"]:
121 msg = "language %s" % (config["language"],)
124 logger.info('writing translation file for %s to %s', msg, config["translate_out"])
126 fileformat = os.path.splitext(config["translate_out"])[-1][1:].lower()
127 buf = file(config["translate_out"], "w")
128 dbname = config['db_name']
129 cr = openerp.pooler.get_db(dbname).cursor()
130 openerp.tools.trans_export(config["language"], config["translate_modules"] or ["all"], buf, fileformat, cr)
134 logger.info('translation file written successfully')
137 if config["translate_in"]:
138 context = {'overwrite': config["overwrite_existing_translations"]}
139 dbname = config['db_name']
140 cr = openerp.pooler.get_db(dbname).cursor()
141 openerp.tools.trans_load(cr,
142 config["translate_in"],
145 openerp.tools.trans_update_res_ids(cr)
150 #----------------------------------------------------------------------------------
151 # if we don't want the server to continue to run after initialization, we quit here
152 #----------------------------------------------------------------------------------
153 if config["stop_after_init"]:
156 openerp.cron.start_master_thread()
158 #----------------------------------------------------------
160 #----------------------------------------------------------
162 LST_SIGNALS = ['SIGINT', 'SIGTERM']
165 [(getattr(signal, sign), sign) for sign in LST_SIGNALS]
168 quit_signals_received = 0
170 def handler(signum, frame):
172 :param signum: the signal number
173 :param frame: the interrupted stack frame or None
175 global quit_signals_received
176 quit_signals_received += 1
177 if quit_signals_received > 1:
178 sys.stderr.write("Forced shutdown.\n")
181 def dumpstacks(signum, frame):
182 # code from http://stackoverflow.com/questions/132058/getting-stack-trace-from-a-running-python-application#answer-2569696
183 # modified for python 2.5 compatibility
184 thread_map = dict(threading._active, **threading._limbo)
185 id2name = dict([(threadId, thread.getName()) for threadId, thread in thread_map.items()])
187 for threadId, stack in sys._current_frames().items():
188 code.append("\n# Thread: %s(%d)" % (id2name[threadId], threadId))
189 for filename, lineno, name, line in traceback.extract_stack(stack):
190 code.append('File: "%s", line %d, in %s' % (filename, lineno, name))
192 code.append(" %s" % (line.strip()))
193 logging.getLogger('dumpstacks').info("\n".join(code))
195 for signum in SIGNALS:
196 signal.signal(signum, handler)
198 if os.name == 'posix':
199 signal.signal(signal.SIGQUIT, dumpstacks)
202 # stop scheduling new jobs; we will have to wait for the jobs to complete below
203 openerp.cron.cancel_all()
204 openerp.netsvc.Server.quitAll()
205 if config['pidfile']:
206 os.unlink(config['pidfile'])
207 logger = logging.getLogger('shutdown')
208 logger.info("Initiating OpenERP Server shutdown")
209 logger.info("Hit CTRL-C again or send a second signal to immediately terminate the server...")
212 # manually join() all threads before calling sys.exit() to allow a second signal
213 # to trigger _force_quit() in case some non-daemon threads won't exit cleanly.
214 # threading.Thread.join() should not mask signals (at least in python 2.5)
215 for thread in threading.enumerate():
216 if thread != threading.currentThread() and not thread.isDaemon():
217 while thread.isAlive():
218 # need a busyloop here as thread.join() masks signals
219 # and would prevent the forced shutdown
222 openerp.modules.registry.RegistryManager.delete_all()
225 if config['pidfile']:
226 fd = open(config['pidfile'], 'w')
227 pidtext = "%d" % (os.getpid())
231 openerp.netsvc.Server.startAll()
233 logger.info('OpenERP server is running, waiting for connections...')
235 while quit_signals_received == 0:
240 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: