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