~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/smart/medium.py

merge merge tweaks from aaron, which includes latest .dev

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2006 Canonical Ltd
2
 
#
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.
7
 
#
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.
12
 
#
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
16
 
 
17
 
"""The 'medium' layer for the smart servers and clients.
18
 
 
19
 
"Medium" here is the noun meaning "a means of transmission", not the adjective
20
 
for "the quality between big and small."
21
 
 
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.
25
 
"""
26
 
 
27
 
import os
28
 
import socket
29
 
import sys
30
 
import urllib
31
 
 
32
 
from bzrlib import (
33
 
    errors,
34
 
    osutils,
35
 
    symbol_versioning,
36
 
    urlutils,
37
 
    )
38
 
from bzrlib.smart.protocol import (
39
 
    MESSAGE_VERSION_THREE,
40
 
    REQUEST_VERSION_TWO,
41
 
    SmartClientRequestProtocolOne,
42
 
    SmartServerRequestProtocolOne,
43
 
    SmartServerRequestProtocolTwo,
44
 
    build_server_protocol_three
45
 
    )
46
 
from bzrlib.transport import ssh
47
 
 
48
 
 
49
 
def _get_protocol_factory_for_bytes(bytes):
50
 
    """Determine the right protocol factory for 'bytes'.
51
 
 
52
 
    This will return an appropriate protocol factory depending on the version
53
 
    of the protocol being used, as determined by inspecting the given bytes.
54
 
    The bytes should have at least one newline byte (i.e. be a whole line),
55
 
    otherwise it's possible that a request will be incorrectly identified as
56
 
    version 1.
57
 
 
58
 
    Typical use would be::
59
 
 
60
 
         factory, unused_bytes = _get_protocol_factory_for_bytes(bytes)
61
 
         server_protocol = factory(transport, write_func, root_client_path)
62
 
         server_protocol.accept_bytes(unused_bytes)
63
 
 
64
 
    :param bytes: a str of bytes of the start of the request.
65
 
    :returns: 2-tuple of (protocol_factory, unused_bytes).  protocol_factory is
66
 
        a callable that takes three args: transport, write_func,
67
 
        root_client_path.  unused_bytes are any bytes that were not part of a
68
 
        protocol version marker.
69
 
    """
70
 
    if bytes.startswith(MESSAGE_VERSION_THREE):
71
 
        protocol_factory = build_server_protocol_three
72
 
        bytes = bytes[len(MESSAGE_VERSION_THREE):]
73
 
    elif bytes.startswith(REQUEST_VERSION_TWO):
74
 
        protocol_factory = SmartServerRequestProtocolTwo
75
 
        bytes = bytes[len(REQUEST_VERSION_TWO):]
76
 
    else:
77
 
        protocol_factory = SmartServerRequestProtocolOne
78
 
    return protocol_factory, bytes
79
 
 
80
 
 
81
 
class SmartServerStreamMedium(object):
82
 
    """Handles smart commands coming over a stream.
83
 
 
84
 
    The stream may be a pipe connected to sshd, or a tcp socket, or an
85
 
    in-process fifo for testing.
86
 
 
87
 
    One instance is created for each connected client; it can serve multiple
88
 
    requests in the lifetime of the connection.
89
 
 
90
 
    The server passes requests through to an underlying backing transport, 
91
 
    which will typically be a LocalTransport looking at the server's filesystem.
92
 
 
93
 
    :ivar _push_back_buffer: a str of bytes that have been read from the stream
94
 
        but not used yet, or None if there are no buffered bytes.  Subclasses
95
 
        should make sure to exhaust this buffer before reading more bytes from
96
 
        the stream.  See also the _push_back method.
97
 
    """
98
 
 
99
 
    def __init__(self, backing_transport, root_client_path='/'):
100
 
        """Construct new server.
101
 
 
102
 
        :param backing_transport: Transport for the directory served.
103
 
        """
104
 
        # backing_transport could be passed to serve instead of __init__
105
 
        self.backing_transport = backing_transport
106
 
        self.root_client_path = root_client_path
107
 
        self.finished = False
108
 
        self._push_back_buffer = None
109
 
 
110
 
    def _push_back(self, bytes):
111
 
        """Return unused bytes to the medium, because they belong to the next
112
 
        request(s).
113
 
 
114
 
        This sets the _push_back_buffer to the given bytes.
115
 
        """
116
 
        if self._push_back_buffer is not None:
117
 
            raise AssertionError(
118
 
                "_push_back called when self._push_back_buffer is %r"
119
 
                % (self._push_back_buffer,))
120
 
        if bytes == '':
121
 
            return
122
 
        self._push_back_buffer = bytes
123
 
 
124
 
    def _get_push_back_buffer(self):
125
 
        if self._push_back_buffer == '':
126
 
            raise AssertionError(
127
 
                '%s._push_back_buffer should never be the empty string, '
128
 
                'which can be confused with EOF' % (self,))
129
 
        bytes = self._push_back_buffer
130
 
        self._push_back_buffer = None
131
 
        return bytes
132
 
 
133
 
    def serve(self):
134
 
        """Serve requests until the client disconnects."""
135
 
        # Keep a reference to stderr because the sys module's globals get set to
136
 
        # None during interpreter shutdown.
137
 
        from sys import stderr
138
 
        try:
139
 
            while not self.finished:
140
 
                server_protocol = self._build_protocol()
141
 
                self._serve_one_request(server_protocol)
142
 
        except Exception, e:
143
 
            stderr.write("%s terminating on exception %s\n" % (self, e))
144
 
            raise
145
 
 
146
 
    def _build_protocol(self):
147
 
        """Identifies the version of the incoming request, and returns an
148
 
        a protocol object that can interpret it.
149
 
 
150
 
        If more bytes than the version prefix of the request are read, they will
151
 
        be fed into the protocol before it is returned.
152
 
 
153
 
        :returns: a SmartServerRequestProtocol.
154
 
        """
155
 
        bytes = self._get_line()
156
 
        protocol_factory, unused_bytes = _get_protocol_factory_for_bytes(bytes)
157
 
        protocol = protocol_factory(
158
 
            self.backing_transport, self._write_out, self.root_client_path)
159
 
        protocol.accept_bytes(unused_bytes)
160
 
        return protocol
161
 
 
162
 
    def _serve_one_request(self, protocol):
163
 
        """Read one request from input, process, send back a response.
164
 
        
165
 
        :param protocol: a SmartServerRequestProtocol.
166
 
        """
167
 
        try:
168
 
            self._serve_one_request_unguarded(protocol)
169
 
        except KeyboardInterrupt:
170
 
            raise
171
 
        except Exception, e:
172
 
            self.terminate_due_to_error()
173
 
 
174
 
    def terminate_due_to_error(self):
175
 
        """Called when an unhandled exception from the protocol occurs."""
176
 
        raise NotImplementedError(self.terminate_due_to_error)
177
 
 
178
 
    def _get_bytes(self, desired_count):
179
 
        """Get some bytes from the medium.
180
 
 
181
 
        :param desired_count: number of bytes we want to read.
182
 
        """
183
 
        raise NotImplementedError(self._get_bytes)
184
 
 
185
 
    def _get_line(self):
186
 
        """Read bytes from this request's response until a newline byte.
187
 
        
188
 
        This isn't particularly efficient, so should only be used when the
189
 
        expected size of the line is quite short.
190
 
 
191
 
        :returns: a string of bytes ending in a newline (byte 0x0A).
192
 
        """
193
 
        newline_pos = -1
194
 
        bytes = ''
195
 
        while newline_pos == -1:
196
 
            new_bytes = self._get_bytes(1)
197
 
            bytes += new_bytes
198
 
            if new_bytes == '':
199
 
                # Ran out of bytes before receiving a complete line.
200
 
                return bytes
201
 
            newline_pos = bytes.find('\n')
202
 
        line = bytes[:newline_pos+1]
203
 
        self._push_back(bytes[newline_pos+1:])
204
 
        return line
205
 
 
206
 
 
207
 
class SmartServerSocketStreamMedium(SmartServerStreamMedium):
208
 
 
209
 
    def __init__(self, sock, backing_transport, root_client_path='/'):
210
 
        """Constructor.
211
 
 
212
 
        :param sock: the socket the server will read from.  It will be put
213
 
            into blocking mode.
214
 
        """
215
 
        SmartServerStreamMedium.__init__(
216
 
            self, backing_transport, root_client_path=root_client_path)
217
 
        sock.setblocking(True)
218
 
        self.socket = sock
219
 
 
220
 
    def _serve_one_request_unguarded(self, protocol):
221
 
        while protocol.next_read_size():
222
 
            bytes = self._get_bytes(4096)
223
 
            if bytes == '':
224
 
                self.finished = True
225
 
                return
226
 
            protocol.accept_bytes(bytes)
227
 
        
228
 
        self._push_back(protocol.unused_data)
229
 
 
230
 
    def _get_bytes(self, desired_count):
231
 
        if self._push_back_buffer is not None:
232
 
            return self._get_push_back_buffer()
233
 
        # We ignore the desired_count because on sockets it's more efficient to
234
 
        # read 4k at a time.
235
 
        return self.socket.recv(4096)
236
 
    
237
 
    def terminate_due_to_error(self):
238
 
        # TODO: This should log to a server log file, but no such thing
239
 
        # exists yet.  Andrew Bennetts 2006-09-29.
240
 
        self.socket.close()
241
 
        self.finished = True
242
 
 
243
 
    def _write_out(self, bytes):
244
 
        osutils.send_all(self.socket, bytes)
245
 
 
246
 
 
247
 
class SmartServerPipeStreamMedium(SmartServerStreamMedium):
248
 
 
249
 
    def __init__(self, in_file, out_file, backing_transport):
250
 
        """Construct new server.
251
 
 
252
 
        :param in_file: Python file from which requests can be read.
253
 
        :param out_file: Python file to write responses.
254
 
        :param backing_transport: Transport for the directory served.
255
 
        """
256
 
        SmartServerStreamMedium.__init__(self, backing_transport)
257
 
        if sys.platform == 'win32':
258
 
            # force binary mode for files
259
 
            import msvcrt
260
 
            for f in (in_file, out_file):
261
 
                fileno = getattr(f, 'fileno', None)
262
 
                if fileno:
263
 
                    msvcrt.setmode(fileno(), os.O_BINARY)
264
 
        self._in = in_file
265
 
        self._out = out_file
266
 
 
267
 
    def _serve_one_request_unguarded(self, protocol):
268
 
        while True:
269
 
            bytes_to_read = protocol.next_read_size()
270
 
            if bytes_to_read == 0:
271
 
                # Finished serving this request.
272
 
                self._out.flush()
273
 
                return
274
 
            bytes = self._get_bytes(bytes_to_read)
275
 
            if bytes == '':
276
 
                # Connection has been closed.
277
 
                self.finished = True
278
 
                self._out.flush()
279
 
                return
280
 
            protocol.accept_bytes(bytes)
281
 
 
282
 
    def _get_bytes(self, desired_count):
283
 
        if self._push_back_buffer is not None:
284
 
            return self._get_push_back_buffer()
285
 
        return self._in.read(desired_count)
286
 
 
287
 
    def terminate_due_to_error(self):
288
 
        # TODO: This should log to a server log file, but no such thing
289
 
        # exists yet.  Andrew Bennetts 2006-09-29.
290
 
        self._out.close()
291
 
        self.finished = True
292
 
 
293
 
    def _write_out(self, bytes):
294
 
        self._out.write(bytes)
295
 
 
296
 
 
297
 
class SmartClientMediumRequest(object):
298
 
    """A request on a SmartClientMedium.
299
 
 
300
 
    Each request allows bytes to be provided to it via accept_bytes, and then
301
 
    the response bytes to be read via read_bytes.
302
 
 
303
 
    For instance:
304
 
    request.accept_bytes('123')
305
 
    request.finished_writing()
306
 
    result = request.read_bytes(3)
307
 
    request.finished_reading()
308
 
 
309
 
    It is up to the individual SmartClientMedium whether multiple concurrent
310
 
    requests can exist. See SmartClientMedium.get_request to obtain instances 
311
 
    of SmartClientMediumRequest, and the concrete Medium you are using for 
312
 
    details on concurrency and pipelining.
313
 
    """
314
 
 
315
 
    def __init__(self, medium):
316
 
        """Construct a SmartClientMediumRequest for the medium medium."""
317
 
        self._medium = medium
318
 
        # we track state by constants - we may want to use the same
319
 
        # pattern as BodyReader if it gets more complex.
320
 
        # valid states are: "writing", "reading", "done"
321
 
        self._state = "writing"
322
 
 
323
 
    def accept_bytes(self, bytes):
