1
# Copyright (C) 2006 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
"""The 'medium' layer for the smart servers and clients.
19
"Medium" here is the noun meaning "a means of transmission", not the adjective
20
for "the quality between big and small."
22
Media carry the bytes of the requests somehow (e.g. via TCP, wrapped in HTTP, or
23
over SSH), and pass them to and from the protocol logic. See the overview in
24
bzrlib/transport/smart/__init__.py.
32
from bzrlib.lazy_import import lazy_import
33
lazy_import(globals(), """
40
from bzrlib.smart import protocol
41
from bzrlib.transport import ssh
45
def _get_protocol_factory_for_bytes(bytes):
46
"""Determine the right protocol factory for 'bytes'.
48
This will return an appropriate protocol factory depending on the version
49
of the protocol being used, as determined by inspecting the given bytes.
50
The bytes should have at least one newline byte (i.e. be a whole line),
51
otherwise it's possible that a request will be incorrectly identified as
54
Typical use would be::
56
factory, unused_bytes = _get_protocol_factory_for_bytes(bytes)
57
server_protocol = factory(transport, write_func, root_client_path)
58
server_protocol.accept_bytes(unused_bytes)
60
:param bytes: a str of bytes of the start of the request.
61
:returns: 2-tuple of (protocol_factory, unused_bytes). protocol_factory is
62
a callable that takes three args: transport, write_func,
63
root_client_path. unused_bytes are any bytes that were not part of a
64
protocol version marker.
66
if bytes.startswith(protocol.MESSAGE_VERSION_THREE):
67
protocol_factory = protocol.build_server_protocol_three
68
bytes = bytes[len(protocol.MESSAGE_VERSION_THREE):]
69
elif bytes.startswith(protocol.REQUEST_VERSION_TWO):
70
protocol_factory = protocol.SmartServerRequestProtocolTwo
71
bytes = bytes[len(protocol.REQUEST_VERSION_TWO):]
73
protocol_factory = protocol.SmartServerRequestProtocolOne
74
return protocol_factory, bytes
77
class SmartServerStreamMedium(object):
78
"""Handles smart commands coming over a stream.
80
The stream may be a pipe connected to sshd, or a tcp socket, or an
81
in-process fifo for testing.
83
One instance is created for each connected client; it can serve multiple
84
requests in the lifetime of the connection.
86
The server passes requests through to an underlying backing transport,
87
which will typically be a LocalTransport looking at the server's filesystem.
89
:ivar _push_back_buffer: a str of bytes that have been read from the stream
90
but not used yet, or None if there are no buffered bytes. Subclasses
91
should make sure to exhaust this buffer before reading more bytes from
92
the stream. See also the _push_back method.
95
def __init__(self, backing_transport, root_client_path='/'):
96
"""Construct new server.
98
:param backing_transport: Transport for the directory served.
100
# backing_transport could be passed to serve instead of __init__
101
self.backing_transport = backing_transport
102
self.root_client_path = root_client_path
103
self.finished = False
104
self._push_back_buffer = None
106
def _push_back(self, bytes):
107
"""Return unused bytes to the medium, because they belong to the next
110
This sets the _push_back_buffer to the given bytes.
112
if self._push_back_buffer is not None:
113
raise AssertionError(
114
"_push_back called when self._push_back_buffer is %r"
115
% (self._push_back_buffer,))
118
self._push_back_buffer = bytes
120
def _get_push_back_buffer(self):
121
if self._push_back_buffer == '':
122
raise AssertionError(
123
'%s._push_back_buffer should never be the empty string, '
124
'which can be confused with EOF' % (self,))
125
bytes = self._push_back_buffer
126
self._push_back_buffer = None
130
"""Serve requests until the client disconnects."""
131
# Keep a reference to stderr because the sys module's globals get set to
132
# None during interpreter shutdown.
133
from sys import stderr
135
while not self.finished:
136
server_protocol = self._build_protocol()
137
self._serve_one_request(server_protocol)
139
stderr.write("%s terminating on exception %s\n" % (self, e))
142
def _build_protocol(self):
143
"""Identifies the version of the incoming request, and returns an
144
a protocol object that can interpret it.
146
If more bytes than the version prefix of the request are read, they will
147
be fed into the protocol before it is returned.
149
:returns: a SmartServerRequestProtocol.
151
bytes = self._get_line()
152
protocol_factory, unused_bytes = _get_protocol_factory_for_bytes(bytes)
153
protocol = protocol_factory(
154
self.backing_transport, self._write_out, self.root_client_path)
155
protocol.accept_bytes(unused_bytes)
158
def _serve_one_request(self, protocol):
159
"""Read one request from input, process, send back a response.
161
:param protocol: a SmartServerRequestProtocol.
164
self._serve_one_request_unguarded(protocol)
165
except KeyboardInterrupt:
168
self.terminate_due_to_error()
170
def terminate_due_to_error(self):
171
"""Called when an unhandled exception from the protocol occurs."""
172
raise NotImplementedError(self.terminate_due_to_error)
174
def _get_bytes(self, desired_count):
175
"""Get some bytes from the medium.
177
:param desired_count: number of bytes we want to read.
179
raise NotImplementedError(self._get_bytes)
182
"""Read bytes from this request's response until a newline byte.
184
This isn't particularly efficient, so should only be used when the
185
expected size of the line is quite short.
187
:returns: a string of bytes ending in a newline (byte 0x0A).
191
while newline_pos == -1:
192
new_bytes = self._get_bytes(1)
195
# Ran out of bytes before receiving a complete line.
197
newline_pos = bytes.find('\n')
198
line = bytes[:newline_pos+1]
199
self._push_back(bytes[newline_pos+1:])
203
class SmartServerSocketStreamMedium(SmartServerStreamMedium):
205
def __init__(self, sock, backing_transport, root_client_path='/'):
208
:param sock: the socket the server will read from. It will be put
211
SmartServerStreamMedium.__init__(
212
self, backing_transport, root_client_path=root_client_path)
213
sock.setblocking(True)
216
def _serve_one_request_unguarded(self, protocol):
217
while protocol.next_read_size():
218
bytes = self._get_bytes(4096)
222
protocol.accept_bytes(bytes)
224
self._push_back(protocol.unused_data)
226
def _get_bytes(self, desired_count):
227
if self._push_back_buffer is not None:
228
return self._get_push_back_buffer()
229
# We ignore the desired_count because on sockets it's more efficient to
231
return self.socket.recv(4096)
233
def terminate_due_to_error(self):
234
# TODO: This should log to a server log file, but no such thing
235
# exists yet. Andrew Bennetts 2006-09-29.
239
def _write_out(self, bytes):
240
osutils.send_all(self.socket, bytes)
243
class SmartServerPipeStreamMedium(SmartServerStreamMedium):
245
def __init__(self, in_file, out_file, backing_transport):
246
"""Construct new server.
248
:param in_file: Python file from which requests can be read.
249
:param out_file: Python file to write responses.
250
:param backing_transport: Transport for the directory served.
252
SmartServerStreamMedium.__init__(self, backing_transport)
253
if sys.platform == 'win32':
254
# force binary mode for files
256
for f in (in_file, out_file):
257
fileno = getattr(f, 'fileno', None)
259
msvcrt.setmode(fileno(), os.O_BINARY)
263
def _serve_one_request_unguarded(self, protocol):
265
bytes_to_read = protocol.next_read_size()
266
if bytes_to_read == 0:
267
# Finished serving this request.
270
bytes = self._get_bytes(bytes_to_read)
272
# Connection has been closed.
276
protocol.accept_bytes(bytes)
278
def _get_bytes(self, desired_count):
279
if self._push_back_buffer is not None:
280
return self._get_push_back_buffer()
281
return self._in.read(desired_count)
283
def terminate_due_to_error(self):
284
# TODO: This should log to a server log file, but no such thing
285
# exists yet. Andrew Bennetts 2006-09-29.
289
def _write_out(self, bytes):
290
self._out.write(bytes)
293
class SmartClientMediumRequest(object):
294
"""A request on a SmartClientMedium.
296
Each request allows bytes to be provided to it via accept_bytes, and then
297
the response bytes to be read via read_bytes.
300
request.accept_bytes('123')
301
request.finished_writing()
302
result = request.read_bytes(3)
303
request.finished_reading()
305
It is up to the individual SmartClientMedium whether multiple concurrent
306
requests can exist. See SmartClientMedium.get_request to obtain instances
307
of SmartClientMediumRequest, and the concrete Medium you are using for
308
details on concurrency and pipelining.
311
def __init__(self, medium):
312
"""Construct a SmartClientMediumRequest for the medium medium."""
313
self._medium = medium
314
# we track state by constants - we may want to use the same
315
# pattern as BodyReader if it gets more complex.
316
# valid states are: "writing", "reading", "done"
317
self._state = "writing"
319
def accept_bytes(self, bytes):
320
"""Accept bytes for inclusion in this request.
322
This method may not be be called after finished_writing() has been
323
called. It depends upon the Medium whether or not the bytes will be
324
immediately transmitted. Message based Mediums will tend to buffer the
325
bytes until finished_writing() is called.
327
:param bytes: A bytestring.
329
if self._state != "writing":
330
raise errors.WritingCompleted(self)
331
self._accept_bytes(bytes)
333
def _accept_bytes(self, bytes):
334
"""Helper for accept_bytes.
336
Accept_bytes checks the state of the request to determing if bytes
337
should be accepted. After that it hands off to _accept_bytes to do the
340
raise NotImplementedError(self._accept_bytes)
342
def finished_reading(self):
343
"""Inform the request that all desired data has been read.
345
This will remove the request from the pipeline for its medium (if the
346
medium supports pipelining) and any further calls to methods on the
347
request will raise ReadingCompleted.
349
if self._state == "writing":
350
raise errors.WritingNotComplete(self)
351
if self._state != "reading":
352
raise errors.ReadingCompleted(self)
354
self._finished_reading()
356
def _finished_reading(self):
357
"""Helper for finished_reading.
359
finished_reading checks the state of the request to determine if
360
finished_reading is allowed, and if it is hands off to _finished_reading
361
to perform the action.
363
raise NotImplementedError(self._finished_reading)
365
def finished_writing(self):
366
"""Finish the writing phase of this request.
368
This will flush all pending data for this request along the medium.
369
After calling finished_writing, you may not call accept_bytes anymore.
371
if self._state != "writing":
372
raise errors.WritingCompleted(self)
373
self._state = "reading"
374
self._finished_writing()
376
def _finished_writing(self):
377
"""Helper for finished_writing.
379
finished_writing checks the state of the request to determine if
380
finished_writing is allowed, and if it is hands off to _finished_writing
381
to perform the action.
383
raise NotImplementedError(self._finished_writing)
385
def read_bytes(self, count):
386
"""Read bytes from this requests response.
388
This method will block and wait for count bytes to be read. It may not
389
be invoked until finished_writing() has been called - this is to ensure
390
a message-based approach to requests, for compatibility with message
391
based mediums like HTTP.
393
if self._state == "writing":
394
raise errors.WritingNotComplete(self)
395
if self._state != "reading":
396
raise errors.ReadingCompleted(self)
397
return self._read_bytes(count)
399
def _read_bytes(self, count):
400
"""Helper for read_bytes.
402
read_bytes checks the state of the request to determing if bytes
403
should be read. After that it hands off to _read_bytes to do the
406
raise NotImplementedError(self._read_bytes)
409
"""Read bytes from this request's response until a newline byte.
411
This isn't particularly efficient, so should only be used when the
412
expected size of the line is quite short.
414
:returns: a string of bytes ending in a newline (byte 0x0A).
416
# XXX: this duplicates SmartClientRequestProtocolOne._recv_tuple
418
while not line or line[-1] != '\n':
419
new_char = self.read_bytes(1)
422
# end of file encountered reading from server
423
raise errors.ConnectionReset(
424
"please check connectivity and permissions",
425
"(and try -Dhpss if further diagnosis is required)")
429
class SmartClientMedium(object):
430
"""Smart client is a medium for sending smart protocol requests over."""
432
def __init__(self, base):
433
super(SmartClientMedium, self).__init__()
435
self._protocol_version_error = None
436
self._protocol_version = None
437
self._done_hello = False
438
# Be optimistic: we assume the remote end can accept new remote
439
# requests until we get an error saying otherwise.
440
# _remote_version_is_before tracks the bzr version the remote side
441
# can be based on what we've seen so far.
442
self._remote_version_is_before = None
444
def _is_remote_before(self, version_tuple):
445
"""Is it possible the remote side supports RPCs for a given version?
449
needed_version = (1, 2)
450
if medium._is_remote_before(needed_version):
451
fallback_to_pre_1_2_rpc()
455
except UnknownSmartMethod:
456
medium._remember_remote_is_before(needed_version)
457
fallback_to_pre_1_2_rpc()
459
:seealso: _remember_remote_is_before
461
if self._remote_version_is_before is None:
462
# So far, the remote side seems to support everything
464
return version_tuple >= self._remote_version_is_before
466
def _remember_remote_is_before(self, version_tuple):
467
"""Tell this medium that the remote side is older the given version.
469
:seealso: _is_remote_before
471
if (self._remote_version_is_before is not None and
472
version_tuple > self._remote_version_is_before):
473
raise AssertionError(
474
"_remember_remote_is_before(%r) called, but "
475
"_remember_remote_is_before(%r) was called previously."
476
% (version_tuple, self._remote_version_is_before))
477
self._remote_version_is_before = version_tuple
479
def protocol_version(self):
480
"""Find out if 'hello' smart request works."""
481
if self._protocol_version_error is not None:
482
raise self._protocol_version_error
483
if not self._done_hello:
485
medium_request = self.get_request()
486
# Send a 'hello' request in protocol version one, for maximum
487
# backwards compatibility.
488
client_protocol = protocol.SmartClientRequestProtocolOne(medium_request)
489
client_protocol.query_version()
490
self._done_hello = True
491
except errors.SmartProtocolError, e:
492
# Cache the error, just like we would cache a successful
494
self._protocol_version_error = e
498
def should_probe(self):
499
"""Should RemoteBzrDirFormat.probe_transport send a smart request on
502
Some transports are unambiguously smart-only; there's no need to check
503
if the transport is able to carry smart requests, because that's all
504
it is for. In those cases, this method should return False.
506
But some HTTP transports can sometimes fail to carry smart requests,
507
but still be usuable for accessing remote bzrdirs via plain file
508
accesses. So for those transports, their media should return True here
509
so that RemoteBzrDirFormat can determine if it is appropriate for that
514
def disconnect(self):
515
"""If this medium maintains a persistent connection, close it.
517
The default implementation does nothing.
520
def remote_path_from_transport(self, transport):
521
"""Convert transport into a path suitable for using in a request.
523
Note that the resulting remote path doesn't encode the host name or
524
anything but path, so it is only safe to use it in requests sent over
525
the medium from the matching transport.
527
medium_base = urlutils.join(self.base, '/')
528
rel_url = urlutils.relative_url(medium_base, transport.base)
529
return urllib.unquote(rel_url)
532
class SmartClientStreamMedium(SmartClientMedium):
533
"""Stream based medium common class.
535
SmartClientStreamMediums operate on a stream. All subclasses use a common
536
SmartClientStreamMediumRequest for their requests, and should implement
537
_accept_bytes and _read_bytes to allow the request objects to send and
541
def __init__(self, base):
542
SmartClientMedium.__init__(self, base)
543
self._current_request = None
545
def accept_bytes(self, bytes):
546
self._accept_bytes(bytes)
549
"""The SmartClientStreamMedium knows how to close the stream when it is
555
"""Flush the output stream.
557
This method is used by the SmartClientStreamMediumRequest to ensure that
558
all data for a request is sent, to avoid long timeouts or deadlocks.
560
raise NotImplementedError(self._flush)
562
def get_request(self):
563
"""See SmartClientMedium.get_request().
565
SmartClientStreamMedium always returns a SmartClientStreamMediumRequest
568
return SmartClientStreamMediumRequest(self)
570
def read_bytes(self, count):
571
return self._read_bytes(count)
574
class SmartSimplePipesClientMedium(SmartClientStreamMedium):
575
"""A client medium using simple pipes.
577
This client does not manage the pipes: it assumes they will always be open.
580
def __init__(self, readable_pipe, writeable_pipe, base):
581
SmartClientStreamMedium.__init__(self, base)
582
self._readable_pipe = readable_pipe
583
self._writeable_pipe = writeable_pipe
585
def _accept_bytes(self, bytes):
586
"""See SmartClientStreamMedium.accept_bytes."""
587
self._writeable_pipe.write(bytes)
590
"""See SmartClientStreamMedium._flush()."""
591
self._writeable_pipe.flush()
593
def _read_bytes(self, count):
594
"""See SmartClientStreamMedium._read_bytes."""
595
return self._readable_pipe.read(count)
598
class SmartSSHClientMedium(SmartClientStreamMedium):
599
"""A client medium using SSH."""
601
def __init__(self, host, port=None, username=None, password=None,
602
base=None, vendor=None, bzr_remote_path=None):
603
"""Creates a client that will connect on the first use.
605
:param vendor: An optional override for the ssh vendor to use. See
606
bzrlib.transport.ssh for details on ssh vendors.
608
SmartClientStreamMedium.__init__(self, base)
609
self._connected = False
611
self._password = password
613
self._username = username
614
self._read_from = None
615
self._ssh_connection = None
616
self._vendor = vendor
617
self._write_to = None
618
self._bzr_remote_path = bzr_remote_path
619
if self._bzr_remote_path is None:
620
symbol_versioning.warn(
621
'bzr_remote_path is required as of bzr 0.92',
622
DeprecationWarning, stacklevel=2)
623
self._bzr_remote_path = os.environ.get('BZR_REMOTE_PATH', 'bzr')
625
def _accept_bytes(self, bytes):
626
"""See SmartClientStreamMedium.accept_bytes."""
627
self._ensure_connection()
628
self._write_to.write(bytes)
630
def disconnect(self):
631
"""See SmartClientMedium.disconnect()."""
632
if not self._connected:
634
self._read_from.close()
635
self._write_to.close()
636
self._ssh_connection.close()
637
self._connected = False
639
def _ensure_connection(self):
640
"""Connect this medium if not already connected."""
643
if self._vendor is None:
644
vendor = ssh._get_ssh_vendor()
646
vendor = self._vendor
647
self._ssh_connection = vendor.connect_ssh(self._username,
648
self._password, self._host, self._port,
649
command=[self._bzr_remote_path, 'serve', '--inet',
650
'--directory=/', '--allow-writes'])
651
self._read_from, self._write_to = \
652
self._ssh_connection.get_filelike_channels()
653
self._connected = True
656
"""See SmartClientStreamMedium._flush()."""
657
self._write_to.flush()
659
def _read_bytes(self, count):
660
"""See SmartClientStreamMedium.read_bytes."""
661
if not self._connected:
662
raise errors.MediumNotConnected(self)
663
return self._read_from.read(count)
666
# Port 4155 is the default port for bzr://, registered with IANA.
667
BZR_DEFAULT_INTERFACE = '0.0.0.0'
668
BZR_DEFAULT_PORT = 4155
671
class SmartTCPClientMedium(SmartClientStreamMedium):
672
"""A client medium using TCP."""
674
def __init__(self, host, port, base):
675
"""Creates a client that will connect on the first use."""
676
SmartClientStreamMedium.__init__(self, base)
677
self._connected = False
682
def _accept_bytes(self, bytes):
683
"""See SmartClientMedium.accept_bytes."""
684
self._ensure_connection()
685
osutils.send_all(self._socket, bytes)
687
def disconnect(self):
688
"""See SmartClientMedium.disconnect()."""
689
if not self._connected:
693
self._connected = False
695
def _ensure_connection(self):
696
"""Connect this medium if not already connected."""
699
self._socket = socket.socket()
700
self._socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
701
if self._port is None:
702
port = BZR_DEFAULT_PORT
704
port = int(self._port)
706
self._socket.connect((self._host, port))
707
except socket.error, err:
708
# socket errors either have a (string) or (errno, string) as their
710
if type(err.args) is str:
713
err_msg = err.args[1]
714
raise errors.ConnectionError("failed to connect to %s:%d: %s" %
715
(self._host, port, err_msg))
716
self._connected = True
719
"""See SmartClientStreamMedium._flush().
721
For TCP we do no flushing. We may want to turn off TCP_NODELAY and
722
add a means to do a flush, but that can be done in the future.
725
def _read_bytes(self, count):
726
"""See SmartClientMedium.read_bytes."""
727
if not self._connected:
728
raise errors.MediumNotConnected(self)
729
return self._socket.recv(count)
732
class SmartClientStreamMediumRequest(SmartClientMediumRequest):
733
"""A SmartClientMediumRequest that works with an SmartClientStreamMedium."""
735
def __init__(self, medium):
736
SmartClientMediumRequest.__init__(self, medium)
737
# check that we are safe concurrency wise. If some streams start
738
# allowing concurrent requests - i.e. via multiplexing - then this
739
# assert should be moved to SmartClientStreamMedium.get_request,
740
# and the setting/unsetting of _current_request likewise moved into
741
# that class : but its unneeded overhead for now. RBC 20060922
742
if self._medium._current_request is not None:
743
raise errors.TooManyConcurrentRequests(self._medium)
744
self._medium._current_request = self
746
def _accept_bytes(self, bytes):
747
"""See SmartClientMediumRequest._accept_bytes.
749
This forwards to self._medium._accept_bytes because we are operating
750
on the mediums stream.
752
self._medium._accept_bytes(bytes)
754
def _finished_reading(self):
755
"""See SmartClientMediumRequest._finished_reading.
757
This clears the _current_request on self._medium to allow a new
758
request to be created.
760
if self._medium._current_request is not self:
761
raise AssertionError()
762
self._medium._current_request = None
764
def _finished_writing(self):
765
"""See SmartClientMediumRequest._finished_writing.
767
This invokes self._medium._flush to ensure all bytes are transmitted.
769
self._medium._flush()
771
def _read_bytes(self, count):
772
"""See SmartClientMediumRequest._read_bytes.
774
This forwards to self._medium._read_bytes because we are operating
775
on the mediums stream.
777
return self._medium._read_bytes(count)