Merge remote-tracking branch 'upstream/7.0' into 7.0-travis
[odoo/odoo.git] / openerp / service / __init__.py
1 # -*- coding: utf-8 -*-
2 ##############################################################################
3 #
4 #    OpenERP, Open Source Management Solution
5 #    Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>).
6 #    Copyright (C) 2010-2013 OpenERP SA (<http://www.openerp.com>)
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 import logging
24 import os
25 import signal
26 import subprocess
27 import sys
28 import threading
29 import time
30
31 import cron
32 import netrpc_server
33 import web_services
34 import web_services
35 import wsgi_server
36
37 import openerp.modules
38 import openerp.netsvc
39 import openerp.osv
40 from openerp.release import nt_service_name
41 import openerp.tools
42 from openerp.tools.misc import stripped_sys_argv
43
44 #.apidoc title: RPC Services
45
46 """ Classes of this module implement the network protocols that the
47     OpenERP server uses to communicate with remote clients.
48
49     Some classes are mostly utilities, whose API need not be visible to
50     the average user/developer. Study them only if you are about to
51     implement an extension to the network protocols, or need to debug some
52     low-level behavior of the wire.
53 """
54
55 _logger = logging.getLogger(__name__)
56
57 def load_server_wide_modules():
58     for m in openerp.conf.server_wide_modules:
59         try:
60             openerp.modules.module.load_openerp_module(m)
61         except Exception:
62             msg = ''
63             if m == 'web':
64                 msg = """
65 The `web` module is provided by the addons found in the `openerp-web` project.
66 Maybe you forgot to add those addons in your addons_path configuration."""
67             _logger.exception('Failed to load server-wide module `%s`.%s', m, msg)
68
69 start_internal_done = False
70 main_thread_id = threading.currentThread().ident
71
72 def start_internal():
73     global start_internal_done
74     if start_internal_done:
75         return
76     openerp.netsvc.init_logger()
77     openerp.modules.loading.open_openerp_namespace()
78
79     # Instantiate local services (this is a legacy design).
80     openerp.osv.osv.start_object_proxy()
81     # Export (for RPC) services.
82     web_services.start_service()
83
84     load_server_wide_modules()
85     start_internal_done = True
86
87 def start_services():
88     """ Start all services including http, netrpc and cron """
89     start_internal()
90     # Initialize the NETRPC server.
91     netrpc_server.start_service()
92     # Start the WSGI server.
93     wsgi_server.start_service()
94     # Start the main cron thread.
95     cron.start_service()
96
97 def stop_services():
98     """ Stop all services. """
99     # stop services
100     cron.stop_service()
101     netrpc_server.stop_service()
102     wsgi_server.stop_service()
103
104     _logger.info("Initiating shutdown")
105     _logger.info("Hit CTRL-C again or send a second signal to force the shutdown.")
106
107     # Manually join() all threads before calling sys.exit() to allow a second signal
108     # to trigger _force_quit() in case some non-daemon threads won't exit cleanly.
109     # threading.Thread.join() should not mask signals (at least in python 2.5).
110     me = threading.currentThread()
111     _logger.debug('current thread: %r', me)
112     for thread in threading.enumerate():
113         _logger.debug('process %r (%r)', thread, thread.isDaemon())
114         if thread != me and not thread.isDaemon() and thread.ident != main_thread_id:
115             while thread.isAlive():
116                 _logger.debug('join and sleep')
117                 # Need a busyloop here as thread.join() masks signals
118                 # and would prevent the forced shutdown.
119                 thread.join(0.05)
120                 time.sleep(0.05)
121
122     _logger.debug('--')
123     openerp.modules.registry.RegistryManager.delete_all()
124     logging.shutdown()
125
126 def start_services_workers():
127     import openerp.service.workers
128     openerp.multi_process = True
129     openerp.service.workers.Multicorn(openerp.service.wsgi_server.application).run()
130
131 def _reexec():
132     """reexecute openerp-server process with (nearly) the same arguments"""
133     if openerp.tools.osutil.is_running_as_nt_service():
134         subprocess.call('net stop {0} && net start {0}'.format(nt_service_name), shell=True)
135     exe = os.path.basename(sys.executable)
136     args = stripped_sys_argv()
137     if not args or args[0] != exe:
138         args.insert(0, exe)
139     os.execv(sys.executable, args)
140
141 def restart_server():
142     if openerp.multi_process:
143         raise NotImplementedError("Multicorn is not supported (but gunicorn was)")
144         pid = openerp.wsgi.core.arbiter_pid
145         os.kill(pid, signal.SIGHUP)
146     else:
147         if os.name == 'nt':
148             def reborn():
149                 stop_services()
150                 _reexec()
151
152             # run in a thread to let the current thread return response to the caller.
153             threading.Thread(target=reborn).start()
154         else:
155             openerp.phoenix = True
156             os.kill(os.getpid(), signal.SIGINT)
157
158 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: