[IMP] in Accounting > Journal Entries > Journal Items, do not filter on Posted by...
[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
43 import openerp.release as 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 # import the tools module so that the commandline parameters are parsed
57 #-----------------------------------------------------------------------
58 import openerp.tools as tools
59 tools.config.parse_config(sys.argv[1:])
60
61 #----------------------------------------------------------
62 # get logger
63 #----------------------------------------------------------
64 import openerp.netsvc as netsvc
65 netsvc.init_logger()
66 logger = logging.getLogger('server')
67
68 logger.info("OpenERP version - %s", release.version)
69 for name, value in [('addons_path', tools.config['addons_path']),
70                     ('database hostname', tools.config['db_host'] or 'localhost'),
71                     ('database port', tools.config['db_port'] or '5432'),
72                     ('database user', tools.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 tools.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 import time
81
82 #----------------------------------------------------------
83 # init net service
84 #----------------------------------------------------------
85 logger.info('initialising distributed objects services')
86
87 #---------------------------------------------------------------
88 # connect to the database and initialize it with base if needed
89 #---------------------------------------------------------------
90 import openerp.pooler as pooler
91
92 #----------------------------------------------------------
93 # import basic modules
94 #----------------------------------------------------------
95 import openerp.osv as osv
96 import openerp.workflow as workflow
97 import openerp.report as report
98 import openerp.service as service
99
100 #----------------------------------------------------------
101 # import addons
102 #----------------------------------------------------------
103
104 import openerp.addons as addons
105
106 #----------------------------------------------------------
107 # Load and update databases if requested
108 #----------------------------------------------------------
109
110 import openerp.service.http_server as service_http_server
111
112 if not ( tools.config["stop_after_init"] or \
113     tools.config["translate_in"] or \
114     tools.config["translate_out"] ):
115     service_http_server.init_servers()
116     service_http_server.init_xmlrpc()
117     service_http_server.init_static_http()
118
119     import openerp.service.netrpc_server as service_netrpc_server
120     service_netrpc_server.init_servers()
121
122 if tools.config['db_name']:
123     for dbname in tools.config['db_name'].split(','):
124         db,pool = pooler.get_db_and_pool(dbname, update_module=tools.config['init'] or tools.config['update'], pooljobs=False)
125         cr = db.cursor()
126
127         if tools.config["test_file"]:
128             logger.info('loading test file %s', tools.config["test_file"])
129             tools.convert_yaml_import(cr, 'base', file(tools.config["test_file"]), {}, 'test', True)
130             cr.rollback()
131
132         pool.get('ir.cron')._poolJobs(db.dbname)
133
134         cr.close()
135
136 #----------------------------------------------------------
137 # translation stuff
138 #----------------------------------------------------------
139 if tools.config["translate_out"]:
140     import csv
141
142     if tools.config["language"]:
143         msg = "language %s" % (tools.config["language"],)
144     else:
145         msg = "new language"
146     logger.info('writing translation file for %s to %s', msg, tools.config["translate_out"])
147
148     fileformat = os.path.splitext(tools.config["translate_out"])[-1][1:].lower()
149     buf = file(tools.config["translate_out"], "w")
150     dbname = tools.config['db_name']
151     cr = pooler.get_db(dbname).cursor()
152     tools.trans_export(tools.config["language"], tools.config["translate_modules"] or ["all"], buf, fileformat, cr)
153     cr.close()
154     buf.close()
155
156     logger.info('translation file written successfully')
157     sys.exit(0)
158
159 if tools.config["translate_in"]:
160     context = {'overwrite': tools.config["overwrite_existing_translations"]}
161     dbname = tools.config['db_name']
162     cr = pooler.get_db(dbname).cursor()
163     tools.trans_load(cr,
164                      tools.config["translate_in"], 
165                      tools.config["language"],
166                      context=context)
167     tools.trans_update_res_ids(cr)
168     cr.commit()
169     cr.close()
170     sys.exit(0)
171
172 #----------------------------------------------------------------------------------
173 # if we don't want the server to continue to run after initialization, we quit here
174 #----------------------------------------------------------------------------------
175 if tools.config["stop_after_init"]:
176     sys.exit(0)
177
178
179 #----------------------------------------------------------
180 # Launch Servers
181 #----------------------------------------------------------
182
183 LST_SIGNALS = ['SIGINT', 'SIGTERM']
184
185 SIGNALS = dict(
186     [(getattr(signal, sign), sign) for sign in LST_SIGNALS]
187 )
188
189 netsvc.quit_signals_received = 0
190
191 def handler(signum, frame):
192     """
193     :param signum: the signal number
194     :param frame: the interrupted stack frame or None
195     """
196     netsvc.quit_signals_received += 1
197     if netsvc.quit_signals_received > 1:
198         sys.stderr.write("Forced shutdown.\n")
199         os._exit(0)
200
201 def dumpstacks(signum, frame):
202     # code from http://stackoverflow.com/questions/132058/getting-stack-trace-from-a-running-python-application#answer-2569696
203     # modified for python 2.5 compatibility
204     thread_map = dict(threading._active, **threading._limbo)
205     id2name = dict([(threadId, thread.getName()) for threadId, thread in thread_map.items()])
206     code = []
207     for threadId, stack in sys._current_frames().items():
208         code.append("\n# Thread: %s(%d)" % (id2name[threadId], threadId))
209         for filename, lineno, name, line in traceback.extract_stack(stack):
210             code.append('File: "%s", line %d, in %s' % (filename, lineno, name))
211             if line:
212                 code.append("  %s" % (line.strip()))
213     logging.getLogger('dumpstacks').info("\n".join(code))
214
215 for signum in SIGNALS:
216     signal.signal(signum, handler)
217
218 if os.name == 'posix':
219     signal.signal(signal.SIGQUIT, dumpstacks)
220
221 def quit():
222     netsvc.Agent.quit()
223     netsvc.Server.quitAll()
224     if tools.config['pidfile']:
225         os.unlink(tools.config['pidfile'])
226     logger = logging.getLogger('shutdown')
227     logger.info("Initiating OpenERP Server shutdown")
228     logger.info("Hit CTRL-C again or send a second signal to immediately terminate the server...")
229     logging.shutdown()
230
231     # manually join() all threads before calling sys.exit() to allow a second signal
232     # to trigger _force_quit() in case some non-daemon threads won't exit cleanly.
233     # threading.Thread.join() should not mask signals (at least in python 2.5)
234     for thread in threading.enumerate():
235         if thread != threading.currentThread() and not thread.isDaemon():
236             while thread.isAlive():
237                 # need a busyloop here as thread.join() masks signals
238                 # and would present the forced shutdown
239                 thread.join(0.05)
240                 time.sleep(0.05)
241     sys.exit(0)
242
243 if tools.config['pidfile']:
244     fd = open(tools.config['pidfile'], 'w')
245     pidtext = "%d" % (os.getpid())
246     fd.write(pidtext)
247     fd.close()
248
249 netsvc.Server.startAll()
250
251 logger.info('OpenERP server is running, waiting for connections...')
252
253 while netsvc.quit_signals_received == 0:
254     time.sleep(60)
255
256 quit()
257
258 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: