~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/smart/medium.py

  • Committer: Vincent Ladeuil
  • Date: 2009-06-22 12:52:39 UTC
  • mto: (4471.1.1 integration)
  • mto: This revision was merged to the branch mainline in revision 4472.
  • Revision ID: v.ladeuil+lp@free.fr-20090622125239-kabo9smxt9c3vnir
Use a consistent scheme for naming pyrex source files.

Show diffs side-by-side

added added

removed removed

Lines of Context:
12
12
#
13
13
# You should have received a copy of the GNU General Public License
14
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
 
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
16
16
 
17
17
"""The 'medium' layer for the smart servers and clients.
18
18
 
24
24
bzrlib/transport/smart/__init__.py.
25
25
"""
26
26
 
 
27
import errno
27
28
import os
28
29
import socket
29
30
import sys
30
31
import urllib
31
32
 
 
33
from bzrlib.lazy_import import lazy_import
 
34
lazy_import(globals(), """
 
35
import atexit
 
36
import weakref
32
37
from bzrlib import (
 
38
    debug,
33
39
    errors,
34
40
    osutils,
35
41
    symbol_versioning,
 
42
    trace,
 
43
    ui,
36
44
    urlutils,
37
45
    )
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.smart import client, protocol, request, vfs
46
47
from bzrlib.transport import ssh
 
48
""")
 
49
 
 
50
 
 
51
# We must not read any more than 64k at a time so we don't risk "no buffer
 
52
# space available" errors on some platforms.  Windows in particular is likely
 
53
# to give error 10053 or 10055 if we read more than 64k from a socket.
 
54
_MAX_READ_SIZE = 64 * 1024
47
55
 
48
56
 
49
57
def _get_protocol_factory_for_bytes(bytes):
67
75
        root_client_path.  unused_bytes are any bytes that were not part of a
68
76
        protocol version marker.
69
77
    """
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):]
 
78
    if bytes.startswith(protocol.MESSAGE_VERSION_THREE):
 
79
        protocol_factory = protocol.build_server_protocol_three
 
80
        bytes = bytes[len(protocol.MESSAGE_VERSION_THREE):]
 
81
    elif bytes.startswith(protocol.REQUEST_VERSION_TWO):
 
82
        protocol_factory = protocol.SmartServerRequestProtocolTwo
 
83
        bytes = bytes[len(protocol.REQUEST_VERSION_TWO):]
76
84
    else:
77
 
        protocol_factory = SmartServerRequestProtocolOne
 
85
        protocol_factory = protocol.SmartServerRequestProtocolOne
78
86
    return protocol_factory, bytes
79
87
 
80
88
 
81
 
class SmartServerStreamMedium(object):
 
89
def _get_line(read_bytes_func):
 
90
    """Read bytes using read_bytes_func until a newline byte.
 
91
 
 
92
    This isn't particularly efficient, so should only be used when the
 
93
    expected size of the line is quite short.
 
94
 
 
95
    :returns: a tuple of two strs: (line, excess)
 
96
    """
 
97
    newline_pos = -1
 
98
    bytes = ''
 
99
    while newline_pos == -1:
 
100
        new_bytes = read_bytes_func(1)
 
101
        bytes += new_bytes
 
102
        if new_bytes == '':
 
103
            # Ran out of bytes before receiving a complete line.
 
104
            return bytes, ''
 
105
        newline_pos = bytes.find('\n')
 
106
    line = bytes[:newline_pos+1]
 
107
    excess = bytes[newline_pos+1:]
 
108
    return line, excess
 
109
 
 
110
 
 
111
class SmartMedium(object):
 
112
    """Base class for smart protocol media, both client- and server-side."""
 
113
 
 
114
    def __init__(self):
 
115
        self._push_back_buffer = None
 
116
 
 
117
    def _push_back(self, bytes):
 
118
        """Return unused bytes to the medium, because they belong to the next
 
119
        request(s).
 
120
 
 
121
        This sets the _push_back_buffer to the given bytes.
 
122
        """
 
123
        if self._push_back_buffer is not None:
 
124
            raise AssertionError(
 
125
                "_push_back called when self._push_back_buffer is %r"
 
126
                % (self._push_back_buffer,))
 
127
        if bytes == '':
 
128
            return
 
129
        self._push_back_buffer = bytes
 
130
 
 
131
    def _get_push_back_buffer(self):
 
132
        if self._push_back_buffer == '':
 
133
            raise AssertionError(
 
134
                '%s._push_back_buffer should never be the empty string, '
 
135
                'which can be confused with EOF' % (self,))
 
136
        bytes = self._push_back_buffer
 
137
        self._push_back_buffer = None
 
138
        return bytes
 
139
 
 
140
    def read_bytes(self, desired_count):
 
141
        """Read some bytes from this medium.
 
142
 
 
143
        :returns: some bytes, possibly more or less than the number requested
 
144
            in 'desired_count' depending on the medium.
 
145
        """
 
146
        if self._push_back_buffer is not None:
 
147
            return self._get_push_back_buffer()
 
148
        bytes_to_read = min(desired_count, _MAX_READ_SIZE)
 
149
        return self._read_bytes(bytes_to_read)
 
150
 
 
151
    def _read_bytes(self, count):
 
152
        raise NotImplementedError(self._read_bytes)
 
153
 
 
154
    def _get_line(self):
 
155
        """Read bytes from this request's response until a newline byte.
 
156
 
 
157
        This isn't particularly efficient, so should only be used when the
 
158
        expected size of the line is quite short.
 
159
 
 
160
        :returns: a string of bytes ending in a newline (byte 0x0A).
 
161
        """
 
162
        line, excess = _get_line(self.read_bytes)
 
163
        self._push_back(excess)
 
164
        return line
 
165
 
 
166
    def _report_activity(self, bytes, direction):
 
167
        """Notify that this medium has activity.
 
168
 
 
169
        Implementations should call this from all methods that actually do IO.
 
170
        Be careful that it's not called twice, if one method is implemented on
 
171
        top of another.
 
172
 
 
173
        :param bytes: Number of bytes read or written.
 
174
        :param direction: 'read' or 'write' or None.
 
175
        """
 
176
        ui.ui_factory.report_transport_activity(self, bytes, direction)
 
177
 
 
178
 
 
179
class SmartServerStreamMedium(SmartMedium):
82
180
    """Handles smart commands coming over a stream.
83
181
 
84
182
    The stream may be a pipe connected to sshd, or a tcp socket, or an
87
185
    One instance is created for each connected client; it can serve multiple
88
186
    requests in the lifetime of the connection.
89
187
 
90
 
    The server passes requests through to an underlying backing transport, 
 
188
    The server passes requests through to an underlying backing transport,
91
189
    which will typically be a LocalTransport looking at the server's filesystem.
92
190
 
93
191
    :ivar _push_back_buffer: a str of bytes that have been read from the stream
105
203
        self.backing_transport = backing_transport
106
204
        self.root_client_path = root_client_path
107
205
        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
 
206
        SmartMedium.__init__(self)
132
207
 
133
208
    def serve(self):
134
209
        """Serve requests until the client disconnects."""
161
236
 
162
237
    def _serve_one_request(self, protocol):
163
238
        """Read one request from input, process, send back a response.
164
 
        
 
239
 
165
240
        :param protocol: a SmartServerRequestProtocol.
166
241
        """
167
242
        try:
175
250
        """Called when an unhandled exception from the protocol occurs."""
176
251
        raise NotImplementedError(self.terminate_due_to_error)
177
252
 
178
 
    def _get_bytes(self, desired_count):
 
253
    def _read_bytes(self, desired_count):
179
254
        """Get some bytes from the medium.
180
255
 
181
256
        :param desired_count: number of bytes we want to read.
182
257
        """
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
 
 
 
258
        raise NotImplementedError(self._read_bytes)
 
259
 
206
260
 
207
261
class SmartServerSocketStreamMedium(SmartServerStreamMedium):
208
262
 
219
273
 
220
274
    def _serve_one_request_unguarded(self, protocol):
221
275
        while protocol.next_read_size():
222
 
            bytes = self._get_bytes(4096)
 
276
            # We can safely try to read large chunks.  If there is less data
 
277
            # than _MAX_READ_SIZE ready, the socket wil just return a short
 
278
            # read immediately rather than block.
 
279
            bytes = self.read_bytes(_MAX_READ_SIZE)
223
280
            if bytes == '':
224
281
                self.finished = True
225
282
                return
226
283
            protocol.accept_bytes(bytes)
227
 
        
 
284
 
228
285
        self._push_back(protocol.unused_data)
229
286
 
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
 
    
 
287
    def _read_bytes(self, desired_count):
 
288
        return _read_bytes_from_socket(
 
289
            self.socket.recv, desired_count, self._report_activity)
 
290
 
237
291
    def terminate_due_to_error(self):
238
292
        # TODO: This should log to a server log file, but no such thing
239
293
        # exists yet.  Andrew Bennetts 2006-09-29.
241
295
        self.finished = True
242
296
 
243
297
    def _write_out(self, bytes):
244
 
        osutils.send_all(self.socket, bytes)
 
298
        osutils.send_all(self.socket, bytes, self._report_activity)
245
299
 
246
300
 
247
301
class SmartServerPipeStreamMedium(SmartServerStreamMedium):
266
320
 
267
321
    def _serve_one_request_unguarded(self, protocol):
268
322
        while True:
 
323
            # We need to be careful not to read past the end of the current
 
324
            # request, or else the read from the pipe will block, so we use
 
325
            # protocol.next_read_size().
269
326
            bytes_to_read = protocol.next_read_size()
270
327
            if bytes_to_read == 0:
271
328
                # Finished serving this request.
272
329
                self._out.flush()
273
330
                return
274
 
            bytes = self._get_bytes(bytes_to_read)
 
331
            bytes = self.read_bytes(bytes_to_read)
275
332
            if bytes == '':
276
333
                # Connection has been closed.
277
334
                self.finished = True
279
336
                return
280
337
            protocol.accept_bytes(bytes)
281
338
 
282
 
    def _get_bytes(self, desired_count):
283
 
        if self._push_back_buffer is not None:
284
 
            return self._get_push_back_buffer()
 
339
    def _read_bytes(self, desired_count):
285
340
        return self._in.read(desired_count)
286
341
 
287
342
    def terminate_due_to_error(self):
307
362
    request.finished_reading()
308
363
 
309
364
    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 
 
365
    requests can exist. See SmartClientMedium.get_request to obtain instances
 
366
    of SmartClientMediumRequest, and the concrete Medium you are using for
312
367
    details on concurrency and pipelining.
313
368
    """
314
369
 
323
378
    def accept_bytes(self, bytes):
324
379
        """Accept bytes for inclusion in this request.
325
380
 
326
 
        This method may not be be called after finished_writing() has been
 
381
        This method may not be called after finished_writing() has been
327
382
        called.  It depends upon the Medium whether or not the bytes will be
328
383
        immediately transmitted. Message based Mediums will tend to buffer the
329
384
        bytes until finished_writing() is called.
360
415
    def _finished_reading(self):
361
416
        """Helper for finished_reading.
362
417
 
363
 
        finished_reading checks the state of the request to determine if 
 
418
        finished_reading checks the state of the request to determine if
364
419
        finished_reading is allowed, and if it is hands off to _finished_reading
365
420
        to perform the action.
366
421
        """
380
435
    def _finished_writing(self):
381
436
        """Helper for finished_writing.
382
437
 
383
 
        finished_writing checks the state of the request to determine if 
 
438
        finished_writing checks the state of the request to determine if
384
439
        finished_writing is allowed, and if it is hands off to _finished_writing
385
440
        to perform the action.
386
441
        """
401
456
        return self._read_bytes(count)
402
457
 
403
458
    def _read_bytes(self, count):
404
 
        """Helper for read_bytes.
 
459
        """Helper for SmartClientMediumRequest.read_bytes.
405
460
 
406
461
        read_bytes checks the state of the request to determing if bytes
407
462
        should be read. After that it hands off to _read_bytes to do the
408
463
        actual read.
 
464
 
 
465
        By default this forwards to self._medium.read_bytes because we are
 
466
        operating on the medium's stream.