324
 
        """Accept bytes for inclusion in this request.
325
 
 
326
 
        This method may not be be called after finished_writing() has been
327
 
        called.  It depends upon the Medium whether or not the bytes will be
328
 
        immediately transmitted. Message based Mediums will tend to buffer the
329
 
        bytes until finished_writing() is called.
330
 
 
331
 
        :param bytes: A bytestring.
332
 
        """
333
 
        if self._state != "writing":
334
 
            raise errors.WritingCompleted(self)
335
 
        self._accept_bytes(bytes)
336
 
 
337
 
    def _accept_bytes(self, bytes):
338
 
        """Helper for accept_bytes.
339
 
 
340
 
        Accept_bytes checks the state of the request to determing if bytes
341
 
        should be accepted. After that it hands off to _accept_bytes to do the
342
 
        actual acceptance.
343
 
        """
344
 
        raise NotImplementedError(self._accept_bytes)
345
 
 
346
 
    def finished_reading(self):
347
 
        """Inform the request that all desired data has been read.
348
 
 
349
 
        This will remove the request from the pipeline for its medium (if the
350
 
        medium supports pipelining) and any further calls to methods on the
351
 
        request will raise ReadingCompleted.
352
 
        """
353
 
        if self._state == "writing":
354
 
            raise errors.WritingNotComplete(self)
355
 
        if self._state != "reading":
356
 
            raise errors.ReadingCompleted(self)
357
 
        self._state = "done"
358
 
        self._finished_reading()
359
 
 
360
 
    def _finished_reading(self):
361
 
        """Helper for finished_reading.
362
 
 
363
 
        finished_reading checks the state of the request to determine if 
364
 
        finished_reading is allowed, and if it is hands off to _finished_reading
365
 
        to perform the action.
366
 
        """
367
 
        raise NotImplementedError(self._finished_reading)
368
 
 
369
 
    def finished_writing(self):
370
 
        """Finish the writing phase of this request.
371
 
 
372
 
        This will flush all pending data for this request along the medium.
373
 
        After calling finished_writing, you may not call accept_bytes anymore.
374
 
        """
375
 
        if self._state != "writing":
376
 
            raise errors.WritingCompleted(self)
377
 
        self._state = "reading"
378
 
        self._finished_writing()
379
 
 
380
 
    def _finished_writing(self):
381
 
        """Helper for finished_writing.
382
 
 
383
 
        finished_writing checks the state of the request to determine if 
384
 
        finished_writing is allowed, and if it is hands off to _finished_writing
385
 
        to perform the action.
386
 
        """
387
 
        raise NotImplementedError(self._finished_writing)
388
 
 
389
 
    def read_bytes(self, count):
390
 
        """Read bytes from this requests response.
391
 
 
392
 
        This method will block and wait for count bytes to be read. It may not
393
 
        be invoked until finished_writing() has been called - this is to ensure
394
 
        a message-based approach to requests, for compatibility with message
395
 
        based mediums like HTTP.
396
 
        """
397
 
        if self._state == "writing":
398
 
            raise errors.WritingNotComplete(self)
399
 
        if self._state != "reading":
400
 
            raise errors.ReadingCompleted(self)
401
 
        return self._read_bytes(count)
402
 
 
403
 
    def _read_bytes(self, count):
404
 
        """Helper for read_bytes.
405
 
 
406
 
        read_bytes checks the state of the request to determing if bytes
407
 
        should be read. After that it hands off to _read_bytes to do the
408
 
        actual read.
409
 
        """
410
 
        raise NotImplementedError(self._read_bytes)
411
 
 
412
 
    def read_line(self):
413
 
        """Read bytes from this request's response until a newline byte.
414
 
        
415
 
        This isn't particularly efficient, so should only be used when the
416
 
        expected size of the line is quite short.
417
 
 
418
 
        :returns: a string of bytes ending in a newline (byte 0x0A).
419
 
        """
420
 
        # XXX: this duplicates SmartClientRequestProtocolOne._recv_tuple
421
 
        line = ''
422
 
        while not line or line[-1] != '\n':
423
 
            new_char = self.read_bytes(1)
424
 
            line += new_char
425
 
            if new_char == '':
426
 
                # end of file encountered reading from server
427
 
                raise errors.ConnectionReset(
428
 
                    "please check connectivity and permissions",
429
 
                    "(and try -Dhpss if further diagnosis is required)")
430
 
        return line
431
 
 
432
 
 
433
 
class SmartClientMedium(object):
434
 
    """Smart client is a medium for sending smart protocol requests over."""
435
 
 
436
 
    def __init__(self, base):
437
 
        super(SmartClientMedium, self).__init__()
438
 
        self.base = base
439
 
        self._protocol_version_error = None
440
 
        self._protocol_version = None
441
 
        self._done_hello = False
442
 
        # Be optimistic: we assume the remote end can accept new remote
443
 
        # requests until we get an error saying otherwise.  (1.2 adds some
444
 
        # requests that send bodies, which confuses older servers.)
445
 
        self._remote_is_at_least_1_2 = True
446
 
 
447
 
    def protocol_version(self):
448
 
        """Find out if 'hello' smart request works."""
449
 
        if self._protocol_version_error is not None:
450
 
            raise self._protocol_version_error
451
 
        if not self._done_hello:
452
 
            try:
453
 
                medium_request = self.get_request()
454
 
                # Send a 'hello' request in protocol version one, for maximum
455
 
                # backwards compatibility.
456
 
                client_protocol = SmartClientRequestProtocolOne(medium_request)
457
 
                client_protocol.query_version()
458
 
                self._done_hello = True
459
 
            except errors.SmartProtocolError, e:
460
 
                # Cache the error, just like we would cache a successful
461
 
                # result.
462
 
                self._protocol_version_error = e
463
 
                raise
464
 
        return '2'
465
 
 
466
 
    def should_probe(self):
467
 
        """Should RemoteBzrDirFormat.probe_transport send a smart request on
468
 
        this medium?
469
 
 
470
 
        Some transports are unambiguously smart-only; there's no need to check
471
 
        if the transport is able to carry smart requests, because that's all
472
 
        it is for.  In those cases, this method should return False.
473
 
 
474
 
        But some HTTP transports can sometimes fail to carry smart requests,
475
 
        but still be usuable for accessing remote bzrdirs via plain file
476
 
        accesses.  So for those transports, their media should return True here
477
 
        so that RemoteBzrDirFormat can determine if it is appropriate for that
478
 
        transport.
479
 
        """
480
 
        return False
481
 
 
482
 
    def disconnect(self):
483
 
        """If this medium maintains a persistent connection, close it.
484
 
        
485
 
        The default implementation does nothing.
486
 
        """
487
 
        
488
 
    def remote_path_from_transport(self, transport):
489
 
        """Convert transport into a path suitable for using in a request.
490
 
        
491
 
        Note that the resulting remote path doesn't encode the host name or
492
 
        anything but path, so it is only safe to use it in requests sent over
493
 
        the medium from the matching transport.
494
 
        """
495
 
        medium_base = urlutils.join(self.base, '/')
496
 
        rel_url = urlutils.relative_url(medium_base, transport.base)
497
 
        return urllib.unquote(rel_url)
498
 
 
499
 
 
500
 
class SmartClientStreamMedium(SmartClientMedium):
501
 
    """Stream based medium common class.
502
 
 
503
 
    SmartClientStreamMediums operate on a stream. All subclasses use a common
504
 
    SmartClientStreamMediumRequest for their requests, and should implement
505
 
    _accept_bytes and _read_bytes to allow the request objects to send and
506
 
    receive bytes.
507
 
    """
508
 
 
509
 
    def __init__(self, base):
510
 
        SmartClientMedium.__init__(self, base)
511
 
        self._current_request = None
512
 
 
513
 
    def accept_bytes(self, bytes):
514
 
        self._accept_bytes(bytes)
515
 
 
516
 
    def __del__(self):
517
 
        """The SmartClientStreamMedium knows how to close the stream when it is
518
 
        finished with it.
519
 
        """
520
 
        self.disconnect()
521
 
 
522
 
    def _flush(self):
523
 
        """Flush the output stream.
524
 
        
525
 
        This method is used by the SmartClientStreamMediumRequest to ensure that
526
 
        all data for a request is sent, to avoid long timeouts or deadlocks.
527
 
        """
528
 
        raise NotImplementedError(self._flush)
529
 
 
530
 
    def get_request(self):
531
 
        """See SmartClientMedium.get_request().
532
 
 
533
 
        SmartClientStreamMedium always returns a SmartClientStreamMediumRequest
534
 
        for get_request.
535
 
        """
536
 
        return SmartClientStreamMediumRequest(self)
537
 
 
538
 
    def read_bytes(self, count):
