1
# Copyright (C) 2006, 2007 Canonical Ltd
3
# This program is free software; you can redistribute it and/or modify
4
# it under the terms of the GNU General Public License as published by
5
# the Free Software Foundation; either version 2 of the License, or
6
# (at your option) any later version.
8
# This program is distributed in the hope that it will be useful,
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11
# GNU General Public License for more details.
13
# You should have received a copy of the GNU General Public License
14
# along with this program; if not, write to the Free Software
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17
"""Server for smart-server protocol."""
24
from bzrlib.hooks import Hooks
25
from bzrlib.smart import medium
31
from bzrlib.smart.medium import SmartServerSocketStreamMedium
34
class SmartTCPServer(object):
35
"""Listens on a TCP socket and accepts connections from smart clients.
37
Each connection will be served by a SmartServerSocketStreamMedium running in
40
hooks: An instance of SmartServerHooks.
43
def __init__(self, backing_transport, host='127.0.0.1', port=0):
44
"""Construct a new server.
46
To actually start it running, call either start_background_thread or
49
:param host: Name of the interface to listen on.
50
:param port: TCP port to listen on, or 0 to allocate a transient port.
52
# let connections timeout so that we get a chance to terminate
53
# Keep a reference to the exceptions we want to catch because the socket
54
# module's globals get set to None during interpreter shutdown.
55
from socket import timeout as socket_timeout
56
from socket import error as socket_error
57
self._socket_error = socket_error
58
self._socket_timeout = socket_timeout
59
self._server_socket = socket.socket()
60
self._server_socket.bind((host, port))
61
self._sockname = self._server_socket.getsockname()
62
self.port = self._sockname[1]
63
self._server_socket.listen(1)
64
self._server_socket.settimeout(1)
65
self.backing_transport = backing_transport
66
self._started = threading.Event()
67
self._stopped = threading.Event()
70
self._should_terminate = False
71
for hook in SmartTCPServer.hooks['server_started']:
72
hook(self.backing_transport.base, self.get_url())
76
while not self._should_terminate:
78
conn, client_addr = self._server_socket.accept()
79
except self._socket_timeout:
80
# just check if we're asked to stop
82
except self._socket_error, e:
83
# if the socket is closed by stop_background_thread
84
# we might get a EBADF here, any other socket errors
86
if e.args[0] != errno.EBADF:
87
trace.warning("listening socket error: %s", e)
90
except KeyboardInterrupt:
91
# dont log when CTRL-C'd.
94
trace.error("Unhandled smart server error.")
95
trace.log_exception_quietly()
100
# ensure the server socket is closed.
101
self._server_socket.close()
102
except self._socket_error:
103
# ignore errors on close
105
for hook in SmartTCPServer.hooks['server_stopped']:
106
hook(self.backing_transport.base, self.get_url())
109
"""Return the url of the server"""
110
return "bzr://%s:%d/" % self._sockname
112
def serve_conn(self, conn):
113
# For WIN32, where the timeout value from the listening socket
114
# propogates to the newly accepted socket.
115
conn.setblocking(True)
116
conn.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
117
handler = SmartServerSocketStreamMedium(conn, self.backing_transport)
118
connection_thread = threading.Thread(None, handler.serve, name='smart-server-child')
119
connection_thread.setDaemon(True)
120
connection_thread.start()
122
def start_background_thread(self):
123
self._started.clear()
124
self._server_thread = threading.Thread(None,
126
name='server-' + self.get_url())
127
self._server_thread.setDaemon(True)
128
self._server_thread.start()
131
def stop_background_thread(self):
132
self._stopped.clear()
133
# tell the main loop to quit on the next iteration.
134
self._should_terminate = True
135
# close the socket - gives error to connections from here on in,
136
# rather than a connection reset error to connections made during
137
# the period between setting _should_terminate = True and
138
# the current request completing/aborting. It may also break out the
139
# main loop if it was currently in accept() (on some platforms).
141
self._server_socket.close()
142
except self._socket_error:
143
# ignore errors on close
145
if not self._stopped.isSet():
146
# server has not stopped (though it may be stopping)
147
# its likely in accept(), so give it a connection
148
temp_socket = socket.socket()
149
temp_socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
150
if not temp_socket.connect_ex(self._sockname):
151
# and close it immediately: we dont choose to send any requests.
154
self._server_thread.join()
157
class SmartServerHooks(Hooks):
158
"""Hooks for the smart server."""
161
"""Create the default hooks.
163
These are all empty initially, because by default nothing should get
167
# Introduced in 0.16:
168
# invoked whenever the server starts serving a directory.
169
# The api signature is (backing url, public url).
170
self['server_started'] = []
171
# Introduced in 0.16:
172
# invoked whenever the server stops serving a directory.
173
# The api signature is (backing url, public url).
174
self['server_stopped'] = []
176
SmartTCPServer.hooks = SmartServerHooks()
179
class SmartTCPServer_for_testing(SmartTCPServer):
180
"""Server suitable for use by transport tests.
182
This server is backed by the process's cwd.
186
SmartTCPServer.__init__(self, None)
188
def get_backing_transport(self, backing_transport_server):
189
"""Get a backing transport from a server we are decorating."""
190
return transport.get_transport(backing_transport_server.get_url())
192
def setUp(self, backing_transport_server=None):
193
"""Set up server for testing"""
194
from bzrlib.transport.chroot import ChrootServer
195
if backing_transport_server is None:
196
from bzrlib.transport.local import LocalURLServer
197
backing_transport_server = LocalURLServer()
198
self.chroot_server = ChrootServer(
199
self.get_backing_transport(backing_transport_server))
200
self.chroot_server.setUp()
201
self.backing_transport = transport.get_transport(
202
self.chroot_server.get_url())
203
self.start_background_thread()
206
self.stop_background_thread()
207
self.chroot_server.tearDown()
209
def get_bogus_url(self):
210
"""Return a URL which will fail to connect"""
211
return 'bzr://127.0.0.1:1/'
214
class ReadonlySmartTCPServer_for_testing(SmartTCPServer_for_testing):
215
"""Get a readonly server for testing."""
217
def get_backing_transport(self, backing_transport_server):
218
"""Get a backing transport from a server we are decorating."""
219
url = 'readonly+' + backing_transport_server.get_url()
220
return transport.get_transport(url)