409
467
        """
410
 
        raise NotImplementedError(self._read_bytes)
 
468
        return self._medium.read_bytes(count)
411
469
 
412
470
    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)")
 
471
        line = self._read_line()
 
472
        if not line.endswith('\n'):
 
473
            # end of file encountered reading from server
 
474
            raise errors.ConnectionReset(
 
475
                "please check connectivity and permissions")
430
476
        return line
431
477
 
432
 
 
433
 
class SmartClientMedium(object):
 
478
    def _read_line(self):
 
479
        """Helper for SmartClientMediumRequest.read_line.
 
480
 
 
481
        By default this forwards to self._medium._get_line because we are
 
482
        operating on the medium's stream.
 
483
        """
 
484
        return self._medium._get_line()
 
485
 
 
486
 
 
487
class _DebugCounter(object):
 
488
    """An object that counts the HPSS calls made to each client medium.
 
489
 
 
490
    When a medium is garbage-collected, or failing that when atexit functions
 
491
    are run, the total number of calls made on that medium are reported via
 
492
    trace.note.
 
493
    """
 
494
 
 
495
    def __init__(self):
 
496
        self.counts = weakref.WeakKeyDictionary()
 
497
        client._SmartClient.hooks.install_named_hook(
 
498
            'call', self.increment_call_count, 'hpss call counter')
 
499
        atexit.register(self.flush_all)
 
500
 
 
501
    def track(self, medium):
 
502
        """Start tracking calls made to a medium.
 
503
 
 
504
        This only keeps a weakref to the medium, so shouldn't affect the
 
505
        medium's lifetime.
 
506
        """
 
507
        medium_repr = repr(medium)
 
508
        # Add this medium to the WeakKeyDictionary
 
509
        self.counts[medium] = dict(count=0, vfs_count=0,
 
510
                                   medium_repr=medium_repr)
 
511
        # Weakref callbacks are fired in reverse order of their association
 
512
        # with the referenced object.  So we add a weakref *after* adding to
 
513
        # the WeakKeyDict so that we can report the value from it before the
 
514
        # entry is removed by the WeakKeyDict's own callback.
 
515
        ref = weakref.ref(medium, self.done)
 
516
 
 
517
    def increment_call_count(self, params):
 
518
        # Increment the count in the WeakKeyDictionary
 
519
        value = self.counts[params.medium]
 
520
        value['count'] += 1
 
521
        request_method = request.request_handlers.get(params.method)
 
522
        if issubclass(request_method, vfs.VfsRequest):
 
523
            value['vfs_count'] += 1
 
524
 
 
525
    def done(self, ref):
 
526
        value = self.counts[ref]
 
527
        count, vfs_count, medium_repr = (
 
528
            value['count'], value['vfs_count'], value['medium_repr'])
 
529
        # In case this callback is invoked for the same ref twice (by the
 
530
        # weakref callback and by the atexit function), set the call count back
 
531
        # to 0 so this item won't be reported twice.
 
532
        value['count'] = 0
 
533
        value['vfs_count'] = 0
 
534
        if count != 0:
 
535
            trace.note('HPSS calls: %d (%d vfs) %s',
 
536
                       count, vfs_count, medium_repr)
 
537
 
 
538
    def flush_all(self):
 
539
        for ref in list(self.counts.keys()):
 
540
            self.done(ref)
 
541
 
 
542
_debug_counter = None
 
543
 
 
544
 
 
545
class SmartClientMedium(SmartMedium):
434
546
    """Smart client is a medium for sending smart protocol requests over."""
435
547
 
436
548
    def __init__(self, base):
439
551
        self._protocol_version_error = None
440
552
        self._protocol_version = None
441
553
        self._done_hello = False
 
554
        # Be optimistic: we assume the remote end can accept new remote
 
555
        # requests until we get an error saying otherwise.
 
556
        # _remote_version_is_before tracks the bzr version the remote side
 
557
        # can be based on what we've seen so far.
 
558
        self._remote_version_is_before = None
 
559
        # Install debug hook function if debug flag is set.
 
560
        if 'hpss' in debug.debug_flags:
 
561
            global _debug_counter
 
562
            if _debug_counter is None:
 
563
                _debug_counter = _DebugCounter()
 
564
            _debug_counter.track(self)
 
565
 
 
566
    def _is_remote_before(self, version_tuple):
 
567
        """Is it possible the remote side supports RPCs for a given version?
 
