[Merge] Merge with trunk addons
[odoo/odoo.git] / bin / service / netrpc_server.py
1 # -*- coding: utf-8 -*-
2
3 #
4 # Copyright P. Christeas <p_christ@hol.gr> 2008,2009
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 """ This file contains instance of the net-rpc server
23
24     
25 """
26 import netsvc
27 import threading
28 import tools
29 import os
30 import select
31 import socket
32
33 import tiny_socket
34
35 class TinySocketClientThread(threading.Thread, netsvc.OpenERPDispatcher):
36     def __init__(self, sock, threads):
37         threading.Thread.__init__(self)
38         self.sock = sock
39         # Only at the server side, use a big timeout: close the
40         # clients connection when they're idle for 20min.
41         self.sock.settimeout(1200)
42         self.threads = threads
43
44     def __del__(self):
45         if self.sock:
46             try:
47                 self.socket.shutdown(
48                     getattr(socket, 'SHUT_RDWR', 2))
49             except: pass
50             # That should garbage-collect and close it, too
51             self.sock = None
52
53     def run(self):
54         self.running = True
55         try:
56             ts = tiny_socket.mysocket(self.sock)
57         except:
58             self.threads.remove(self)
59             self.running = False
60             return False
61         while self.running:
62             try:
63                 msg = ts.myreceive()
64             except:
65                 self.threads.remove(self)
66                 self.running = False
67                 return False
68             try:
69                 result = self.dispatch(msg[0], msg[1], msg[2:])
70                 ts.mysend(result)
71             except netsvc.OpenERPDispatcherException, e:
72                 try:
73                     new_e = Exception(tools.exception_to_unicode(e.exception)) # avoid problems of pickeling
74                     ts.mysend(new_e, exception=True, traceback=e.traceback)
75                 except:
76                     self.running = False
77                     break
78             except Exception, e:
79                 # this code should not be reachable, therefore we warn
80                 netsvc.Logger().notifyChannel("net-rpc", netsvc.LOG_WARNING, "exception: %s" % str(e))
81                 break
82
83         self.threads.remove(self)
84         self.running = False
85         return True
86
87     def stop(self):
88         self.running = False
89
90
91 class TinySocketServerThread(threading.Thread,netsvc.Server):
92     def __init__(self, interface, port, secure=False):
93         threading.Thread.__init__(self, name="Net-RPC socket")
94         netsvc.Server.__init__(self)
95         self.__port = port
96         self.__interface = interface
97         self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
98         self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
99         self.socket.bind((self.__interface, self.__port))
100         self.socket.listen(5)
101         self.threads = []
102         netsvc.Logger().notifyChannel("web-services", netsvc.LOG_INFO, 
103                          "starting NET-RPC service at %s port %d" % (interface or '0.0.0.0', port,))
104
105     def run(self):
106         try:
107             self.running = True
108             while self.running:
109                 timeout = self.socket.gettimeout()
110                 fd_sets = select.select([self.socket], [], [], timeout)
111                 if not fd_sets[0]:
112                     continue
113                 (clientsocket, address) = self.socket.accept()
114                 ct = TinySocketClientThread(clientsocket, self.threads)
115                 clientsocket = None
116                 self.threads.append(ct)
117                 ct.start()
118                 lt = len(self.threads)
119                 if (lt > 10) and (lt % 10 == 0):
120                      # Not many threads should be serving at the same time, so log
121                      # their abuse.
122                      netsvc.Logger().notifyChannel("web-services", netsvc.LOG_DEBUG,
123                         "Netrpc: %d threads" % len(self.threads))
124             self.socket.close()
125         except Exception, e:
126             import logging
127             logging.getLogger('web-services').warning("Netrpc: closing because of exception %s" % str(e))
128             self.socket.close()
129             return False
130
131     def stop(self):
132         self.running = False
133         for t in self.threads:
134             t.stop()
135         self._close_socket()
136
137     def stats(self):
138         res = "Net-RPC: " + ( (self.running and "running") or  "stopped")
139         i = 0
140         for t in self.threads:
141             i += 1
142             res += "\nNet-RPC #%d: %s " % (i, t.name)
143             if t.isAlive():
144                 res += "running"
145             else:
146                 res += "finished"
147             if t.sock:
148                 res += ", socket"
149         return res
150
151 netrpcd = None
152
153 def init_servers():
154     global netrpcd
155     if tools.config.get_misc('netrpcd','enable', True):
156         netrpcd = TinySocketServerThread(tools.config.get_misc('netrpcd','interface', ''), \
157             int(tools.config.get_misc('netrpcd','port', tools.config.get('netport', 8070))))