14
14
# along with this program; if not, write to the Free Software
15
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17
"""Smart-server protocol, client and server.
19
Requests are sent as a command and list of arguments, followed by optional
20
bulk body data. Responses are similarly a response and list of arguments,
21
followed by bulk body data. ::
24
Fields are separated by Ctrl-A.
25
BULK_DATA := CHUNK TRAILER
26
Chunks can be repeated as many times as necessary.
27
CHUNK := CHUNK_LEN CHUNK_BODY
28
CHUNK_LEN := DIGIT+ NEWLINE
29
Gives the number of bytes in the following chunk.
30
CHUNK_BODY := BYTE[chunk_len]
31
TRAILER := SUCCESS_TRAILER | ERROR_TRAILER
32
SUCCESS_TRAILER := 'done' NEWLINE
35
Paths are passed across the network. The client needs to see a namespace that
36
includes any repository that might need to be referenced, and the client needs
37
to know about a root directory beyond which it cannot ascend.
39
Servers run over ssh will typically want to be able to access any path the user
40
can access. Public servers on the other hand (which might be over http, ssh
41
or tcp) will typically want to restrict access to only a particular directory
42
and its children, so will want to do a software virtual root at that level.
43
In other words they'll want to rewrite incoming paths to be under that level
44
(and prevent escaping using ../ tricks.)
46
URLs that include ~ should probably be passed across to the server verbatim
47
and the server can expand them. This will proably not be meaningful when
48
limited to a directory?
50
At the bottom level socket, pipes, HTTP server. For sockets, we have the idea
51
that you have multiple requests and get a read error because the other side did
52
shutdown. For pipes we have read pipe which will have a zero read which marks
53
end-of-file. For HTTP server environment there is not end-of-stream because
54
each request coming into the server is independent.
56
So we need a wrapper around pipes and sockets to seperate out requests from
57
substrate and this will give us a single model which is consist for HTTP,
63
MEDIUM (factory for protocol, reads bytes & pushes to protocol,
64
uses protocol to detect end-of-request, sends written
65
bytes to client) e.g. socket, pipe, HTTP request handler.
70
PROTOCOL (serialization, deserialization) accepts bytes for one
71
request, decodes according to internal state, pushes
72
structured data to handler. accepts structured data from
73
handler and encodes and writes to the medium. factory for
79
HANDLER (domain logic) accepts structured data, operates state
80
machine until the request can be satisfied,
81
sends structured data to the protocol.
87
CLIENT domain logic, accepts domain requests, generated structured
88
data, reads structured data from responses and turns into
89
domain data. Sends structured data to the protocol.
90
Operates state machines until the request can be delivered
91
(e.g. reading from a bundle generated in bzrlib to deliver a
94
Possibly this should just be RemoteBzrDir, RemoteTransport,
100
PROTOCOL (serialization, deserialization) accepts structured data for one
101
request, encodes and writes to the medium. Reads bytes from the
102
medium, decodes and allows the client to read structured data.
107
MEDIUM (accepts bytes from the protocol & delivers to the remote server.
108
Allows the potocol to read bytes e.g. socket, pipe, HTTP request.
17
"""RemoteTransport client for the smart-server.
19
This module shouldn't be accessed directly. The classes defined here should be
20
imported from bzrlib.smart.
112
# TODO: _translate_error should be on the client, not the transport because
113
# error coding is wire protocol specific.
115
# TODO: A plain integer from query_version is too simple; should give some
118
# TODO: Server should probably catch exceptions within itself and send them
119
# back across the network. (But shouldn't catch KeyboardInterrupt etc)
120
# Also needs to somehow report protocol errors like bad requests. Need to
121
# consider how we'll handle error reporting, e.g. if we get halfway through a
122
# bulk transfer and then something goes wrong.
124
# TODO: Standard marker at start of request/response lines?
126
# TODO: Make each request and response self-validatable, e.g. with checksums.
128
# TODO: get/put objects could be changed to gradually read back the data as it
129
# comes across the network
131
# TODO: What should the server do if it hits an error and has to terminate?
133
# TODO: is it useful to allow multiple chunks in the bulk data?
135
# TODO: If we get an exception during transmission of bulk data we can't just
136
# emit the exception because it won't be seen.
137
# John proposes: I think it would be worthwhile to have a header on each
138
# chunk, that indicates it is another chunk. Then you can send an 'error'
139
# chunk as long as you finish the previous chunk.
141
# TODO: Clone method on Transport; should work up towards parent directory;
142
# unclear how this should be stored or communicated to the server... maybe
143
# just pass it on all relevant requests?
145
# TODO: Better name than clone() for changing between directories. How about
146
# open_dir or change_dir or chdir?
148
# TODO: Is it really good to have the notion of current directory within the
149
# connection? Perhaps all Transports should factor out a common connection
150
# from the thing that has the directory context?
152
# TODO: Pull more things common to sftp and ssh to a higher level.
154
# TODO: The server that manages a connection should be quite small and retain
155
# minimum state because each of the requests are supposed to be stateless.
156
# Then we can write another implementation that maps to http.
158
# TODO: What to do when a client connection is garbage collected? Maybe just
159
# abruptly drop the connection?
161
# TODO: Server in some cases will need to restrict access to files outside of
162
# a particular root directory. LocalTransport doesn't do anything to stop you
163
# ascending above the base directory, so we need to prevent paths
164
# containing '..' in either the server or transport layers. (Also need to
165
# consider what happens if someone creates a symlink pointing outside the
168
# TODO: Server should rebase absolute paths coming across the network to put
169
# them under the virtual root, if one is in use. LocalTransport currently
170
# doesn't do that; if you give it an absolute path it just uses it.
172
# XXX: Arguments can't contain newlines or ascii; possibly we should e.g.
173
# urlescape them instead. Indeed possibly this should just literally be
176
# FIXME: This transport, with several others, has imperfect handling of paths
177
# within urls. It'd probably be better for ".." from a root to raise an error
178
# rather than return the same directory as we do at present.
180
# TODO: Rather than working at the Transport layer we want a Branch,
181
# Repository or BzrDir objects that talk to a server.
183
# TODO: Probably want some way for server commands to gradually produce body
184
# data rather than passing it as a string; they could perhaps pass an
185
# iterator-like callback that will gradually yield data; it probably needs a
186
# close() method that will always be closed to do any necessary cleanup.
188
# TODO: Split the actual smart server from the ssh encoding of it.
190
# TODO: Perhaps support file-level readwrite operations over the transport
193
# TODO: SmartBzrDir class, proxying all Branch etc methods across to another
194
# branch doing file-level operations.
23
__all__ = ['RemoteTransport', 'RemoteTCPTransport', 'RemoteSSHTransport']
197
25
from cStringIO import StringIO
205
29
from bzrlib import (
213
from bzrlib.bundle.serializer import write_bundle
215
from bzrlib.transport import ssh
216
except errors.ParamikoNotPresent:
217
# no paramiko. SmartSSHClientMedium will break.
34
from bzrlib.smart import client, medium, protocol
220
36
# must do this otherwise urllib can't parse the urls properly :(
221
37
for scheme in ['ssh', 'bzr', 'bzr+loopback', 'bzr+ssh', 'bzr+http']:
226
def _recv_tuple(from_file):
227
req_line = from_file.readline()
228
return _decode_tuple(req_line)
231
def _decode_tuple(req_line):
232
if req_line == None or req_line == '':
234
if req_line[-1] != '\n':
235
raise errors.SmartProtocolError("request %r not terminated" % req_line)
236
return tuple(req_line[:-1].split('\x01'))
239
def _encode_tuple(args):
240
"""Encode the tuple args to a bytestream."""
241
return '\x01'.join(args) + '\n'
244
class SmartProtocolBase(object):
245
"""Methods common to client and server"""
247
# TODO: this only actually accomodates a single block; possibly should
248
# support multiple chunks?
249
def _encode_bulk_data(self, body):
250
"""Encode body as a bulk data chunk."""
251
return ''.join(('%d\n' % len(body), body, 'done\n'))
253
def _serialise_offsets(self, offsets):
254
"""Serialise a readv offset list."""
256
for start, length in offsets:
257
txt.append('%d,%d' % (start, length))
258
return '\n'.join(txt)
261
class SmartServerRequestProtocolOne(SmartProtocolBase):
262
"""Server-side encoding and decoding logic for smart version 1."""
264
def __init__(self, backing_transport, write_func):
265
self._backing_transport = backing_transport
266
self.excess_buffer = ''
267
self._finished = False
269
self.has_dispatched = False
271
self._body_decoder = None
272
self._write_func = write_func
274
def accept_bytes(self, bytes):
275
"""Take bytes, and advance the internal state machine appropriately.
277
:param bytes: must be a byte string
279
assert isinstance(bytes, str)
280
self.in_buffer += bytes
281
if not self.has_dispatched:
282
if '\n' not in self.in_buffer:
283
# no command line yet
285
self.has_dispatched = True
287
first_line, self.in_buffer = self.in_buffer.split('\n', 1)
289
req_args = _decode_tuple(first_line)
290
self.request = SmartServerRequestHandler(
291
self._backing_transport)
292
self.request.dispatch_command(req_args[0], req_args[1:])
293
if self.request.finished_reading:
295
self.excess_buffer = self.in_buffer
297
self._send_response(self.request.response.args,
298
self.request.response.body)
299
except KeyboardInterrupt:
301
except Exception, exception:
302
# everything else: pass to client, flush, and quit
303
self._send_response(('error', str(exception)))
306
if self.has_dispatched:
308
# nothing to do.XXX: this routine should be a single state
310
self.excess_buffer += self.in_buffer
313
if self._body_decoder is None:
314
self._body_decoder = LengthPrefixedBodyDecoder()
315
self._body_decoder.accept_bytes(self.in_buffer)
316
self.in_buffer = self._body_decoder.unused_data
317
body_data = self._body_decoder.read_pending_data()
318
self.request.accept_body(body_data)
319
if self._body_decoder.finished_reading:
320
self.request.end_of_body()
321
assert self.request.finished_reading, \
322
"no more body, request not finished"
323
if self.request.response is not None:
324
self._send_response(self.request.response.args,
325
self.request.response.body)
326
self.excess_buffer = self.in_buffer
329
assert not self.request.finished_reading, \
330
"no response and we have finished reading."
332
def _send_response(self, args, body=None):
333
"""Send a smart server response down the output stream."""
334
assert not self._finished, 'response already sent'
335
self._finished = True
336
self._write_func(_encode_tuple(args))
338
assert isinstance(body, str), 'body must be a str'
339
bytes = self._encode_bulk_data(body)
340
self._write_func(bytes)
342
def next_read_size(self):
345
if self._body_decoder is None:
348
return self._body_decoder.next_read_size()
351
class LengthPrefixedBodyDecoder(object):
352
"""Decodes the length-prefixed bulk data."""
355
self.bytes_left = None
356
self.finished_reading = False
357
self.unused_data = ''
358
self.state_accept = self._state_accept_expecting_length
359
self.state_read = self._state_read_no_data
361
self._trailer_buffer = ''
363
def accept_bytes(self, bytes):
364
"""Decode as much of bytes as possible.
366
If 'bytes' contains too much data it will be appended to
369
finished_reading will be set when no more data is required. Further
370
data will be appended to self.unused_data.
372
# accept_bytes is allowed to change the state
373
current_state = self.state_accept
374
self.state_accept(bytes)
375
while current_state != self.state_accept:
376
current_state = self.state_accept
377
self.state_accept('')
379
def next_read_size(self):
380
if self.bytes_left is not None:
381
# Ideally we want to read all the remainder of the body and the
383
return self.bytes_left + 5
384
elif self.state_accept == self._state_accept_reading_trailer:
385
# Just the trailer left
386
return 5 - len(self._trailer_buffer)
387
elif self.state_accept == self._state_accept_expecting_length:
388
# There's still at least 6 bytes left ('\n' to end the length, plus
392
# Reading excess data. Either way, 1 byte at a time is fine.
395
def read_pending_data(self):
396
"""Return any pending data that has been decoded."""
397
return self.state_read()
399
def _state_accept_expecting_length(self, bytes):
400
self._in_buffer += bytes
401
pos = self._in_buffer.find('\n')
404
self.bytes_left = int(self._in_buffer[:pos])
405
self._in_buffer = self._in_buffer[pos+1:]
406
self.bytes_left -= len(self._in_buffer)
407
self.state_accept = self._state_accept_reading_body
408
self.state_read = self._state_read_in_buffer
410
def _state_accept_reading_body(self, bytes):
411
self._in_buffer += bytes
412
self.bytes_left -= len(bytes)
413
if self.bytes_left <= 0:
415
if self.bytes_left != 0:
416
self._trailer_buffer = self._in_buffer[self.bytes_left:]
417
self._in_buffer = self._in_buffer[:self.bytes_left]
418
self.bytes_left = None
419
self.state_accept = self._state_accept_reading_trailer
421
def _state_accept_reading_trailer(self, bytes):
422
self._trailer_buffer += bytes
423
# TODO: what if the trailer does not match "done\n"? Should this raise
424
# a ProtocolViolation exception?
425
if self._trailer_buffer.startswith('done\n'):
426
self.unused_data = self._trailer_buffer[len('done\n'):]
427
self.state_accept = self._state_accept_reading_unused
428
self.finished_reading = True
430
def _state_accept_reading_unused(self, bytes):
431
self.unused_data += bytes
433
def _state_read_no_data(self):
436
def _state_read_in_buffer(self):
437
result = self._in_buffer
442
class SmartServerStreamMedium(object):
443
"""Handles smart commands coming over a stream.
445
The stream may be a pipe connected to sshd, or a tcp socket, or an
446
in-process fifo for testing.
448
One instance is created for each connected client; it can serve multiple
449
requests in the lifetime of the connection.
451
The server passes requests through to an underlying backing transport,
452
which will typically be a LocalTransport looking at the server's filesystem.
455
def __init__(self, backing_transport):
456
"""Construct new server.
458
:param backing_transport: Transport for the directory served.
460
# backing_transport could be passed to serve instead of __init__
461
self.backing_transport = backing_transport
462
self.finished = False
465
"""Serve requests until the client disconnects."""
466
# Keep a reference to stderr because the sys module's globals get set to
467
# None during interpreter shutdown.
468
from sys import stderr
470
while not self.finished:
471
protocol = SmartServerRequestProtocolOne(self.backing_transport,
473
self._serve_one_request(protocol)
475
stderr.write("%s terminating on exception %s\n" % (self, e))
478
def _serve_one_request(self, protocol):
479
"""Read one request from input, process, send back a response.
481
:param protocol: a SmartServerRequestProtocol.
484
self._serve_one_request_unguarded(protocol)
485
except KeyboardInterrupt:
488
self.terminate_due_to_error()
490
def terminate_due_to_error(self):
491
"""Called when an unhandled exception from the protocol occurs."""
492
raise NotImplementedError(self.terminate_due_to_error)
495
class SmartServerSocketStreamMedium(SmartServerStreamMedium):
497
def __init__(self, sock, backing_transport):
500
:param sock: the socket the server will read from. It will be put
503
SmartServerStreamMedium.__init__(self, backing_transport)
505
sock.setblocking(True)
508
def _serve_one_request_unguarded(self, protocol):
509
while protocol.next_read_size():
511
protocol.accept_bytes(self.push_back)
514
bytes = self.socket.recv(4096)
518
protocol.accept_bytes(bytes)
520
self.push_back = protocol.excess_buffer
522
def terminate_due_to_error(self):
523
"""Called when an unhandled exception from the protocol occurs."""
524
# TODO: This should log to a server log file, but no such thing
525
# exists yet. Andrew Bennetts 2006-09-29.
529
def _write_out(self, bytes):
530
self.socket.sendall(bytes)
533
class SmartServerPipeStreamMedium(SmartServerStreamMedium):
535
def __init__(self, in_file, out_file, backing_transport):
536
"""Construct new server.
538
:param in_file: Python file from which requests can be read.
539
:param out_file: Python file to write responses.
540
:param backing_transport: Transport for the directory served.
542
SmartServerStreamMedium.__init__(self, backing_transport)
546
def _serve_one_request_unguarded(self, protocol):
548
bytes_to_read = protocol.next_read_size()
549
if bytes_to_read == 0:
550
# Finished serving this request.
553
bytes = self._in.read(bytes_to_read)
555
# Connection has been closed.
559
protocol.accept_bytes(bytes)
561
def terminate_due_to_error(self):
562
# TODO: This should log to a server log file, but no such thing
563
# exists yet. Andrew Bennetts 2006-09-29.
567
def _write_out(self, bytes):
568
self._out.write(bytes)
571
class SmartServerResponse(object):
572
"""Response generated by SmartServerRequestHandler."""
574
def __init__(self, args, body=None):
578
# XXX: TODO: Create a SmartServerRequestHandler which will take the responsibility
579
# for delivering the data for a request. This could be done with as the
580
# StreamServer, though that would create conflation between request and response
581
# which may be undesirable.
584
class SmartServerRequestHandler(object):
585
"""Protocol logic for smart server.
587
This doesn't handle serialization at all, it just processes requests and
591
# IMPORTANT FOR IMPLEMENTORS: It is important that SmartServerRequestHandler
592
# not contain encoding or decoding logic to allow the wire protocol to vary
593
# from the object protocol: we will want to tweak the wire protocol separate
594
# from the object model, and ideally we will be able to do that without
595
# having a SmartServerRequestHandler subclass for each wire protocol, rather
596
# just a Protocol subclass.
598
# TODO: Better way of representing the body for commands that take it,
599
# and allow it to be streamed into the server.
601
def __init__(self, backing_transport):
602
self._backing_transport = backing_transport
603
self._converted_command = False
604
self.finished_reading = False
605
self._body_bytes = ''
608
def accept_body(self, bytes):
611
This should be overriden for each command that desired body data to
612
handle the right format of that data. I.e. plain bytes, a bundle etc.
614
The deserialisation into that format should be done in the Protocol
615
object. Set self.desired_body_format to the format your method will
618
# default fallback is to accumulate bytes.
619
self._body_bytes += bytes
621
def _end_of_body_handler(self):
622
"""An unimplemented end of body handler."""
623
raise NotImplementedError(self._end_of_body_handler)
626
"""Answer a version request with my version."""
627
return SmartServerResponse(('ok', '1'))
629
def do_has(self, relpath):
630
r = self._backing_transport.has(relpath) and 'yes' or 'no'
631
return SmartServerResponse((r,))
633
def do_get(self, relpath):
634
backing_bytes = self._backing_transport.get_bytes(relpath)
635
return SmartServerResponse(('ok',), backing_bytes)
637
def _deserialise_optional_mode(self, mode):
638
# XXX: FIXME this should be on the protocol object.
644
def do_append(self, relpath, mode):
645
self._converted_command = True
646
self._relpath = relpath
647
self._mode = self._deserialise_optional_mode(mode)
648
self._end_of_body_handler = self._handle_do_append_end
650
def _handle_do_append_end(self):
651
old_length = self._backing_transport.append_bytes(
652
self._relpath, self._body_bytes, self._mode)
653
self.response = SmartServerResponse(('appended', '%d' % old_length))
655
def do_delete(self, relpath):
656
self._backing_transport.delete(relpath)
658
def do_iter_files_recursive(self, relpath):
659
transport = self._backing_transport.clone(relpath)
660
filenames = transport.iter_files_recursive()
661
return SmartServerResponse(('names',) + tuple(filenames))
663
def do_list_dir(self, relpath):
664
filenames = self._backing_transport.list_dir(relpath)
665
return SmartServerResponse(('names',) + tuple(filenames))
667
def do_mkdir(self, relpath, mode):
668
self._backing_transport.mkdir(relpath,
669
self._deserialise_optional_mode(mode))
671
def do_move(self, rel_from, rel_to):
672
self._backing_transport.move(rel_from, rel_to)
674
def do_put(self, relpath, mode):
675
self._converted_command = True
676
self._relpath = relpath
677
self._mode = self._deserialise_optional_mode(mode)
678
self._end_of_body_handler = self._handle_do_put
680
def _handle_do_put(self):
681
self._backing_transport.put_bytes(self._relpath,
682
self._body_bytes, self._mode)
683
self.response = SmartServerResponse(('ok',))
685
def _deserialise_offsets(self, text):
686
# XXX: FIXME this should be on the protocol object.
688
for line in text.split('\n'):
691
start, length = line.split(',')
692
offsets.append((int(start), int(length)))
695
def do_put_non_atomic(self, relpath, mode, create_parent, dir_mode):
696
self._converted_command = True
697
self._end_of_body_handler = self._handle_put_non_atomic
698
self._relpath = relpath
699
self._dir_mode = self._deserialise_optional_mode(dir_mode)
700
self._mode = self._deserialise_optional_mode(mode)
701
# a boolean would be nicer XXX
702
self._create_parent = (create_parent == 'T')
704
def _handle_put_non_atomic(self):
705
self._backing_transport.put_bytes_non_atomic(self._relpath,
708
create_parent_dir=self._create_parent,
709
dir_mode=self._dir_mode)
710
self.response = SmartServerResponse(('ok',))
712
def do_readv(self, relpath):
713
self._converted_command = True
714
self._end_of_body_handler = self._handle_readv_offsets
715
self._relpath = relpath
717
def end_of_body(self):
718
"""No more body data will be received."""
719
self._run_handler_code(self._end_of_body_handler, (), {})
720
# cannot read after this.
721
self.finished_reading = True
723
def _handle_readv_offsets(self):
724
"""accept offsets for a readv request."""
725
offsets = self._deserialise_offsets(self._body_bytes)
726
backing_bytes = ''.join(bytes for offset, bytes in
727
self._backing_transport.readv(self._relpath, offsets))
728
self.response = SmartServerResponse(('readv',), backing_bytes)
730
def do_rename(self, rel_from, rel_to):
731
self._backing_transport.rename(rel_from, rel_to)
733
def do_rmdir(self, relpath):
734
self._backing_transport.rmdir(relpath)
736
def do_stat(self, relpath):
737
stat = self._backing_transport.stat(relpath)
738
return SmartServerResponse(('stat', str(stat.st_size), oct(stat.st_mode)))
740
def do_get_bundle(self, path, revision_id):
741
# open transport relative to our base
742
t = self._backing_transport.clone(path)
743
control, extra_path = bzrdir.BzrDir.open_containing_from_transport(t)
744
repo = control.open_repository()
745
tmpf = tempfile.TemporaryFile()
746
base_revision = revision.NULL_REVISION
747
write_bundle(repo, revision_id, base_revision, tmpf)
749
return SmartServerResponse((), tmpf.read())
751
def dispatch_command(self, cmd, args):
752
"""Deprecated compatibility method.""" # XXX XXX
753
func = getattr(self, 'do_' + cmd, None)
755
raise errors.SmartProtocolError("bad request %r" % (cmd,))
756
self._run_handler_code(func, args, {})
758
def _run_handler_code(self, callable, args, kwargs):
759
"""Run some handler specific code 'callable'.
761
If a result is returned, it is considered to be the commands response,
762
and finished_reading is set true, and its assigned to self.response.
764
Any exceptions caught are translated and a response object created
767
result = self._call_converting_errors(callable, args, kwargs)
768
if result is not None:
769
self.response = result
770
self.finished_reading = True
771
# handle unconverted commands
772
if not self._converted_command:
773
self.finished_reading = True
775
self.response = SmartServerResponse(('ok',))
777
def _call_converting_errors(self, callable, args, kwargs):
778
"""Call callable converting errors to Response objects."""
780
return callable(*args, **kwargs)
781
except errors.NoSuchFile, e:
782
return SmartServerResponse(('NoSuchFile', e.path))
783
except errors.FileExists, e:
784
return SmartServerResponse(('FileExists', e.path))
785
except errors.DirectoryNotEmpty, e:
786
return SmartServerResponse(('DirectoryNotEmpty', e.path))
787
except errors.ShortReadvError, e:
788
return SmartServerResponse(('ShortReadvError',
789
e.path, str(e.offset), str(e.length), str(e.actual)))
790
except UnicodeError, e:
791
# If it is a DecodeError, than most likely we are starting
792
# with a plain string
793
str_or_unicode = e.object
794
if isinstance(str_or_unicode, unicode):
795
# XXX: UTF-8 might have \x01 (our seperator byte) in it. We
796
# should escape it somehow.
797
val = 'u:' + str_or_unicode.encode('utf-8')
799
val = 's:' + str_or_unicode.encode('base64')
800
# This handles UnicodeEncodeError or UnicodeDecodeError
801
return SmartServerResponse((e.__class__.__name__,
802
e.encoding, val, str(e.start), str(e.end), e.reason))
803
except errors.TransportNotPossible, e:
804
if e.msg == "readonly transport":
805
return SmartServerResponse(('ReadOnlyError', ))
810
class SmartTCPServer(object):
811
"""Listens on a TCP socket and accepts connections from smart clients"""
813
def __init__(self, backing_transport, host='127.0.0.1', port=0):
814
"""Construct a new server.
816
To actually start it running, call either start_background_thread or
819
:param host: Name of the interface to listen on.
820
:param port: TCP port to listen on, or 0 to allocate a transient port.
822
self._server_socket = socket.socket()
823
self._server_socket.bind((host, port))
824
self.port = self._server_socket.getsockname()[1]
825
self._server_socket.listen(1)
826
self._server_socket.settimeout(1)
827
self.backing_transport = backing_transport
830
# let connections timeout so that we get a chance to terminate
831
# Keep a reference to the exceptions we want to catch because the socket
832
# module's globals get set to None during interpreter shutdown.
833
from socket import timeout as socket_timeout
834
from socket import error as socket_error
835
self._should_terminate = False
836
while not self._should_terminate:
838
self.accept_and_serve()
839
except socket_timeout:
840
# just check if we're asked to stop
842
except socket_error, e:
843
trace.warning("client disconnected: %s", e)
847
"""Return the url of the server"""
848
return "bzr://%s:%d/" % self._server_socket.getsockname()
850
def accept_and_serve(self):
851
conn, client_addr = self._server_socket.accept()
852
# For WIN32, where the timeout value from the listening socket
853
# propogates to the newly accepted socket.
854
conn.setblocking(True)
855
conn.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
856
handler = SmartServerSocketStreamMedium(conn, self.backing_transport)
857
connection_thread = threading.Thread(None, handler.serve, name='smart-server-child')
858
connection_thread.setDaemon(True)
859
connection_thread.start()
861
def start_background_thread(self):
862
self._server_thread = threading.Thread(None,
864
name='server-' + self.get_url())
865
self._server_thread.setDaemon(True)
866
self._server_thread.start()
868
def stop_background_thread(self):
869
self._should_terminate = True
870
# self._server_socket.close()
871
# we used to join the thread, but it's not really necessary; it will
873
## self._server_thread.join()
876
class SmartTCPServer_for_testing(SmartTCPServer):
877
"""Server suitable for use by transport tests.
879
This server is backed by the process's cwd.
883
self._homedir = urlutils.local_path_to_url(os.getcwd())[7:]
884
# The server is set up by default like for ssh access: the client
885
# passes filesystem-absolute paths; therefore the server must look
886
# them up relative to the root directory. it might be better to act
887
# a public server and have the server rewrite paths into the test
889
SmartTCPServer.__init__(self,
890
transport.get_transport(urlutils.local_path_to_url('/')))
893
"""Set up server for testing"""
894
self.start_background_thread()
897
self.stop_background_thread()
900
"""Return the url of the server"""
901
host, port = self._server_socket.getsockname()
902
return "bzr://%s:%d%s" % (host, port, urlutils.escape(self._homedir))
904
def get_bogus_url(self):
905
"""Return a URL which will fail to connect"""
906
return 'bzr://127.0.0.1:1/'
909
class SmartStat(object):
42
# Port 4155 is the default port for bzr://, registered with IANA.
43
BZR_DEFAULT_INTERFACE = '0.0.0.0'
44
BZR_DEFAULT_PORT = 4155
47
class _SmartStat(object):
911
49
def __init__(self, size, mode):
912
50
self.st_size = size
913
51
self.st_mode = mode
916
class SmartTransport(transport.Transport):
54
class RemoteTransport(transport.Transport):
917
55
"""Connection to a smart server.
919
The connection holds references to pipes that can be used to send requests
57
The connection holds references to the medium that can be used to send
58
requests to the server.
922
60
The connection has a notion of the current directory to which it's
923
61
connected; this is incorporated in filenames passed to the server.
1269
419
self._translate_error(resp)
1272
class SmartClientMediumRequest(object):
1273
"""A request on a SmartClientMedium.
1275
Each request allows bytes to be provided to it via accept_bytes, and then
1276
the response bytes to be read via read_bytes.
1279
request.accept_bytes('123')
1280
request.finished_writing()
1281
result = request.read_bytes(3)
1282
request.finished_reading()
1284
It is up to the individual SmartClientMedium whether multiple concurrent
1285
requests can exist. See SmartClientMedium.get_request to obtain instances
1286
of SmartClientMediumRequest, and the concrete Medium you are using for
1287
details on concurrency and pipelining.
1290
def __init__(self, medium):
1291
"""Construct a SmartClientMediumRequest for the medium medium."""
1292
self._medium = medium
1293
# we track state by constants - we may want to use the same
1294
# pattern as BodyReader if it gets more complex.
1295
# valid states are: "writing", "reading", "done"
1296
self._state = "writing"
1298
def accept_bytes(self, bytes):
1299
"""Accept bytes for inclusion in this request.
1301
This method may not be be called after finished_writing() has been
1302
called. It depends upon the Medium whether or not the bytes will be
1303
immediately transmitted. Message based Mediums will tend to buffer the
1304
bytes until finished_writing() is called.
1306
:param bytes: A bytestring.
1308
if self._state != "writing":
1309
raise errors.WritingCompleted(self)
1310
self._accept_bytes(bytes)
1312
def _accept_bytes(self, bytes):
1313
"""Helper for accept_bytes.
1315
Accept_bytes checks the state of the request to determing if bytes
1316
should be accepted. After that it hands off to _accept_bytes to do the
1319
raise NotImplementedError(self._accept_bytes)
1321
def finished_reading(self):
1322
"""Inform the request that all desired data has been read.
1324
This will remove the request from the pipeline for its medium (if the
1325
medium supports pipelining) and any further calls to methods on the
1326
request will raise ReadingCompleted.
1328
if self._state == "writing":
1329
raise errors.WritingNotComplete(self)
1330
if self._state != "reading":
1331
raise errors.ReadingCompleted(self)
1332
self._state = "done"
1333
self._finished_reading()
1335
def _finished_reading(self):
1336
"""Helper for finished_reading.
1338
finished_reading checks the state of the request to determine if
1339
finished_reading is allowed, and if it is hands off to _finished_reading
1340
to perform the action.
1342
raise NotImplementedError(self._finished_reading)
1344
def finished_writing(self):
1345
"""Finish the writing phase of this request.
1347
This will flush all pending data for this request along the medium.
1348
After calling finished_writing, you may not call accept_bytes anymore.
1350
if self._state != "writing":
1351
raise errors.WritingCompleted(self)
1352
self._state = "reading"
1353
self._finished_writing()
1355
def _finished_writing(self):
1356
"""Helper for finished_writing.
1358
finished_writing checks the state of the request to determine if
1359
finished_writing is allowed, and if it is hands off to _finished_writing
1360
to perform the action.
1362
raise NotImplementedError(self._finished_writing)
1364
def read_bytes(self, count):
1365
"""Read bytes from this requests response.
1367
This method will block and wait for count bytes to be read. It may not
1368
be invoked until finished_writing() has been called - this is to ensure
1369
a message-based approach to requests, for compatability with message
1370
based mediums like HTTP.
1372
if self._state == "writing":
1373
raise errors.WritingNotComplete(self)
1374
if self._state != "reading":
1375
raise errors.ReadingCompleted(self)
1376
return self._read_bytes(count)
1378
def _read_bytes(self, count):
1379
"""Helper for read_bytes.
1381
read_bytes checks the state of the request to determing if bytes
1382
should be read. After that it hands off to _read_bytes to do the
1385
raise NotImplementedError(self._read_bytes)
1388
class SmartClientStreamMediumRequest(SmartClientMediumRequest):
1389
"""A SmartClientMediumRequest that works with an SmartClientStreamMedium."""
1391
def __init__(self, medium):
1392
SmartClientMediumRequest.__init__(self, medium)
1393
# check that we are safe concurrency wise. If some streams start
1394
# allowing concurrent requests - i.e. via multiplexing - then this
1395
# assert should be moved to SmartClientStreamMedium.get_request,
1396
# and the setting/unsetting of _current_request likewise moved into
1397
# that class : but its unneeded overhead for now. RBC 20060922
1398
if self._medium._current_request is not None:
1399
raise errors.TooManyConcurrentRequests(self._medium)
1400
self._medium._current_request = self
1402
def _accept_bytes(self, bytes):
1403
"""See SmartClientMediumRequest._accept_bytes.
1405
This forwards to self._medium._accept_bytes because we are operating
1406
on the mediums stream.
1408
self._medium._accept_bytes(bytes)
1410
def _finished_reading(self):
1411
"""See SmartClientMediumRequest._finished_reading.
1413
This clears the _current_request on self._medium to allow a new
1414
request to be created.
1416
assert self._medium._current_request is self
1417
self._medium._current_request = None
1419
def _finished_writing(self):
1420
"""See SmartClientMediumRequest._finished_writing.
1422
This invokes self._medium._flush to ensure all bytes are transmitted.
1424
self._medium._flush()
1426
def _read_bytes(self, count):
1427
"""See SmartClientMediumRequest._read_bytes.
1429
This forwards to self._medium._read_bytes because we are operating
1430
on the mediums stream.
1432
return self._medium._read_bytes(count)
1435
class SmartClientRequestProtocolOne(SmartProtocolBase):
1436
"""The client-side protocol for smart version 1."""
1438
def __init__(self, request):
1439
"""Construct a SmartClientRequestProtocolOne.
1441
:param request: A SmartClientMediumRequest to serialise onto and
1444
self._request = request
1445
self._body_buffer = None
1447
def call(self, *args):
1448
bytes = _encode_tuple(args)
1449
self._request.accept_bytes(bytes)
1450
self._request.finished_writing()
1452
def call_with_body_bytes(self, args, body):
1453
"""Make a remote call of args with body bytes 'body'.
1455
After calling this, call read_response_tuple to find the result out.
1457
bytes = _encode_tuple(args)
1458
self._request.accept_bytes(bytes)
1459
bytes = self._encode_bulk_data(body)
1460
self._request.accept_bytes(bytes)
1461
self._request.finished_writing()
1463
def call_with_body_readv_array(self, args, body):
1464
"""Make a remote call with a readv array.
1466
The body is encoded with one line per readv offset pair. The numbers in
1467
each pair are separated by a comma, and no trailing \n is emitted.
1469
bytes = _encode_tuple(args)
1470
self._request.accept_bytes(bytes)
1471
readv_bytes = self._serialise_offsets(body)
1472
bytes = self._encode_bulk_data(readv_bytes)
1473
self._request.accept_bytes(bytes)
1474
self._request.finished_writing()
1476
def cancel_read_body(self):
1477
"""After expecting a body, a response code may indicate one otherwise.
1479
This method lets the domain client inform the protocol that no body
1480
will be transmitted. This is a terminal method: after calling it the
1481
protocol is not able to be used further.
1483
self._request.finished_reading()
1485
def read_response_tuple(self, expect_body=False):
1486
"""Read a response tuple from the wire.
1488
This should only be called once.
1490
result = self._recv_tuple()
1492
self._request.finished_reading()
1495
def read_body_bytes(self, count=-1):
1496
"""Read bytes from the body, decoding into a byte stream.
1498
We read all bytes at once to ensure we've checked the trailer for
1499
errors, and then feed the buffer back as read_body_bytes is called.
1501
if self._body_buffer is not None:
1502
return self._body_buffer.read(count)
1503
_body_decoder = LengthPrefixedBodyDecoder()
1505
while not _body_decoder.finished_reading:
1506
bytes_wanted = _body_decoder.next_read_size()
1507
bytes = self._request.read_bytes(bytes_wanted)
1508
_body_decoder.accept_bytes(bytes)
1509
self._request.finished_reading()
1510
self._body_buffer = StringIO(_body_decoder.read_pending_data())
1511
# XXX: TODO check the trailer result.
1512
return self._body_buffer.read(count)
1514
def _recv_tuple(self):
1515
"""Receive a tuple from the medium request."""
1517
while not line or line[-1] != '\n':
1518
# TODO: this is inefficient - but tuples are short.
1519
new_char = self._request.read_bytes(1)
1521
assert new_char != '', "end of file reading from server."
1522
return _decode_tuple(line)
1524
def query_version(self):
1525
"""Return protocol version number of the server."""
1527
resp = self.read_response_tuple()
1528
if resp == ('ok', '1'):
1531
raise errors.SmartProtocolError("bad response %r" % (resp,))
1534
class SmartClientMedium(object):
1535
"""Smart client is a medium for sending smart protocol requests over."""
1537
def disconnect(self):
1538
"""If this medium maintains a persistent connection, close it.
1540
The default implementation does nothing.
1544
class SmartClientStreamMedium(SmartClientMedium):
1545
"""Stream based medium common class.
1547
SmartClientStreamMediums operate on a stream. All subclasses use a common
1548
SmartClientStreamMediumRequest for their requests, and should implement
1549
_accept_bytes and _read_bytes to allow the request objects to send and
1554
self._current_request = None
1556
def accept_bytes(self, bytes):
1557
self._accept_bytes(bytes)
1560
"""The SmartClientStreamMedium knows how to close the stream when it is
1566
"""Flush the output stream.
1568
This method is used by the SmartClientStreamMediumRequest to ensure that
1569
all data for a request is sent, to avoid long timeouts or deadlocks.
1571
raise NotImplementedError(self._flush)
1573
def get_request(self):
1574
"""See SmartClientMedium.get_request().
1576
SmartClientStreamMedium always returns a SmartClientStreamMediumRequest
1579
return SmartClientStreamMediumRequest(self)
1581
def read_bytes(self, count):
1582
return self._read_bytes(count)
1585
class SmartSimplePipesClientMedium(SmartClientStreamMedium):
1586
"""A client medium using simple pipes.
1588
This client does not manage the pipes: it assumes they will always be open.
1591
def __init__(self, readable_pipe, writeable_pipe):
1592
SmartClientStreamMedium.__init__(self)
1593
self._readable_pipe = readable_pipe
1594
self._writeable_pipe = writeable_pipe
1596
def _accept_bytes(self, bytes):
1597
"""See SmartClientStreamMedium.accept_bytes."""
1598
self._writeable_pipe.write(bytes)
1601
"""See SmartClientStreamMedium._flush()."""
1602
self._writeable_pipe.flush()
1604
def _read_bytes(self, count):
1605
"""See SmartClientStreamMedium._read_bytes."""
1606
return self._readable_pipe.read(count)
1609
class SmartSSHClientMedium(SmartClientStreamMedium):
1610
"""A client medium using SSH."""
1612
def __init__(self, host, port=None, username=None, password=None,
1614
"""Creates a client that will connect on the first use.
1616
:param vendor: An optional override for the ssh vendor to use. See
1617
bzrlib.transport.ssh for details on ssh vendors.
1619
SmartClientStreamMedium.__init__(self)
1620
self._connected = False
1622
self._password = password
1624
self._username = username
1625
self._read_from = None
1626
self._ssh_connection = None
1627
self._vendor = vendor
1628
self._write_to = None
1630
def _accept_bytes(self, bytes):
1631
"""See SmartClientStreamMedium.accept_bytes."""
1632
self._ensure_connection()
1633
self._write_to.write(bytes)
1635
def disconnect(self):
1636
"""See SmartClientMedium.disconnect()."""
1637
if not self._connected:
1639
self._read_from.close()
1640
self._write_to.close()
1641
self._ssh_connection.close()
1642
self._connected = False
1644
def _ensure_connection(self):
1645
"""Connect this medium if not already connected."""
1648
executable = os.environ.get('BZR_REMOTE_PATH', 'bzr')
1649
if self._vendor is None:
1650
vendor = ssh._get_ssh_vendor()
1652
vendor = self._vendor
1653
self._ssh_connection = vendor.connect_ssh(self._username,
1654
self._password, self._host, self._port,
1655
command=[executable, 'serve', '--inet', '--directory=/',
1657
self._read_from, self._write_to = \
1658
self._ssh_connection.get_filelike_channels()
1659
self._connected = True
1662
"""See SmartClientStreamMedium._flush()."""
1663
self._write_to.flush()
1665
def _read_bytes(self, count):
1666
"""See SmartClientStreamMedium.read_bytes."""
1667
if not self._connected:
1668
raise errors.MediumNotConnected(self)
1669
return self._read_from.read(count)
1672
class SmartTCPClientMedium(SmartClientStreamMedium):
1673
"""A client medium using TCP."""
1675
def __init__(self, host, port):
1676
"""Creates a client that will connect on the first use."""
1677
SmartClientStreamMedium.__init__(self)
1678
self._connected = False
1683
def _accept_bytes(self, bytes):
1684
"""See SmartClientMedium.accept_bytes."""
1685
self._ensure_connection()
1686
self._socket.sendall(bytes)
1688
def disconnect(self):
1689
"""See SmartClientMedium.disconnect()."""
1690
if not self._connected:
1692
self._socket.close()
1694
self._connected = False
1696
def _ensure_connection(self):
1697
"""Connect this medium if not already connected."""
1700
self._socket = socket.socket()
1701
self._socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
1702
result = self._socket.connect_ex((self._host, int(self._port)))
1704
raise errors.ConnectionError("failed to connect to %s:%d: %s" %
1705
(self._host, self._port, os.strerror(result)))
1706
self._connected = True
1709
"""See SmartClientStreamMedium._flush().
1711
For TCP we do no flushing. We may want to turn off TCP_NODELAY and
1712
add a means to do a flush, but that can be done in the future.
1715
def _read_bytes(self, count):
1716
"""See SmartClientMedium.read_bytes."""
1717
if not self._connected:
1718
raise errors.MediumNotConnected(self)
1719
return self._socket.recv(count)
1722
class SmartTCPTransport(SmartTransport):
422
class RemoteTCPTransport(RemoteTransport):
1723
423
"""Connection to smart server over plain tcp.
1725
425
This is essentially just a factory to get 'RemoteTransport(url,