568
 
 
569
        Typical use::
 
570
 
 
571
            needed_version = (1, 2)
 
572
            if medium._is_remote_before(needed_version):
 
573
                fallback_to_pre_1_2_rpc()
 
574
            else:
 
575
                try:
 
576
                    do_1_2_rpc()
 
577
                except UnknownSmartMethod:
 
578
                    medium._remember_remote_is_before(needed_version)
 
579
                    fallback_to_pre_1_2_rpc()
 
580
 
 
581
        :seealso: _remember_remote_is_before
 
582
        """
 
583
        if self._remote_version_is_before is None:
 
584
            # So far, the remote side seems to support everything
 
585
            return False
 
586
        return version_tuple >= self._remote_version_is_before
 
587
 
 
588
    def _remember_remote_is_before(self, version_tuple):
 
589
        """Tell this medium that the remote side is older the given version.
 
590
 
 
591
        :seealso: _is_remote_before
 
592
        """
 
593
        if (self._remote_version_is_before is not None and
 
594
            version_tuple > self._remote_version_is_before):
 
595
            # We have been told that the remote side is older than some version
 
596
            # which is newer than a previously supplied older-than version.
 
597
            # This indicates that some smart verb call is not guarded
 
598
            # appropriately (it should simply not have been tried).
 
599
            raise AssertionError(
 
600
                "_remember_remote_is_before(%r) called, but "
 
601
                "_remember_remote_is_before(%r) was called previously."
 
602
                % (version_tuple, self._remote_version_is_before))
 
603
        self._remote_version_is_before = version_tuple
442
604
 
443
605
    def protocol_version(self):
444
606
        """Find out if 'hello' smart request works."""
449
611
                medium_request = self.get_request()
450
612
                # Send a 'hello' request in protocol version one, for maximum
451
613
                # backwards compatibility.
452
 
                client_protocol = SmartClientRequestProtocolOne(medium_request)
 
614
                client_protocol = protocol.SmartClientRequestProtocolOne(medium_request)
453
615
                client_protocol.query_version()
454
616
                self._done_hello = True
455
617
            except errors.SmartProtocolError, e:
477
639
 
478
640
    def disconnect(self):
479
641
        """If this medium maintains a persistent connection, close it.
480
 
        
 
642
 
481
643
        The default implementation does nothing.
482
644
        """
483
 
        
 
645
 
484
646
    def remote_path_from_transport(self, transport):
485
647
        """Convert transport into a path suitable for using in a request.
486
 
        
 
648
 
487
649
        Note that the resulting remote path doesn't encode the host name or
488
650
        anything but path, so it is only safe to use it in requests sent over
489
651
        the medium from the matching transport.
505
667
    def __init__(self, base):
506
668
        SmartClientMedium.__init__(self, base)
507
669
        self._current_request = None
508
 
        # Be optimistic: we assume the remote end can accept new remote
509
 
        # requests until we get an error saying otherwise.  (1.2 adds some
510
 
        # requests that send bodies, which confuses older servers.)
511
 
        self._remote_is_at_least_1_2 = True
512
670
 
513
671
    def accept_bytes(self, bytes):
514
672
        self._accept_bytes(bytes)
521
679
 
522
680
    def _flush(self):
523
681
        """Flush the output stream.
524
 
        
 
682
 
525
683
        This method is used by the SmartClientStreamMediumRequest to ensure that
526
684
        all data for a request is sent, to avoid long timeouts or deadlocks.
527
685
        """
535
693
        """
536
694
        return SmartClientStreamMediumRequest(self)
537
695
 
538
 
    def read_bytes(self, count):
539
 
        return self._read_bytes(count)
540
 
 
541
696
 
542
697
class SmartSimplePipesClientMedium(SmartClientStreamMedium):
543
698
    """A client medium using simple pipes.
544
 
    
 
699
 
545
700
    This client does not manage the pipes: it assumes they will always be open.
