[FIX] use unique localstorage path when running phantomjs tests
[odoo/odoo.git] / openerp / cli / server.py
1 # -*- coding: utf-8 -*-
2 ##############################################################################
3 #
4 #    OpenERP, Open Source Management Solution
5 #    Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>).
6 #
7 #    This program is free software: you can redistribute it and/or modify
8 #    it under the terms of the GNU Affero General Public License as
9 #    published by the Free Software Foundation, either version 3 of the
10 #    License, or (at your option) any later version.
11 #
12 #    This program is distributed in the hope that it will be useful,
13 #    but WITHOUT ANY WARRANTY; without even the implied warranty of
14 #    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 #    GNU Affero General Public License for more details.
16 #
17 #    You should have received a copy of the GNU Affero General Public License
18 #    along with this program.  If not, see <http://www.gnu.org/licenses/>.
19 #
20 ##############################################################################
21
22 """
23 OpenERP - Server
24 OpenERP is an ERP+CRM program for small and medium businesses.
25
26 The whole source code is distributed under the terms of the
27 GNU Public Licence.
28
29 (c) 2003-TODAY, Fabien Pinckaers - OpenERP SA
30 """
31
32 import atexit
33 import logging
34 import os
35 import signal
36 import sys
37 import threading
38 import traceback
39 import time
40
41 import openerp
42
43 from . import Command
44
45 __author__ = openerp.release.author
46 __version__ = openerp.release.version
47
48 # Also use the `openerp` logger for the main script.
49 _logger = logging.getLogger('openerp')
50
51 def check_root_user():
52     """ Exit if the process's user is 'root' (on POSIX system)."""
53     if os.name == 'posix':
54         import pwd
55         if pwd.getpwuid(os.getuid())[0] == 'root' :
56             sys.stderr.write("Running as user 'root' is a security risk, aborting.\n")
57             sys.exit(1)
58
59 def check_postgres_user():
60     """ Exit if the configured database user is 'postgres'.
61
62     This function assumes the configuration has been initialized.
63     """
64     config = openerp.tools.config
65     if config['db_user'] == 'postgres':
66         sys.stderr.write("Using the database user 'postgres' is a security risk, aborting.")
67         sys.exit(1)
68
69 def report_configuration():
70     """ Log the server version and some configuration values.
71
72     This function assumes the configuration has been initialized.
73     """
74     config = openerp.tools.config
75     _logger.info("OpenERP version %s", __version__)
76     for name, value in [('addons paths', openerp.modules.module.ad_paths),
77                         ('database hostname', config['db_host'] or 'localhost'),
78                         ('database port', config['db_port'] or '5432'),
79                         ('database user', config['db_user'])]:
80         _logger.info("%s: %s", name, value)
81
82 def rm_pid_file():
83     config = openerp.tools.config
84     if not openerp.evented and config['pidfile']:
85         try:
86             os.unlink(config['pidfile'])
87         except OSError:
88             pass
89
90 def setup_pid_file():
91     """ Create a file with the process id written in it.
92
93     This function assumes the configuration has been initialized.
94     """
95     config = openerp.tools.config
96     if not openerp.evented and config['pidfile']:
97         with open(config['pidfile'], 'w') as fd:
98             pidtext = "%d" % (os.getpid())
99             fd.write(pidtext)
100         atexit.register(rm_pid_file)
101
102
103 def export_translation():
104     config = openerp.tools.config
105     dbname = config['db_name']
106
107     if config["language"]:
108         msg = "language %s" % (config["language"],)
109     else:
110         msg = "new language"
111     _logger.info('writing translation file for %s to %s', msg,
112         config["translate_out"])
113
114     fileformat = os.path.splitext(config["translate_out"])[-1][1:].lower()
115     buf = file(config["translate_out"], "w")
116     registry = openerp.modules.registry.RegistryManager.new(dbname)
117     cr = registry.cursor()
118     openerp.tools.trans_export(config["language"],
119         config["translate_modules"] or ["all"], buf, fileformat, cr)
120     cr.close()
121     buf.close()
122
123     _logger.info('translation file written successfully')
124
125 def import_translation():
126     config = openerp.tools.config
127     context = {'overwrite': config["overwrite_existing_translations"]}
128     dbname = config['db_name']
129
130     registry = openerp.modules.registry.RegistryManager.new(dbname)
131     cr = registry.cursor()
132     openerp.tools.trans_load( cr, config["translate_in"], config["language"],
133         context=context)
134     cr.commit()
135     cr.close()
136
137 def main(args):
138     check_root_user()
139     openerp.tools.config.parse_config(args)
140     check_postgres_user()
141     report_configuration()
142
143     config = openerp.tools.config
144
145     if config["test_file"]:
146         config["test_enable"] = True
147
148     if config["translate_out"]:
149         export_translation()
150         sys.exit(0)
151
152     if config["translate_in"]:
153         import_translation()
154         sys.exit(0)
155
156     # This needs to be done now to ensure the use of the multiprocessing
157     # signaling mecanism for registries loaded with -d
158     if config['workers']:
159         openerp.multi_process = True
160
161     preload = []
162     if config['db_name']:
163         preload = config['db_name'].split(',')
164
165     stop = config["stop_after_init"]
166
167     setup_pid_file()
168     rc = openerp.service.server.start(preload=preload, stop=stop)
169     sys.exit(rc)
170
171 class Server(Command):
172     def run(self, args):
173         main(args)
174
175 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: