~ubuntu-branches/ubuntu/quantal/openerp6.1/quantal-proposed

« back to all changes in this revision

Viewing changes to .pc/02-fix-localedata.patch/openerp-server

  • Committer: Package Import Robot
  • Author(s): Yolanda Robla
  • Date: 2012-09-20 15:29:00 UTC
  • Revision ID: package-import@ubuntu.com-20120920152900-ph979bapm63fqn9l
Tags: 6.1-1+dfsg-0ubuntu1
Initial OpenERP package. Repackaged to remove non-distributable files

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
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 SA
 
31
"""
 
32
 
 
33
import imp
 
34
import logging
 
35
import os
 
36
import signal
 
37
import sys
 
38
import threading
 
39
import traceback
 
40
import time
 
41
 
 
42
sys.path.insert(6, '/usr/share')
 
43
import openerp
 
44
__author__ = openerp.release.author
 
45
__version__ = openerp.release.version
 
46
 
 
47
# Also use the `openerp` logger for the main script.
 
48
_logger = logging.getLogger('openerp')
 
49
 
 
50
def check_root_user():
 
51
    """ Exit if the process's user is 'root' (on POSIX system)."""
 
52
    if os.name == 'posix':
 
53
        import pwd
 
54
        if pwd.getpwuid(os.getuid())[0] == 'root' :
 
55
            sys.stderr.write("Running as user 'root' is a security risk, aborting.\n")
 
56
            sys.exit(1)
 
57
 
 
58
def check_postgres_user():
 
59
    """ Exit if the configured database user is 'postgres'.
 
60
 
 
61
    This function assumes the configuration has been initialized.
 
62
    """
 
63
    config = openerp.tools.config
 
64
    if config['db_user'] == 'postgres':
 
65
        sys.stderr.write("Using the database user 'postgres' is a security risk, aborting.")
 
66
        sys.exit(1)
 
67
 
 
68
def report_configuration():
 
69
    """ Log the server version and some configuration values.
 
70
 
 
71
    This function assumes the configuration has been initialized.
 
72
    """
 
73
    config = openerp.tools.config
 
74
    _logger.info("OpenERP version %s", __version__)
 
75
    for name, value in [('addons paths', config['addons_path']),
 
76
                        ('database hostname', config['db_host'] or 'localhost'),
 
77
                        ('database port', config['db_port'] or '5432'),
 
78
                        ('database user', config['db_user'])]:
 
79
        _logger.info("%s: %s", name, value)
 
80
 
 
81
def setup_pid_file():
 
82
    """ Create a file with the process id written in it.
 
83
 
 
84
    This function assumes the configuration has been initialized.
 
85
    """
 
86
    config = openerp.tools.config
 
87
    if config['pidfile']:
 
88
        fd = open(config['pidfile'], 'w')
 
89
        pidtext = "%d" % (os.getpid())
 
90
        fd.write(pidtext)
 
91
        fd.close()
 
92
 
 
93
def preload_registry(dbname):
 
94
    """ Preload a registry, and start the cron."""
 
95
    try:
 
96
        db, registry = openerp.pooler.get_db_and_pool(dbname, update_module=config['init'] or config['update'], pooljobs=False)
 
97
 
 
98
        # jobs will start to be processed later, when openerp.cron.start_master_thread() is called by openerp.service.start_services()
 
99
        registry.schedule_cron_jobs()
 
100
    except Exception:
 
101
        _logger.exception('Failed to initialize database `%s`.', dbname)
 
102
 
 
103
def run_test_file(dbname, test_file):
 
104
    """ Preload a registry, possibly run a test file, and start the cron."""
 
105
    try:
 
106
        db, registry = openerp.pooler.get_db_and_pool(dbname, update_module=config['init'] or config['update'], pooljobs=False)
 
107
        cr = db.cursor()
 
108
        _logger.info('loading test file %s', test_file)
 
109
        openerp.tools.convert_yaml_import(cr, 'base', file(test_file), {}, 'test', True)
 
110
        cr.rollback()
 
111
        cr.close()
 
112
    except Exception:
 
113
        _logger.exception('Failed to initialize database `%s` and run test file `%s`.', dbname, test_file)
 
114
 
 
115
 
 
116
def export_translation():
 
117
    config = openerp.tools.config
 
118
    dbname = config['db_name']
 
119
 
 
120
    if config["language"]:
 
121
        msg = "language %s" % (config["language"],)
 
122
    else:
 
123
        msg = "new language"
 
124
    _logger.info('writing translation file for %s to %s', msg,
 
125
        config["translate_out"])
 
126
 
 
127
    fileformat = os.path.splitext(config["translate_out"])[-1][1:].lower()
 
128
    buf = file(config["translate_out"], "w")
 
129
    cr = openerp.pooler.get_db(dbname).cursor()
 
130
    openerp.tools.trans_export(config["language"],
 
131
        config["translate_modules"] or ["all"], buf, fileformat, cr)
 
132
    cr.close()
 
133
    buf.close()
 
134
 
 
135
    _logger.info('translation file written successfully')
 
136
 
 
137
def import_translation():
 
138
    config = openerp.tools.config
 
139
    context = {'overwrite': config["overwrite_existing_translations"]}
 
140
    dbname = config['db_name']
 
141
 
 
142
    cr = openerp.pooler.get_db(dbname).cursor()
 
143
    openerp.tools.trans_load( cr, config["translate_in"], config["language"],
 
144
        context=context)
 
145
    cr.commit()
 
146
    cr.close()
 
147
 
 
148
# Variable keeping track of the number of calls to the signal handler defined
 
149
# below. This variable is monitored by ``quit_on_signals()``.
 
150
quit_signals_received = 0
 
151
 
 
152
def signal_handler(sig, frame):
 
153
    """ Signal handler: exit ungracefully on the second handled signal.
 
154
 
 
155
    :param sig: the signal number
 
156
    :param frame: the interrupted stack frame or None
 
157
    """
 
158
    global quit_signals_received
 
159
    quit_signals_received += 1
 
160
    if quit_signals_received > 1:
 
161
        # logging.shutdown was already called at this point.
 
162
        sys.stderr.write("Forced shutdown.\n")
 
163
        os._exit(0)
 
164
 
 
165
def dumpstacks(sig, frame):
 
166
    """ Signal handler: dump a stack trace for each existing thread."""
 
167
    # code from http://stackoverflow.com/questions/132058/getting-stack-trace-from-a-running-python-application#answer-2569696
 
168
    # modified for python 2.5 compatibility
 
169
    thread_map = dict(threading._active, **threading._limbo)
 
170
    id2name = dict([(threadId, thread.getName()) for threadId, thread in thread_map.items()])
 
171
    code = []
 
172
    for threadId, stack in sys._current_frames().items():
 
173
        code.append("\n# Thread: %s(%d)" % (id2name[threadId], threadId))
 
174
        for filename, lineno, name, line in traceback.extract_stack(stack):
 
175
            code.append('File: "%s", line %d, in %s' % (filename, lineno, name))
 
176
            if line:
 
177
                code.append("  %s" % (line.strip()))
 
178
    _logger.info("\n".join(code))
 
179
 
 
180
def setup_signal_handlers():
 
181
    """ Register the signal handler defined above. """
 
182
    SIGNALS = map(lambda x: getattr(signal, "SIG%s" % x), "INT TERM".split())
 
183
    if os.name == 'posix':
 
184
        map(lambda sig: signal.signal(sig, signal_handler), SIGNALS)
 
185
        signal.signal(signal.SIGQUIT, dumpstacks)
 
186
    elif os.name == 'nt':
 
187
        import win32api
 
188
        win32api.SetConsoleCtrlHandler(lambda sig: signal_handler(sig, None), 1)
 
189
 
 
190
def quit_on_signals():
 
191
    """ Wait for one or two signals then shutdown the server.
 
192
 
 
193
    The first SIGINT or SIGTERM signal will initiate a graceful shutdown while
 
194
    a second one if any will force an immediate exit.
 
195
 
 
196
    """
 
197
    # Wait for a first signal to be handled. (time.sleep will be interrupted
 
198
    # by the signal handler.) The try/except is for the win32 case.
 
199
    try:
 
200
        while quit_signals_received == 0:
 
201
            time.sleep(60)
 
202
    except KeyboardInterrupt, e:
 
203
        pass
 
204
 
 
205
    if config['pidfile']:
 
206
        os.unlink(config['pidfile'])
 
207
 
 
208
    openerp.service.stop_services()
 
209
    sys.exit(0)
 
210
 
 
211
def configure_babel_localedata_path():
 
212
    # Workaround: py2exe and babel.
 
213
    if hasattr(sys, 'frozen'):
 
214
        import babel
 
215
        babel.localedata._dirname = os.path.join(os.path.dirname(sys.executable), 'localedata')
 
216
 
 
217
if __name__ == "__main__":
 
218
 
 
219
    os.environ["TZ"] = "UTC"
 
220
 
 
221
    check_root_user()
 
222
    openerp.tools.config.parse_config(sys.argv[1:])
 
223
 
 
224
    check_postgres_user()
 
225
    openerp.netsvc.init_logger()
 
226
    report_configuration()
 
227
 
 
228
    config = openerp.tools.config
 
229
 
 
230
    configure_babel_localedata_path()
 
231
 
 
232
    setup_signal_handlers()
 
233
 
 
234
    if config["test_file"]:
 
235
        run_test_file(config['db_name'], config['test_file'])
 
236
        sys.exit(0)
 
237
 
 
238
    if config["translate_out"]:
 
239
        export_translation()
 
240
        sys.exit(0)
 
241
 
 
242
    if config["translate_in"]:
 
243
        import_translation()
 
244
        sys.exit(0)
 
245
 
 
246
    if not config["stop_after_init"]:
 
247
        # Some module register themselves when they are loaded so we need the
 
248
        # services to be running before loading any registry.
 
249
        openerp.service.start_services()
 
250
 
 
251
    for m in openerp.conf.server_wide_modules:
 
252
        try:
 
253
            openerp.modules.module.load_openerp_module(m)
 
254
        except Exception:
 
255
            msg = ''
 
256
            if m == 'web':
 
257
                msg = """
 
258
The `web` module is provided by the addons found in the `openerp-web` project.
 
259
Maybe you forgot to add those addons in your addons_path configuration."""
 
260
            _logger.exception('Failed to load server-wide module `%s`.%s', m, msg)
 
261
 
 
262
    if config['db_name']:
 
263
        for dbname in config['db_name'].split(','):
 
264
            preload_registry(dbname)
 
265
 
 
266
    if config["stop_after_init"]:
 
267
        sys.exit(0)
 
268
 
 
269
    setup_pid_file()
 
270
    _logger.info('OpenERP server is running, waiting for connections...')
 
271
    quit_on_signals()
 
272
 
 
273
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: