a808511ab8a86b860c098839381fcabf9f5a6c8b
[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 logging
33 import os
34 import signal
35 import sys
36 import threading
37 import traceback
38 import time
39
40 import openerp
41
42 from . import Command
43
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', openerp.modules.module.ad_paths),
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         with open(config['pidfile'], 'w') as fd:
89             pidtext = "%d" % (os.getpid())
90             fd.write(pidtext)
91
92 def export_translation():
93     config = openerp.tools.config
94     dbname = config['db_name']
95
96     if config["language"]:
97         msg = "language %s" % (config["language"],)
98     else:
99         msg = "new language"
100     _logger.info('writing translation file for %s to %s', msg,
101         config["translate_out"])
102
103     fileformat = os.path.splitext(config["translate_out"])[-1][1:].lower()
104     buf = file(config["translate_out"], "w")
105     registry = openerp.modules.registry.RegistryManager.new(dbname)
106     cr = registry.get_cursor()
107     openerp.tools.trans_export(config["language"],
108         config["translate_modules"] or ["all"], buf, fileformat, cr)
109     cr.close()
110     buf.close()
111
112     _logger.info('translation file written successfully')
113
114 def import_translation():
115     config = openerp.tools.config
116     context = {'overwrite': config["overwrite_existing_translations"]}
117     dbname = config['db_name']
118
119     registry = openerp.modules.registry.RegistryManager.new(dbname)
120     cr = registry.get_cursor()
121     openerp.tools.trans_load( cr, config["translate_in"], config["language"],
122         context=context)
123     cr.commit()
124     cr.close()
125
126 def main(args):
127     check_root_user()
128     openerp.tools.config.parse_config(args)
129     check_postgres_user()
130     report_configuration()
131
132     config = openerp.tools.config
133
134     if config["test_file"]:
135         config["test_enable"] = True
136
137     if config["translate_out"]:
138         export_translation()
139         sys.exit(0)
140
141     if config["translate_in"]:
142         import_translation()
143         sys.exit(0)
144
145     # This needs to be done now to ensure the use of the multiprocessing
146     # signaling mecanism for registries loaded with -d
147     if config['workers']:
148         openerp.multi_process = True
149
150     preload = []
151     if config['db_name']:
152         preload = config['db_name'].split(',')
153
154     stop = config["stop_after_init"]
155
156     setup_pid_file()
157     rc = openerp.service.server.start(preload=preload, stop=stop)
158     if config['pidfile']:
159         os.unlink(config['pidfile'])
160     sys.exit(rc)
161
162 class Server(Command):
163     def run(self, args):
164         main(args)
165
166 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: