/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
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
2018.5.19 by Andrew Bennetts
Add docstrings to all the new modules, and a few other places.
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
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
27
import os
28
import socket
2018.5.162 by Andrew Bennetts
Add some missing _ensure_real calls, and a missing import.
29
import sys
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
30
1551.18.17 by Aaron Bentley
Introduce bzr_remote_path configuration variable
31
from bzrlib import (
32
    errors,
3118.2.1 by Andrew Bennetts
(andrew) Fix #115781 by passing no more than 64k at a time to socket.sendall.
33
    osutils,
1551.18.17 by Aaron Bentley
Introduce bzr_remote_path configuration variable
34
    symbol_versioning,
35
    )
2432.2.2 by Andrew Bennetts
Smart server mediums now detect which protocol version a request is and dispatch accordingly.
36
from bzrlib.smart.protocol import (
2432.2.7 by Andrew Bennetts
Use less confusing version strings, and define REQUEST_VERSION_TWO/RESPONSE_VERSION_TWO constants for them.
37
    REQUEST_VERSION_TWO,
3241.1.1 by Andrew Bennetts
Shift protocol version querying from RemoteBzrDirFormat into SmartClientMedium.
38
    SmartClientRequestProtocolOne,
2432.2.2 by Andrew Bennetts
Smart server mediums now detect which protocol version a request is and dispatch accordingly.
39
    SmartServerRequestProtocolOne,
40
    SmartServerRequestProtocolTwo,
41
    )
3066.2.1 by John Arbash Meinel
We don't require paramiko for bzr+ssh.
42
from bzrlib.transport import ssh
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
43
2018.5.17 by Andrew Bennetts
Paramaterise the commands handled by SmartServerRequestHandler.
44
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
45
class SmartServerStreamMedium(object):
46
    """Handles smart commands coming over a stream.
47
48
    The stream may be a pipe connected to sshd, or a tcp socket, or an
49
    in-process fifo for testing.
50
51
    One instance is created for each connected client; it can serve multiple
52
    requests in the lifetime of the connection.
53
54
    The server passes requests through to an underlying backing transport, 
55
    which will typically be a LocalTransport looking at the server's filesystem.
56
    """
57
58
    def __init__(self, backing_transport):
59
        """Construct new server.
60
61
        :param backing_transport: Transport for the directory served.
62
        """
63
        # backing_transport could be passed to serve instead of __init__
64
        self.backing_transport = backing_transport
65
        self.finished = False
66
67
    def serve(self):
68
        """Serve requests until the client disconnects."""
69
        # Keep a reference to stderr because the sys module's globals get set to
70
        # None during interpreter shutdown.
71
        from sys import stderr
72
        try:
73
            while not self.finished:
2432.2.3 by Andrew Bennetts
Merge from bzr.dev.
74
                server_protocol = self._build_protocol()
2018.5.14 by Andrew Bennetts
Move SmartTCPServer to smart/server.py, and SmartServerRequestHandler to smart/request.py.
75
                self._serve_one_request(server_protocol)
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
76
        except Exception, e:
77
            stderr.write("%s terminating on exception %s\n" % (self, e))
78
            raise
79
2432.2.2 by Andrew Bennetts
Smart server mediums now detect which protocol version a request is and dispatch accordingly.
80
    def _build_protocol(self):
2432.2.8 by Andrew Bennetts
NEWS entry, greatly improved docstring in bzrlib.smart.
81
        """Identifies the version of the incoming request, and returns an
82
        a protocol object that can interpret it.
83
84
        If more bytes than the version prefix of the request are read, they will
85
        be fed into the protocol before it is returned.
86
87
        :returns: a SmartServerRequestProtocol.
88
        """
2432.2.2 by Andrew Bennetts
Smart server mediums now detect which protocol version a request is and dispatch accordingly.
89
        # Identify the protocol version.
2432.2.7 by Andrew Bennetts
Use less confusing version strings, and define REQUEST_VERSION_TWO/RESPONSE_VERSION_TWO constants for them.
90
        bytes = self._get_line()
91
        if bytes.startswith(REQUEST_VERSION_TWO):
2432.2.2 by Andrew Bennetts
Smart server mediums now detect which protocol version a request is and dispatch accordingly.
92
            protocol_class = SmartServerRequestProtocolTwo
2432.2.7 by Andrew Bennetts
Use less confusing version strings, and define REQUEST_VERSION_TWO/RESPONSE_VERSION_TWO constants for them.
93
            bytes = bytes[len(REQUEST_VERSION_TWO):]
2432.2.2 by Andrew Bennetts
Smart server mediums now detect which protocol version a request is and dispatch accordingly.
94
        else:
95
            protocol_class = SmartServerRequestProtocolOne
96
        protocol = protocol_class(self.backing_transport, self._write_out)
97
        protocol.accept_bytes(bytes)
98
        return protocol
99
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
100
    def _serve_one_request(self, protocol):
101
        """Read one request from input, process, send back a response.
102
        
103
        :param protocol: a SmartServerRequestProtocol.
104
        """
105
        try:
106
            self._serve_one_request_unguarded(protocol)
107
        except KeyboardInterrupt:
108
            raise
109
        except Exception, e:
110
            self.terminate_due_to_error()
111
112
    def terminate_due_to_error(self):
113
        """Called when an unhandled exception from the protocol occurs."""
114
        raise NotImplementedError(self.terminate_due_to_error)
115
2432.2.2 by Andrew Bennetts
Smart server mediums now detect which protocol version a request is and dispatch accordingly.
116
    def _get_bytes(self, desired_count):
117
        """Get some bytes from the medium.
118
119
        :param desired_count: number of bytes we want to read.
120
        """
121
        raise NotImplementedError(self._get_bytes)
122
2432.2.7 by Andrew Bennetts
Use less confusing version strings, and define REQUEST_VERSION_TWO/RESPONSE_VERSION_TWO constants for them.
123
    def _get_line(self):
124
        """Read bytes from this request's response until a newline byte.
125
        
126
        This isn't particularly efficient, so should only be used when the
127
        expected size of the line is quite short.
128
129
        :returns: a string of bytes ending in a newline (byte 0x0A).
130
        """
131
        # XXX: this duplicates SmartClientRequestProtocolOne._recv_tuple
132
        line = ''
133
        while not line or line[-1] != '\n':
134
            new_char = self._get_bytes(1)
135
            line += new_char
136
            if new_char == '':
137
                # Ran out of bytes before receiving a complete line.
138
                break
139
        return line
140
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
141
142
class SmartServerSocketStreamMedium(SmartServerStreamMedium):
143
144
    def __init__(self, sock, backing_transport):
145
        """Constructor.
146
147
        :param sock: the socket the server will read from.  It will be put
148
            into blocking mode.
149
        """
150
        SmartServerStreamMedium.__init__(self, backing_transport)
151
        self.push_back = ''
152
        sock.setblocking(True)
153
        self.socket = sock
154
155
    def _serve_one_request_unguarded(self, protocol):
156
        while protocol.next_read_size():
157
            if self.push_back:
158
                protocol.accept_bytes(self.push_back)
159
                self.push_back = ''
160
            else:
2432.2.2 by Andrew Bennetts
Smart server mediums now detect which protocol version a request is and dispatch accordingly.
161
                bytes = self._get_bytes(4096)
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
162
                if bytes == '':
163
                    self.finished = True
164
                    return
165
                protocol.accept_bytes(bytes)
166
        
167
        self.push_back = protocol.excess_buffer
2432.2.2 by Andrew Bennetts
Smart server mediums now detect which protocol version a request is and dispatch accordingly.
168
169
    def _get_bytes(self, desired_count):
170
        # We ignore the desired_count because on sockets it's more efficient to
171
        # read 4k at a time.
172
        return self.socket.recv(4096)
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
173
    
174
    def terminate_due_to_error(self):
175
        """Called when an unhandled exception from the protocol occurs."""
176
        # TODO: This should log to a server log file, but no such thing
177
        # exists yet.  Andrew Bennetts 2006-09-29.
178
        self.socket.close()
179
        self.finished = True
180
181
    def _write_out(self, bytes):
3118.2.1 by Andrew Bennetts
(andrew) Fix #115781 by passing no more than 64k at a time to socket.sendall.
182
        osutils.send_all(self.socket, bytes)
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
183
184
185
class SmartServerPipeStreamMedium(SmartServerStreamMedium):
186
187
    def __init__(self, in_file, out_file, backing_transport):
188
        """Construct new server.
189
190
        :param in_file: Python file from which requests can be read.
191
        :param out_file: Python file to write responses.
192
        :param backing_transport: Transport for the directory served.
193
        """
194
        SmartServerStreamMedium.__init__(self, backing_transport)
2018.5.161 by Andrew Bennetts
Reinstate forcing binary mode on windows in SmartServerStreamMedium.
195
        if sys.platform == 'win32':
196
            # force binary mode for files
197
            import msvcrt
198
            for f in (in_file, out_file):
199
                fileno = getattr(f, 'fileno', None)
200
                if fileno:
201
                    msvcrt.setmode(fileno(), os.O_BINARY)
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
202
        self._in = in_file
203
        self._out = out_file
204
205
    def _serve_one_request_unguarded(self, protocol):
206
        while True:
207
            bytes_to_read = protocol.next_read_size()
208
            if bytes_to_read == 0:
209
                # Finished serving this request.
210
                self._out.flush()
211
                return
2432.2.2 by Andrew Bennetts
Smart server mediums now detect which protocol version a request is and dispatch accordingly.
212
            bytes = self._get_bytes(bytes_to_read)
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
213
            if bytes == '':
214
                # Connection has been closed.
215
                self.finished = True
216
                self._out.flush()
217
                return
218
            protocol.accept_bytes(bytes)
219
2432.2.2 by Andrew Bennetts
Smart server mediums now detect which protocol version a request is and dispatch accordingly.
220
    def _get_bytes(self, desired_count):
221
        return self._in.read(desired_count)
222
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
223
    def terminate_due_to_error(self):
224
        # TODO: This should log to a server log file, but no such thing
225
        # exists yet.  Andrew Bennetts 2006-09-29.
226
        self._out.close()
227
        self.finished = True
228
229
    def _write_out(self, bytes):
230
        self._out.write(bytes)
231
232
233
class SmartClientMediumRequest(object):
234
    """A request on a SmartClientMedium.
235
236
    Each request allows bytes to be provided to it via accept_bytes, and then
237
    the response bytes to be read via read_bytes.
238
239
    For instance:
240
    request.accept_bytes('123')
241
    request.finished_writing()
242
    result = request.read_bytes(3)
243
    request.finished_reading()
244
245
    It is up to the individual SmartClientMedium whether multiple concurrent
246
    requests can exist. See SmartClientMedium.get_request to obtain instances 
247
    of SmartClientMediumRequest, and the concrete Medium you are using for 
248
    details on concurrency and pipelining.
249
    """
250
251
    def __init__(self, medium):
252
        """Construct a SmartClientMediumRequest for the medium medium."""
253
        self._medium = medium
254
        # we track state by constants - we may want to use the same
255
        # pattern as BodyReader if it gets more complex.
256
        # valid states are: "writing", "reading", "done"
257
        self._state = "writing"
258
259
    def accept_bytes(self, bytes):
260
        """Accept bytes for inclusion in this request.
261
262
        This method may not be be called after finished_writing() has been
263
        called.  It depends upon the Medium whether or not the bytes will be
264
        immediately transmitted. Message based Mediums will tend to buffer the
265
        bytes until finished_writing() is called.
266
267
        :param bytes: A bytestring.
268
        """
269
        if self._state != "writing":
270
            raise errors.WritingCompleted(self)
271
        self._accept_bytes(bytes)
272
273
    def _accept_bytes(self, bytes):
274
        """Helper for accept_bytes.
275
276
        Accept_bytes checks the state of the request to determing if bytes
277
        should be accepted. After that it hands off to _accept_bytes to do the
278
        actual acceptance.
279
        """
280
        raise NotImplementedError(self._accept_bytes)
281
282
    def finished_reading(self):
283
        """Inform the request that all desired data has been read.
284
285
        This will remove the request from the pipeline for its medium (if the
286
        medium supports pipelining) and any further calls to methods on the
287
        request will raise ReadingCompleted.
288
        """
289
        if self._state == "writing":
290
            raise errors.WritingNotComplete(self)
291
        if self._state != "reading":
292
            raise errors.ReadingCompleted(self)
293
        self._state = "done"
294
        self._finished_reading()
295
296
    def _finished_reading(self):
297
        """Helper for finished_reading.
298
299
        finished_reading checks the state of the request to determine if 
300
        finished_reading is allowed, and if it is hands off to _finished_reading
301
        to perform the action.
302
        """
303
        raise NotImplementedError(self._finished_reading)
304
305
    def finished_writing(self):
306
        """Finish the writing phase of this request.
307
308
        This will flush all pending data for this request along the medium.
309
        After calling finished_writing, you may not call accept_bytes anymore.
310
        """
311
        if self._state != "writing":
312
            raise errors.WritingCompleted(self)
313
        self._state = "reading"
314
        self._finished_writing()
315
316
    def _finished_writing(self):
317
        """Helper for finished_writing.
318
319
        finished_writing checks the state of the request to determine if 
320
        finished_writing is allowed, and if it is hands off to _finished_writing
321
        to perform the action.
322
        """
323
        raise NotImplementedError(self._finished_writing)
324
325
    def read_bytes(self, count):
326
        """Read bytes from this requests response.
327
328
        This method will block and wait for count bytes to be read. It may not
329
        be invoked until finished_writing() has been called - this is to ensure
2432.2.7 by Andrew Bennetts
Use less confusing version strings, and define REQUEST_VERSION_TWO/RESPONSE_VERSION_TWO constants for them.
330
        a message-based approach to requests, for compatibility with message
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
331
        based mediums like HTTP.
332
        """
333
        if self._state == "writing":
334
            raise errors.WritingNotComplete(self)
335
        if self._state != "reading":
336
            raise errors.ReadingCompleted(self)
337
        return self._read_bytes(count)
338
339
    def _read_bytes(self, count):
340
        """Helper for read_bytes.
341
342
        read_bytes checks the state of the request to determing if bytes
343
        should be read. After that it hands off to _read_bytes to do the
344
        actual read.
345
        """
346
        raise NotImplementedError(self._read_bytes)
347
2432.2.7 by Andrew Bennetts
Use less confusing version strings, and define REQUEST_VERSION_TWO/RESPONSE_VERSION_TWO constants for them.
348
    def read_line(self):
349
        """Read bytes from this request's response until a newline byte.
350
        
351
        This isn't particularly efficient, so should only be used when the
352
        expected size of the line is quite short.
353
354
        :returns: a string of bytes ending in a newline (byte 0x0A).
355
        """
356
        # XXX: this duplicates SmartClientRequestProtocolOne._recv_tuple
357
        line = ''
358
        while not line or line[-1] != '\n':
359
            new_char = self.read_bytes(1)
360
            line += new_char
361
            if new_char == '':
3195.2.1 by Andrew Bennetts
Improve test coverage, and fix a bug revealed by the improved coverage.
362
                # end of file encountered reading from server
363
                raise errors.ConnectionReset(
364
                    "please check connectivity and permissions",
365
                    "(and try -Dhpss if further diagnosis is required)")
2432.2.7 by Andrew Bennetts
Use less confusing version strings, and define REQUEST_VERSION_TWO/RESPONSE_VERSION_TWO constants for them.
366
        return line
367
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
368
369
class SmartClientMedium(object):
370
    """Smart client is a medium for sending smart protocol requests over."""
371
3241.1.1 by Andrew Bennetts
Shift protocol version querying from RemoteBzrDirFormat into SmartClientMedium.
372
    def __init__(self):
373
        super(SmartClientMedium, self).__init__()
374
        self._protocol_version = None
375
376
    def protocol_version(self):
377
        """Find out the best protocol version to use."""
378
        if self._protocol_version is None:
379
            medium_request = self.get_request()
3241.1.2 by Andrew Bennetts
Tidy comments.
380
            # Send a 'hello' request in protocol version one, for maximum
381
            # backwards compatibility.
3241.1.1 by Andrew Bennetts
Shift protocol version querying from RemoteBzrDirFormat into SmartClientMedium.
382
            client_protocol = SmartClientRequestProtocolOne(medium_request)
383
            self._protocol_version = client_protocol.query_version()
384
        return self._protocol_version
385
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
386
    def disconnect(self):
387
        """If this medium maintains a persistent connection, close it.
388
        
389
        The default implementation does nothing.
390
        """
391
        
392
393
class SmartClientStreamMedium(SmartClientMedium):
394
    """Stream based medium common class.
395
396
    SmartClientStreamMediums operate on a stream. All subclasses use a common
397
    SmartClientStreamMediumRequest for their requests, and should implement
398
    _accept_bytes and _read_bytes to allow the request objects to send and
399
    receive bytes.
400
    """
401
402
    def __init__(self):
3241.1.1 by Andrew Bennetts
Shift protocol version querying from RemoteBzrDirFormat into SmartClientMedium.
403
        SmartClientMedium.__init__(self)
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
404
        self._current_request = None
3213.1.1 by Andrew Bennetts
Recover (by reconnecting) if the server turns out not to understand the new requests in 1.2 that send bodies.
405
        # Be optimistic: we assume the remote end can accept new remote
406
        # requests until we get an error saying otherwise.  (1.2 adds some
407
        # requests that send bodies, which confuses older servers.)
408
        self._remote_is_at_least_1_2 = True
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
409
410
    def accept_bytes(self, bytes):
411
        self._accept_bytes(bytes)
412
413
    def __del__(self):
414
        """The SmartClientStreamMedium knows how to close the stream when it is
415
        finished with it.
416
        """
417
        self.disconnect()
418
419
    def _flush(self):
420
        """Flush the output stream.
421
        
422
        This method is used by the SmartClientStreamMediumRequest to ensure that
423
        all data for a request is sent, to avoid long timeouts or deadlocks.
424
        """
425
        raise NotImplementedError(self._flush)
426
427
    def get_request(self):
428
        """See SmartClientMedium.get_request().
429
430
        SmartClientStreamMedium always returns a SmartClientStreamMediumRequest
431
        for get_request.
432
        """
433
        return SmartClientStreamMediumRequest(self)
434
435
    def read_bytes(self, count):
436
        return self._read_bytes(count)
437
438
439
class SmartSimplePipesClientMedium(SmartClientStreamMedium):
440
    """A client medium using simple pipes.
441
    
442
    This client does not manage the pipes: it assumes they will always be open.
443
    """
444
445
    def __init__(self, readable_pipe, writeable_pipe):
446
        SmartClientStreamMedium.__init__(self)
447
        self._readable_pipe = readable_pipe
448
        self._writeable_pipe = writeable_pipe
449
450
    def _accept_bytes(self, bytes):
451
        """See SmartClientStreamMedium.accept_bytes."""
452
        self._writeable_pipe.write(bytes)
453
454
    def _flush(self):
455
        """See SmartClientStreamMedium._flush()."""
456
        self._writeable_pipe.flush()
457
458
    def _read_bytes(self, count):
459
        """See SmartClientStreamMedium._read_bytes."""
460
        return self._readable_pipe.read(count)
461
462
463
class SmartSSHClientMedium(SmartClientStreamMedium):
464
    """A client medium using SSH."""
465
    
466
    def __init__(self, host, port=None, username=None, password=None,
1551.18.17 by Aaron Bentley
Introduce bzr_remote_path configuration variable
467
            vendor=None, bzr_remote_path=None):
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
468
        """Creates a client that will connect on the first use.
469
        
470
        :param vendor: An optional override for the ssh vendor to use. See
471
            bzrlib.transport.ssh for details on ssh vendors.
472
        """
473
        SmartClientStreamMedium.__init__(self)
474
        self._connected = False
475
        self._host = host
476
        self._password = password
477
        self._port = port
478
        self._username = username
479
        self._read_from = None
480
        self._ssh_connection = None
481
        self._vendor = vendor
482
        self._write_to = None
1551.18.17 by Aaron Bentley
Introduce bzr_remote_path configuration variable
483
        self._bzr_remote_path = bzr_remote_path
484
        if self._bzr_remote_path is None:
485
            symbol_versioning.warn(
486
                'bzr_remote_path is required as of bzr 0.92',
487
                DeprecationWarning, stacklevel=2)
488
            self._bzr_remote_path = os.environ.get('BZR_REMOTE_PATH', 'bzr')
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
489
490
    def _accept_bytes(self, bytes):
491
        """See SmartClientStreamMedium.accept_bytes."""
492
        self._ensure_connection()
493
        self._write_to.write(bytes)
494
495
    def disconnect(self):
496
        """See SmartClientMedium.disconnect()."""
497
        if not self._connected:
498
            return
499
        self._read_from.close()
500
        self._write_to.close()
501
        self._ssh_connection.close()
502
        self._connected = False
503
504
    def _ensure_connection(self):
505
        """Connect this medium if not already connected."""
506
        if self._connected:
507
            return
508
        if self._vendor is None:
509
            vendor = ssh._get_ssh_vendor()
510
        else:
511
            vendor = self._vendor
512
        self._ssh_connection = vendor.connect_ssh(self._username,
513
                self._password, self._host, self._port,
1551.18.17 by Aaron Bentley
Introduce bzr_remote_path configuration variable
514
                command=[self._bzr_remote_path, 'serve', '--inet',
515
                         '--directory=/', '--allow-writes'])
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
516
        self._read_from, self._write_to = \
517
            self._ssh_connection.get_filelike_channels()
518
        self._connected = True
519
520
    def _flush(self):
521
        """See SmartClientStreamMedium._flush()."""
522
        self._write_to.flush()
523
524
    def _read_bytes(self, count):
525
        """See SmartClientStreamMedium.read_bytes."""
526
        if not self._connected:
527
            raise errors.MediumNotConnected(self)
528
        return self._read_from.read(count)
529
530
3004.2.1 by Vincent Ladeuil
Fix 150860 by leaving port as user specified it.
531
# Port 4155 is the default port for bzr://, registered with IANA.
532
BZR_DEFAULT_INTERFACE = '0.0.0.0'
533
BZR_DEFAULT_PORT = 4155
534
535
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
536
class SmartTCPClientMedium(SmartClientStreamMedium):
537
    """A client medium using TCP."""
538
    
539
    def __init__(self, host, port):
540
        """Creates a client that will connect on the first use."""
541
        SmartClientStreamMedium.__init__(self)
542
        self._connected = False
543
        self._host = host
544
        self._port = port
545
        self._socket = None
546
547
    def _accept_bytes(self, bytes):
548
        """See SmartClientMedium.accept_bytes."""
549
        self._ensure_connection()
3118.2.1 by Andrew Bennetts
(andrew) Fix #115781 by passing no more than 64k at a time to socket.sendall.
550
        osutils.send_all(self._socket, bytes)
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
551
552
    def disconnect(self):
553
        """See SmartClientMedium.disconnect()."""
554
        if not self._connected:
555
            return
556
        self._socket.close()
557
        self._socket = None
558
        self._connected = False
559
560
    def _ensure_connection(self):
561
        """Connect this medium if not already connected."""
562
        if self._connected:
563
            return
564
        self._socket = socket.socket()
565
        self._socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
3004.2.1 by Vincent Ladeuil
Fix 150860 by leaving port as user specified it.
566
        if self._port is None:
567
            port = BZR_DEFAULT_PORT
568
        else:
569
            port = int(self._port)
3180.1.1 by Andrew Bennetts
Don't traceback on host name errors when connecting to bzr://...
570
        try:
571
            self._socket.connect((self._host, port))
572
        except socket.error, err:
573
            # socket errors either have a (string) or (errno, string) as their
574
            # args.
575
            if type(err.args) is str:
576
                err_msg = err.args
577
            else:
578
                err_msg = err.args[1]
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
579
            raise errors.ConnectionError("failed to connect to %s:%d: %s" %
3180.1.1 by Andrew Bennetts
Don't traceback on host name errors when connecting to bzr://...
580
                    (self._host, port, err_msg))
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
581
        self._connected = True
582
583
    def _flush(self):
584
        """See SmartClientStreamMedium._flush().
585
        
586
        For TCP we do no flushing. We may want to turn off TCP_NODELAY and 
587
        add a means to do a flush, but that can be done in the future.
588
        """
589
590
    def _read_bytes(self, count):
591
        """See SmartClientMedium.read_bytes."""
592
        if not self._connected:
593
            raise errors.MediumNotConnected(self)
594
        return self._socket.recv(count)
595
596
597
class SmartClientStreamMediumRequest(SmartClientMediumRequest):
598
    """A SmartClientMediumRequest that works with an SmartClientStreamMedium."""
599
600
    def __init__(self, medium):
601
        SmartClientMediumRequest.__init__(self, medium)
602
        # check that we are safe concurrency wise. If some streams start
603
        # allowing concurrent requests - i.e. via multiplexing - then this
604
        # assert should be moved to SmartClientStreamMedium.get_request,
605
        # and the setting/unsetting of _current_request likewise moved into
606
        # that class : but its unneeded overhead for now. RBC 20060922
607
        if self._medium._current_request is not None:
608
            raise errors.TooManyConcurrentRequests(self._medium)
609
        self._medium._current_request = self
610
611
    def _accept_bytes(self, bytes):
612
        """See SmartClientMediumRequest._accept_bytes.
613
        
614
        This forwards to self._medium._accept_bytes because we are operating
615
        on the mediums stream.
616
        """
617
        self._medium._accept_bytes(bytes)
618
619
    def _finished_reading(self):
620
        """See SmartClientMediumRequest._finished_reading.
621
622
        This clears the _current_request on self._medium to allow a new 
623
        request to be created.
624
        """
625
        assert self._medium._current_request is self
626
        self._medium._current_request = None
627
        
628
    def _finished_writing(self):
629
        """See SmartClientMediumRequest._finished_writing.
630
631
        This invokes self._medium._flush to ensure all bytes are transmitted.
632
        """
633
        self._medium._flush()
634
635
    def _read_bytes(self, count):
636
        """See SmartClientMediumRequest._read_bytes.
637
        
638
        This forwards to self._medium._read_bytes because we are operating
639
        on the mediums stream.
640
        """
641
        return self._medium._read_bytes(count)
642