546
701
    """
547
702
 
553
708
    def _accept_bytes(self, bytes):
554
709
        """See SmartClientStreamMedium.accept_bytes."""
555
710
        self._writeable_pipe.write(bytes)
 
711
        self._report_activity(len(bytes), 'write')
556
712
 
557
713
    def _flush(self):
558
714
        """See SmartClientStreamMedium._flush()."""
560
716
 
561
717
    def _read_bytes(self, count):
562
718
        """See SmartClientStreamMedium._read_bytes."""
563
 
        return self._readable_pipe.read(count)
 
719
        bytes = self._readable_pipe.read(count)
 
720
        self._report_activity(len(bytes), 'read')
 
721
        return bytes
564
722
 
565
723
 
566
724
class SmartSSHClientMedium(SmartClientStreamMedium):
567
725
    """A client medium using SSH."""
568
 
    
 
726
 
569
727
    def __init__(self, host, port=None, username=None, password=None,
570
728
            base=None, vendor=None, bzr_remote_path=None):
571
729
        """Creates a client that will connect on the first use.
572
 
        
 
730
 
573
731
        :param vendor: An optional override for the ssh vendor to use. See
574
732
            bzrlib.transport.ssh for details on ssh vendors.
575
733
        """
576
 
        SmartClientStreamMedium.__init__(self, base)
577
734
        self._connected = False
578
735
        self._host = host
579
736
        self._password = password
580
737
        self._port = port
581
738
        self._username = username
 
739
        # SmartClientStreamMedium stores the repr of this object in its
 
740
        # _DebugCounter so we have to store all the values used in our repr
 
741
        # method before calling the super init.
 
742
        SmartClientStreamMedium.__init__(self, base)
582
743
        self._read_from = None
583
744
        self._ssh_connection = None
584
745
        self._vendor = vendor
585
746
        self._write_to = None
586
747
        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')
 
748
        # for the benefit of progress making a short description of this
 
749
        # transport
 
750
        self._scheme = 'bzr+ssh'
 
751
 
 
752
    def __repr__(self):
 
753
        return "%s(connected=%r, username=%r, host=%r, port=%r)" % (
 
754
            self.__class__.__name__,
 
755
            self._connected,
 
756
            self._username,
 
757
            self._host,
 
758
            self._port)
592
759
 
593
760
    def _accept_bytes(self, bytes):
594
761
        """See SmartClientStreamMedium.accept_bytes."""
595
762
        self._ensure_connection()
596
763
        self._write_to.write(bytes)
 
764
        self._report_activity(len(bytes), 'write')
597
765
 
598
766
    def disconnect(self):
599
767
        """See SmartClientMedium.disconnect()."""
628
796
        """See SmartClientStreamMedium.read_bytes."""
629
797
        if not self._connected:
630
798
            raise errors.MediumNotConnected(self)
631
 
        return self._read_from.read(count)
 
799
        bytes_to_read = min(count, _MAX_READ_SIZE)
 
800
        bytes = self._read_from.read(bytes_to_read)
 
801
        self._report_activity(len(bytes), 'read')
 
802
        return bytes
632
803
 
633
804
 
634
805
# Port 4155 is the default port for bzr://, registered with IANA.
635
 
BZR_DEFAULT_INTERFACE = '0.0.0.0'
 
806
BZR_DEFAULT_INTERFACE = None
636
807
BZR_DEFAULT_PORT = 4155
637
808
 
638
809
 
639
810
class SmartTCPClientMedium(SmartClientStreamMedium):
640
811
    """A client medium using TCP."""
641
 
    
 
812
 
642
813
    def __init__(self, host, port, base):
643
814
        """Creates a client that will connect on the first use."""
644
815
        SmartClientStreamMedium.__init__(self, base)
650
821
    def _accept_bytes(self, bytes):
651
822
        """See SmartClientMedium.accept_bytes."""
652
823
        self._ensure_connection()
653
 
        osutils.send_all(self._socket, bytes)
 
824
        osutils.send_all(self._socket, bytes, self._report_activity)
654
825
 
655
826
    def disconnect(self):
656
827
        """See SmartClientMedium.disconnect()."""
664
835
        """Connect this medium if not already connected."""
665
836
        if self._connected:
666
837
            return
667
 
        self._socket = socket.socket()
668
 
        self._socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
669
838
        if self._port is None:
670
839
            port = BZR_DEFAULT_PORT
671
840
        else:
672
841
            port = int(self._port)
673
842
        try:
674
 
            self._socket.connect((self._host, port))
675
 
        except socket.error, err:
 
843
            sockaddrs = socket.getaddrinfo(self._host, port, socket.AF_UNSPEC,
 
844
                socket.SOCK_STREAM, 0, 0)
 
845
        except socket.gaierror, (err_num, err_msg):
 
846
            raise errors.ConnectionError("failed to lookup %s:%d: %s" %
 
847
                    (self._host, port, err_msg))
 
848
        # Initialize err in case there are no addresses returned:
 
849
        err = socket.error("no address found for %s" % self._host)
 
850
        for (family, socktype, proto, canonname, sockaddr) in sockaddrs:
 
851
            try:
 
852
                self._socket = socket.socket(family, socktype, proto)
 
853
                self._socket.setsockopt(socket.IPPROTO_TCP,
 
854
                                        socket.TCP_NODELAY, 1)
 
855
                self._socket.connect(sockaddr)
 
856
            except socket.error, err:
 
857
                if self._socket is not None:
 
858
                    self._socket.close()
 
859
                self._socket = None
 
860
                continue
 
861
            break
 
862
        if self._socket is None:
676
863
            # socket errors either have a (string) or (errno, string) as their
677
864
            # args.
678
865
            if type(err.args) is str:
685
872
 
686
873
    def _flush(self):
687
874
        """See SmartClientStreamMedium._flush().