539
 
        return self._read_bytes(count)
540
 
 
541
 
 
542
 
class SmartSimplePipesClientMedium(SmartClientStreamMedium):
543
 
    """A client medium using simple pipes.
544
 
    
545
 
    This client does not manage the pipes: it assumes they will always be open.
546
 
    """
547
 
 
548
 
    def __init__(self, readable_pipe, writeable_pipe, base):
549
 
        SmartClientStreamMedium.__init__(self, base)
550
 
        self._readable_pipe = readable_pipe
551
 
        self._writeable_pipe = writeable_pipe
552
 
 
553
 
    def _accept_bytes(self, bytes):
554
 
        """See SmartClientStreamMedium.accept_bytes."""
555
 
        self._writeable_pipe.write(bytes)
556
 
 
557
 
    def _flush(self):
558
 
        """See SmartClientStreamMedium._flush()."""
559
 
        self._writeable_pipe.flush()
560
 
 
561
 
    def _read_bytes(self, count):
562
 
        """See SmartClientStreamMedium._read_bytes."""
563
 
        return self._readable_pipe.read(count)
564
 
 
565
 
 
566
 
class SmartSSHClientMedium(SmartClientStreamMedium):
567
 
    """A client medium using SSH."""
568
 
    
569
 
    def __init__(self, host, port=None, username=None, password=None,
570
 
            base=None, vendor=None, bzr_remote_path=None):
571
 
        """Creates a client that will connect on the first use.
572
 
        
573
 
        :param vendor: An optional override for the ssh vendor to use. See
574
 
            bzrlib.transport.ssh for details on ssh vendors.
575
 
        """
576
 
        SmartClientStreamMedium.__init__(self, base)
577
 
        self._connected = False
578
 
        self._host = host
579
 
        self._password = password
580
 
        self._port = port
581
 
        self._username = username
582
 
        self._read_from = None
583
 
        self._ssh_connection = None
584
 
        self._vendor = vendor
585
 
        self._write_to = None
586
 
        self._bzr_remote_path = bzr_remote_path
587
 
        if self._bzr_remote_path is None:
588
 
            symbol_versioning.warn(
589
 
                'bzr_remote_path is required as of bzr 0.92',
590
 
                DeprecationWarning, stacklevel=2)
591
 
            self._bzr_remote_path = os.environ.get('BZR_REMOTE_PATH', 'bzr')
592
 
 
593
 
    def _accept_bytes(self, bytes):
594
 
        """See SmartClientStreamMedium.accept_bytes."""
595
 
        self._ensure_connection()
596
 
        self._write_to.write(bytes)
597
 
 
598
 
    def disconnect(self):
599
 
        """See SmartClientMedium.disconnect()."""
600
 
        if not self._connected:
601
 
            return
602
 
        self._read_from.close()
603
 
        self._write_to.close()
604
 
        self._ssh_connection.close()
605
 
        self._connected = False
606
 
 
607
 
    def _ensure_connection(self):
608
 
        """Connect this medium if not already connected."""
609
 
        if self._connected:
610
 
            return
611
 
        if self._vendor is None:
612
 
            vendor = ssh._get_ssh_vendor()
613
 
        else:
614
 
            vendor = self._vendor
615
 
        self._ssh_connection = vendor.connect_ssh(self._username,
616
 
                self._password, self._host, self._port,
617
 
                command=[self._bzr_remote_path, 'serve', '--inet',
618
 
                         '--directory=/', '--allow-writes'])
619
 
        self._read_from, self._write_to = \
620
 
            self._ssh_connection.get_filelike_channels()
621
 
        self._connected = True
622
 
 
623
 
    def _flush(self):
624
 
        """See SmartClientStreamMedium._flush()."""
625
 
        self._write_to.flush()
626
 
 
627
 
    def _read_bytes(self, count):
628
 
        """See SmartClientStreamMedium.read_bytes."""
629
 
        if not self._connected:
630
 
            raise errors.MediumNotConnected(self)
631
 
        return self._read_from.read(count)
632
 
 
633
 
 
634
 
# Port 4155 is the default port for bzr://, registered with IANA.
635
 
BZR_DEFAULT_INTERFACE = '0.0.0.0'
636
 
BZR_DEFAULT_PORT = 4155
637
 
 
638
 
 
639
 
