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