688
 
        
689
 
        For TCP we do no flushing. We may want to turn off TCP_NODELAY and 
 
875
 
 
876
        For TCP we do no flushing. We may want to turn off TCP_NODELAY and
690
877
        add a means to do a flush, but that can be done in the future.
691
878
        """
692
879
 
694
881
        """See SmartClientMedium.read_bytes."""
695
882
        if not self._connected:
696
883
            raise errors.MediumNotConnected(self)
697
 
        return self._socket.recv(count)
 
884
        return _read_bytes_from_socket(
 
885
            self._socket.recv, count, self._report_activity)
698
886
 
699
887
 
700
888
class SmartClientStreamMediumRequest(SmartClientMediumRequest):
713
901
 
714
902
    def _accept_bytes(self, bytes):
715
903
        """See SmartClientMediumRequest._accept_bytes.
716
 
        
 
904
 
717
905
        This forwards to self._medium._accept_bytes because we are operating
718
906
        on the mediums stream.
719
907
        """
722
910
    def _finished_reading(self):
723
911
        """See SmartClientMediumRequest._finished_reading.
724
912
 
725
 
        This clears the _current_request on self._medium to allow a new 
 
913
        This clears the _current_request on self._medium to allow a new
726
914
        request to be created.
727
915
        """
728
916
        if self._medium._current_request is not self:
729
917
            raise AssertionError()
730
918
        self._medium._current_request = None
731
 
        
 
919
 
732
920
    def _finished_writing(self):
733
921
        """See SmartClientMediumRequest._finished_writing.
734
922
 
736
924
        """
737
925
        self._medium._flush()
738
926
 
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)
 
927
 
 
928
def _read_bytes_from_socket(sock, desired_count, report_activity):
 
929
    # We ignore the desired_count because on sockets it's more efficient to
 
930
    # read large chunks (of _MAX_READ_SIZE bytes) at a time.
 
931
    try:
 
932
        bytes = osutils.until_no_eintr(sock, _MAX_READ_SIZE)
 
933
    except socket.error, e:
 
934
        if len(e.args) and e.args[0] in (errno.ECONNRESET, 10054):
 
935
            # The connection was closed by the other side.  Callers expect an
 
936
            # empty string to signal end-of-stream.
 
937
            bytes = ''
 
938
        else:
 
939
            raise
 
940
    else:
 
941
        report_activity(len(bytes), 'read')
 
942
    return bytes
746
943