class SmartTCPClientMedium(SmartClientStreamMedium):
640
 
    """A client medium using TCP."""
641
 
    
642
 
    def __init__(self, host, port, base):
643
 
        """Creates a client that will connect on the first use."""
644
 
        SmartClientStreamMedium.__init__(self, base)
645
 
        self._connected = False
646
 
        self._host = host
647
 
        self._port = port
648
 
        self._socket = None
649
 
 
650
 
    def _accept_bytes(self, bytes):
651
 
        """See SmartClientMedium.accept_bytes."""
652
 
        self._ensure_connection()
653
 
        osutils.send_all(self._socket, bytes)
654
 
 
655
 
    def disconnect(self):
656
 
        """See SmartClientMedium.disconnect()."""
657
 
        if not self._connected:
658
 
            return
659
 
        self._socket.close()
660
 
        self._socket = None
661
 
        self._connected = False
662
 
 
663
 
    def _ensure_connection(self):
664
 
        """Connect this medium if not already connected."""
665
 
        if self._connected:
666
 
            return
667
 
        self._socket = socket.socket()
668
 
        self._socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
669
 
        if self._port is None:
670
 
            port = BZR_DEFAULT_PORT
671
 
        else:
672
 
            port = int(self._port)
673
 
        try:
674
 
            self._socket.connect((self._host, port))
675
 
        except socket.error, err:
676
 
            # socket errors either have a (string) or (errno, string) as their
677
 
            # args.
678
 
            if type(err.args) is str:
679
 
                err_msg = err.args
680
 
            else:
681
 
                err_msg = err.args[1]
682
 
            raise errors.ConnectionError("failed to connect to %s:%d: %s" %
683
 
                    (self._host, port, err_msg))
684
 
        self._connected = True
685
 
 
686
 
    def _flush(self):
687
 
        """See SmartClientStreamMedium._flush().
688
 
        
689
 
        For TCP we do no flushing. We may want to turn off TCP_NODELAY and 
690
 
        add a means to do a flush, but that can be done in the future.
691
 
        """
692
 
 
693
 
    def _read_bytes(self, count):
694
 
        """See SmartClientMedium.read_bytes."""
695
 
        if not self._connected:
696
 
            raise errors.MediumNotConnected(self)
697
 
        return self._socket.recv(count)
698
 
 
699
 
 
700
 
class SmartClientStreamMediumRequest(SmartClientMediumRequest):
701
 
    """A SmartClientMediumRequest that works with an SmartClientStreamMedium."""
702
 
 
703
 
    def __init__(self, medium):
704
 
        SmartClientMediumRequest.__init__(self, medium)
705
 
        # check that we are safe concurrency wise. If some streams start
706
 
        # allowing concurrent requests - i.e. via multiplexing - then this
707
 
        # assert should be moved to SmartClientStreamMedium.get_request,
708
 
        # and the setting/unsetting of _current_request likewise moved into
709
 
        # that class : but its unneeded overhead for now. RBC 20060922
710
 
        if self._medium._current_request is not None:
711
 
            raise errors.TooManyConcurrentRequests(self._medium)
712
 
        self._medium._current_request = self
713
 
 
714
 
    def _accept_bytes(self, bytes):
715
 
        """See SmartClientMediumRequest._accept_bytes.
716
 
        
717
 
        This forwards to self._medium._accept_bytes because we are operating
718
 
        on the mediums stream.
719
 
        """
720
 
        self._medium._accept_bytes(bytes)
721
 
 
722
 
    def _finished_reading(self):
723
 
        """See SmartClientMediumRequest._finished_reading.
724
 
 
725
 
        This clears the _current_request on self._medium to allow a new 
726
 
        request to be created.
727
 
        """
728
 
        if self._medium._current_request is not self:
729
 
            raise AssertionError()
730
 
        self._medium._current_request = None
731
 
        
732
 
    def _finished_writing(self):
733
 
        """See SmartClientMediumRequest._finished_writing.
734
 
 
735
 
        This invokes self._medium._flush to ensure all bytes are transmitted.
736
 
        """
737
 
        self._medium._flush()
738
 
 
739
 
    def _read_bytes(self, count):
740
 
        """See SmartClientMediumRequest._read_bytes.
741
 
        
742
 
        This forwards to self._medium._read_bytes because we are operating
743
 
        on the mediums stream.
744
 
        """
745
 
        return self._medium._read_bytes(count)
746