/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to bzrlib/transport/remote.py

  • Committer: Robert Collins
  • Date: 2007-04-18 08:39:02 UTC
  • mto: (2425.1.2 integration)
  • mto: This revision was merged to the branch mainline in revision 2427.
  • Revision ID: robertc@robertcollins.net-20070418083902-4o66h9fk7zeisvwa
Command objects can now declare related help topics by having _see_also
set to a list of related topic. Updated the HACKING guide entry on
documentation to be more clear about how the help for commands is
generated and to reference this new feature. (Robert Collins)

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2006 Canonical Ltd
 
2
#
 
3
# This program is free software; you can redistribute it and/or modify
 
4
# it under the terms of the GNU General Public License as published by
 
5
# the Free Software Foundation; either version 2 of the License, or
 
6
# (at your option) any later version.
 
7
#
 
8
# This program is distributed in the hope that it will be useful,
 
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
 
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
11
# GNU General Public License for more details.
 
12
#
 
13
# You should have received a copy of the GNU General Public License
 
14
# along with this program; if not, write to the Free Software
 
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 
16
 
 
17
from cStringIO import StringIO
 
18
import urllib
 
19
import urlparse
 
20
 
 
21
from bzrlib import (
 
22
    errors,
 
23
    transport,
 
24
    )
 
25
from bzrlib.smart.protocol import SmartClientRequestProtocolOne
 
26
from bzrlib.smart.medium import SmartTCPClientMedium, SmartSSHClientMedium
 
27
 
 
28
# must do this otherwise urllib can't parse the urls properly :(
 
29
for scheme in ['ssh', 'bzr', 'bzr+loopback', 'bzr+ssh', 'bzr+http']:
 
30
    transport.register_urlparse_netloc_protocol(scheme)
 
31
del scheme
 
32
 
 
33
 
 
34
# Port 4155 is the default port for bzr://, registered with IANA.
 
35
BZR_DEFAULT_PORT = 4155
 
36
 
 
37
 
 
38
class SmartStat(object):
 
39
 
 
40
    def __init__(self, size, mode):
 
41
        self.st_size = size
 
42
        self.st_mode = mode
 
43
 
 
44
 
 
45
class RemoteTransport(transport.Transport):
 
46
    """Connection to a smart server.
 
47
 
 
48
    The connection holds references to pipes that can be used to send requests
 
49
    to the server.
 
50
 
 
51
    The connection has a notion of the current directory to which it's
 
52
    connected; this is incorporated in filenames passed to the server.
 
53
    
 
54
    This supports some higher-level RPC operations and can also be treated 
 
55
    like a Transport to do file-like operations.
 
56
 
 
57
    The connection can be made over a tcp socket, or (in future) an ssh pipe
 
58
    or a series of http requests.  There are concrete subclasses for each
 
59
    type: RemoteTCPTransport, etc.
 
60
    """
 
61
 
 
62
    # IMPORTANT FOR IMPLEMENTORS: RemoteTransport MUST NOT be given encoding
 
63
    # responsibilities: Put those on SmartClient or similar. This is vital for
 
64
    # the ability to support multiple versions of the smart protocol over time:
 
65
    # RemoteTransport is an adapter from the Transport object model to the 
 
66
    # SmartClient model, not an encoder.
 
67
 
 
68
    def __init__(self, url, clone_from=None, medium=None):
 
69
        """Constructor.
 
70
 
 
71
        :param medium: The medium to use for this RemoteTransport. This must be
 
72
            supplied if clone_from is None.
 
73
        """
 
74
        ### Technically super() here is faulty because Transport's __init__
 
75
        ### fails to take 2 parameters, and if super were to choose a silly
 
76
        ### initialisation order things would blow up. 
 
77
        if not url.endswith('/'):
 
78
            url += '/'
 
79
        super(RemoteTransport, self).__init__(url)
 
80
        self._scheme, self._username, self._password, self._host, self._port, self._path = \
 
81
                transport.split_url(url)
 
82
        if clone_from is None:
 
83
            self._medium = medium
 
84
        else:
 
85
            # credentials may be stripped from the base in some circumstances
 
86
            # as yet to be clearly defined or documented, so copy them.
 
87
            self._username = clone_from._username
 
88
            # reuse same connection
 
89
            self._medium = clone_from._medium
 
90
        assert self._medium is not None
 
91
 
 
92
    def abspath(self, relpath):
 
93
        """Return the full url to the given relative path.
 
94
        
 
95
        @param relpath: the relative path or path components
 
96
        @type relpath: str or list
 
97
        """
 
98
        return self._unparse_url(self._remote_path(relpath))
 
99
    
 
100
    def clone(self, relative_url):
 
101
        """Make a new RemoteTransport related to me, sharing the same connection.
 
102
 
 
103
        This essentially opens a handle on a different remote directory.
 
104
        """
 
105
        if relative_url is None:
 
106
            return RemoteTransport(self.base, self)
 
107
        else:
 
108
            return RemoteTransport(self.abspath(relative_url), self)
 
109
 
 
110
    def is_readonly(self):
 
111
        """Smart server transport can do read/write file operations."""
 
112
        return False
 
113
                                                   
 
114
    def get_smart_client(self):
 
115
        return self._medium
 
116
 
 
117
    def get_smart_medium(self):
 
118
        return self._medium
 
119
                                                   
 
120
    def _unparse_url(self, path):
 
121
        """Return URL for a path.
 
122
 
 
123
        :see: SFTPUrlHandling._unparse_url
 
124
        """
 
125
        # TODO: Eventually it should be possible to unify this with
 
126
        # SFTPUrlHandling._unparse_url?
 
127
        if path == '':
 
128
            path = '/'
 
129
        path = urllib.quote(path)
 
130
        netloc = urllib.quote(self._host)
 
131
        if self._username is not None:
 
132
            netloc = '%s@%s' % (urllib.quote(self._username), netloc)
 
133
        if self._port is not None:
 
134
            netloc = '%s:%d' % (netloc, self._port)
 
135
        return urlparse.urlunparse((self._scheme, netloc, path, '', '', ''))
 
136
 
 
137
    def _remote_path(self, relpath):
 
138
        """Returns the Unicode version of the absolute path for relpath."""
 
139
        return self._combine_paths(self._path, relpath)
 
140
 
 
141
    def _call(self, method, *args):
 
142
        resp = self._call2(method, *args)
 
143
        self._translate_error(resp)
 
144
 
 
145
    def _call2(self, method, *args):
 
146
        """Call a method on the remote server."""
 
147
        protocol = SmartClientRequestProtocolOne(self._medium.get_request())
 
148
        protocol.call(method, *args)
 
149
        return protocol.read_response_tuple()
 
150
 
 
151
    def _call_with_body_bytes(self, method, args, body):
 
152
        """Call a method on the remote server with body bytes."""
 
153
        protocol = SmartClientRequestProtocolOne(self._medium.get_request())
 
154
        protocol.call_with_body_bytes((method, ) + args, body)
 
155
        return protocol.read_response_tuple()
 
156
 
 
157
    def has(self, relpath):
 
158
        """Indicate whether a remote file of the given name exists or not.
 
159
 
 
160
        :see: Transport.has()
 
161
        """
 
162
        resp = self._call2('has', self._remote_path(relpath))
 
163
        if resp == ('yes', ):
 
164
            return True
 
165
        elif resp == ('no', ):
 
166
            return False
 
167
        else:
 
168
            self._translate_error(resp)
 
169
 
 
170
    def get(self, relpath):
 
171
        """Return file-like object reading the contents of a remote file.
 
172
        
 
173
        :see: Transport.get_bytes()/get_file()
 
174
        """
 
175
        return StringIO(self.get_bytes(relpath))
 
176
 
 
177
    def get_bytes(self, relpath):
 
178
        remote = self._remote_path(relpath)
 
179
        protocol = SmartClientRequestProtocolOne(self._medium.get_request())
 
180
        protocol.call('get', remote)
 
181
        resp = protocol.read_response_tuple(True)
 
182
        if resp != ('ok', ):
 
183
            protocol.cancel_read_body()
 
184
            self._translate_error(resp, relpath)
 
185
        return protocol.read_body_bytes()
 
186
 
 
187
    def _serialise_optional_mode(self, mode):
 
188
        if mode is None:
 
189
            return ''
 
190
        else:
 
191
            return '%d' % mode
 
192
 
 
193
    def mkdir(self, relpath, mode=None):
 
194
        resp = self._call2('mkdir', self._remote_path(relpath),
 
195
            self._serialise_optional_mode(mode))
 
196
        self._translate_error(resp)
 
197
 
 
198
    def put_bytes(self, relpath, upload_contents, mode=None):
 
199
        # FIXME: upload_file is probably not safe for non-ascii characters -
 
200
        # should probably just pass all parameters as length-delimited
 
201
        # strings?
 
202
        resp = self._call_with_body_bytes('put',
 
203
            (self._remote_path(relpath), self._serialise_optional_mode(mode)),
 
204
            upload_contents)
 
205
        self._translate_error(resp)
 
206
 
 
207
    def put_bytes_non_atomic(self, relpath, bytes, mode=None,
 
208
                             create_parent_dir=False,
 
209
                             dir_mode=None):
 
210
        """See Transport.put_bytes_non_atomic."""
 
211
        # FIXME: no encoding in the transport!
 
212
        create_parent_str = 'F'
 
213
        if create_parent_dir:
 
214
            create_parent_str = 'T'
 
215
 
 
216
        resp = self._call_with_body_bytes(
 
217
            'put_non_atomic',
 
218
            (self._remote_path(relpath), self._serialise_optional_mode(mode),
 
219
             create_parent_str, self._serialise_optional_mode(dir_mode)),
 
220
            bytes)
 
221
        self._translate_error(resp)
 
222
 
 
223
    def put_file(self, relpath, upload_file, mode=None):
 
224
        # its not ideal to seek back, but currently put_non_atomic_file depends
 
225
        # on transports not reading before failing - which is a faulty
 
226
        # assumption I think - RBC 20060915
 
227
        pos = upload_file.tell()
 
228
        try:
 
229
            return self.put_bytes(relpath, upload_file.read(), mode)
 
230
        except:
 
231
            upload_file.seek(pos)
 
232
            raise
 
233
 
 
234
    def put_file_non_atomic(self, relpath, f, mode=None,
 
235
                            create_parent_dir=False,
 
236
                            dir_mode=None):
 
237
        return self.put_bytes_non_atomic(relpath, f.read(), mode=mode,
 
238
                                         create_parent_dir=create_parent_dir,
 
239
                                         dir_mode=dir_mode)
 
240
 
 
241
    def append_file(self, relpath, from_file, mode=None):
 
242
        return self.append_bytes(relpath, from_file.read(), mode)
 
243
        
 
244
    def append_bytes(self, relpath, bytes, mode=None):
 
245
        resp = self._call_with_body_bytes(
 
246
            'append',
 
247
            (self._remote_path(relpath), self._serialise_optional_mode(mode)),
 
248
            bytes)
 
249
        if resp[0] == 'appended':
 
250
            return int(resp[1])
 
251
        self._translate_error(resp)
 
252
 
 
253
    def delete(self, relpath):
 
254
        resp = self._call2('delete', self._remote_path(relpath))
 
255
        self._translate_error(resp)
 
256
 
 
257
    def readv(self, relpath, offsets):
 
258
        if not offsets:
 
259
            return
 
260
 
 
261
        offsets = list(offsets)
 
262
 
 
263
        sorted_offsets = sorted(offsets)
 
264
        # turn the list of offsets into a stack
 
265
        offset_stack = iter(offsets)
 
266
        cur_offset_and_size = offset_stack.next()
 
267
        coalesced = list(self._coalesce_offsets(sorted_offsets,
 
268
                               limit=self._max_readv_combine,
 
269
                               fudge_factor=self._bytes_to_read_before_seek))
 
270
 
 
271
        protocol = SmartClientRequestProtocolOne(self._medium.get_request())
 
272
        protocol.call_with_body_readv_array(
 
273
            ('readv', self._remote_path(relpath)),
 
274
            [(c.start, c.length) for c in coalesced])
 
275
        resp = protocol.read_response_tuple(True)
 
276
 
 
277
        if resp[0] != 'readv':
 
278
            # This should raise an exception
 
279
            protocol.cancel_read_body()
 
280
            self._translate_error(resp)
 
281
            return
 
282
 
 
283
        # FIXME: this should know how many bytes are needed, for clarity.
 
284
        data = protocol.read_body_bytes()
 
285
        # Cache the results, but only until they have been fulfilled
 
286
        data_map = {}
 
287
        for c_offset in coalesced:
 
288
            if len(data) < c_offset.length:
 
289
                raise errors.ShortReadvError(relpath, c_offset.start,
 
290
                            c_offset.length, actual=len(data))
 
291
            for suboffset, subsize in c_offset.ranges:
 
292
                key = (c_offset.start+suboffset, subsize)
 
293
                data_map[key] = data[suboffset:suboffset+subsize]
 
294
            data = data[c_offset.length:]
 
295
 
 
296
            # Now that we've read some data, see if we can yield anything back
 
297
            while cur_offset_and_size in data_map:
 
298
                this_data = data_map.pop(cur_offset_and_size)
 
299
                yield cur_offset_and_size[0], this_data
 
300
                cur_offset_and_size = offset_stack.next()
 
301
 
 
302
    def rename(self, rel_from, rel_to):
 
303
        self._call('rename',
 
304
                   self._remote_path(rel_from),
 
305
                   self._remote_path(rel_to))
 
306
 
 
307
    def move(self, rel_from, rel_to):
 
308
        self._call('move',
 
309
                   self._remote_path(rel_from),
 
310
                   self._remote_path(rel_to))
 
311
 
 
312
    def rmdir(self, relpath):
 
313
        resp = self._call('rmdir', self._remote_path(relpath))
 
314
 
 
315
    def _translate_error(self, resp, orig_path=None):
 
316
        """Raise an exception from a response"""
 
317
        if resp is None:
 
318
            what = None
 
319
        else:
 
320
            what = resp[0]
 
321
        if what == 'ok':
 
322
            return
 
323
        elif what == 'NoSuchFile':
 
324
            if orig_path is not None:
 
325
                error_path = orig_path
 
326
            else:
 
327
                error_path = resp[1]
 
328
            raise errors.NoSuchFile(error_path)
 
329
        elif what == 'error':
 
330
            raise errors.SmartProtocolError(unicode(resp[1]))
 
331
        elif what == 'FileExists':
 
332
            raise errors.FileExists(resp[1])
 
333
        elif what == 'DirectoryNotEmpty':
 
334
            raise errors.DirectoryNotEmpty(resp[1])
 
335
        elif what == 'ShortReadvError':
 
336
            raise errors.ShortReadvError(resp[1], int(resp[2]),
 
337
                                         int(resp[3]), int(resp[4]))
 
338
        elif what in ('UnicodeEncodeError', 'UnicodeDecodeError'):
 
339
            encoding = str(resp[1]) # encoding must always be a string
 
340
            val = resp[2]
 
341
            start = int(resp[3])
 
342
            end = int(resp[4])
 
343
            reason = str(resp[5]) # reason must always be a string
 
344
            if val.startswith('u:'):
 
345
                val = val[2:].decode('utf-8')
 
346
            elif val.startswith('s:'):
 
347
                val = val[2:].decode('base64')
 
348
            if what == 'UnicodeDecodeError':
 
349
                raise UnicodeDecodeError(encoding, val, start, end, reason)
 
350
            elif what == 'UnicodeEncodeError':
 
351
                raise UnicodeEncodeError(encoding, val, start, end, reason)
 
352
        elif what == "ReadOnlyError":
 
353
            raise errors.TransportNotPossible('readonly transport')
 
354
        else:
 
355
            raise errors.SmartProtocolError('unexpected smart server error: %r' % (resp,))
 
356
 
 
357
    def disconnect(self):
 
358
        self._medium.disconnect()
 
359
 
 
360
    def delete_tree(self, relpath):
 
361
        raise errors.TransportNotPossible('readonly transport')
 
362
 
 
363
    def stat(self, relpath):
 
364
        resp = self._call2('stat', self._remote_path(relpath))
 
365
        if resp[0] == 'stat':
 
366
            return SmartStat(int(resp[1]), int(resp[2], 8))
 
367
        else:
 
368
            self._translate_error(resp)
 
369
 
 
370
    ## def lock_read(self, relpath):
 
371
    ##     """Lock the given file for shared (read) access.
 
372
    ##     :return: A lock object, which should be passed to Transport.unlock()
 
373
    ##     """
 
374
    ##     # The old RemoteBranch ignore lock for reading, so we will
 
375
    ##     # continue that tradition and return a bogus lock object.
 
376
    ##     class BogusLock(object):
 
377
    ##         def __init__(self, path):
 
378
    ##             self.path = path
 
379
    ##         def unlock(self):
 
380
    ##             pass
 
381
    ##     return BogusLock(relpath)
 
382
 
 
383
    def listable(self):
 
384
        return True
 
385
 
 
386
    def list_dir(self, relpath):
 
387
        resp = self._call2('list_dir', self._remote_path(relpath))
 
388
        if resp[0] == 'names':
 
389
            return [name.encode('ascii') for name in resp[1:]]
 
390
        else:
 
391
            self._translate_error(resp)
 
392
 
 
393
    def iter_files_recursive(self):
 
394
        resp = self._call2('iter_files_recursive', self._remote_path(''))
 
395
        if resp[0] == 'names':
 
396
            return resp[1:]
 
397
        else:
 
398
            self._translate_error(resp)
 
399
 
 
400
 
 
401
 
 
402
class RemoteTCPTransport(RemoteTransport):
 
403
    """Connection to smart server over plain tcp.
 
404
    
 
405
    This is essentially just a factory to get 'RemoteTransport(url,
 
406
        SmartTCPClientMedium).
 
407
    """
 
408
 
 
409
    def __init__(self, url):
 
410
        _scheme, _username, _password, _host, _port, _path = \
 
411
            transport.split_url(url)
 
412
        if _port is None:
 
413
            _port = BZR_DEFAULT_PORT
 
414
        else:
 
415
            try:
 
416
                _port = int(_port)
 
417
            except (ValueError, TypeError), e:
 
418
                raise errors.InvalidURL(
 
419
                    path=url, extra="invalid port %s" % _port)
 
420
        medium = SmartTCPClientMedium(_host, _port)
 
421
        super(RemoteTCPTransport, self).__init__(url, medium=medium)
 
422
 
 
423
 
 
424
class RemoteSSHTransport(RemoteTransport):
 
425
    """Connection to smart server over SSH.
 
426
 
 
427
    This is essentially just a factory to get 'RemoteTransport(url,
 
428
        SmartSSHClientMedium).
 
429
    """
 
430
 
 
431
    def __init__(self, url):
 
432
        _scheme, _username, _password, _host, _port, _path = \
 
433
            transport.split_url(url)
 
434
        try:
 
435
            if _port is not None:
 
436
                _port = int(_port)
 
437
        except (ValueError, TypeError), e:
 
438
            raise errors.InvalidURL(path=url, extra="invalid port %s" % 
 
439
                _port)
 
440
        medium = SmartSSHClientMedium(_host, _port, _username, _password)
 
441
        super(RemoteSSHTransport, self).__init__(url, medium=medium)
 
442
 
 
443
 
 
444
class RemoteHTTPTransport(RemoteTransport):
 
445
    """Just a way to connect between a bzr+http:// url and http://.
 
446
    
 
447
    This connection operates slightly differently than the RemoteSSHTransport.
 
448
    It uses a plain http:// transport underneath, which defines what remote
 
449
    .bzr/smart URL we are connected to. From there, all paths that are sent are
 
450
    sent as relative paths, this way, the remote side can properly
 
451
    de-reference them, since it is likely doing rewrite rules to translate an
 
452
    HTTP path into a local path.
 
453
    """
 
454
 
 
455
    def __init__(self, url, http_transport=None):
 
456
        assert url.startswith('bzr+http://')
 
457
 
 
458
        if http_transport is None:
 
459
            http_url = url[len('bzr+'):]
 
460
            self._http_transport = transport.get_transport(http_url)
 
461
        else:
 
462
            self._http_transport = http_transport
 
463
        http_medium = self._http_transport.get_smart_medium()
 
464
        super(RemoteHTTPTransport, self).__init__(url, medium=http_medium)
 
465
 
 
466
    def _remote_path(self, relpath):
 
467
        """After connecting HTTP Transport only deals in relative URLs."""
 
468
        if relpath == '.':
 
469
            return ''
 
470
        else:
 
471
            return relpath
 
472
 
 
473
    def abspath(self, relpath):
 
474
        """Return the full url to the given relative path.
 
475
        
 
476
        :param relpath: the relative path or path components
 
477
        :type relpath: str or list
 
478
        """
 
479
        return self._unparse_url(self._combine_paths(self._path, relpath))
 
480
 
 
481
    def clone(self, relative_url):
 
482
        """Make a new RemoteHTTPTransport related to me.
 
483
 
 
484
        This is re-implemented rather than using the default
 
485
        RemoteTransport.clone() because we must be careful about the underlying
 
486
        http transport.
 
487
        """
 
488
        if relative_url:
 
489
            abs_url = self.abspath(relative_url)
 
490
        else:
 
491
            abs_url = self.base
 
492
        # By cloning the underlying http_transport, we are able to share the
 
493
        # connection.
 
494
        new_transport = self._http_transport.clone(relative_url)
 
495
        return RemoteHTTPTransport(abs_url, http_transport=new_transport)
 
496
 
 
497
 
 
498
def get_test_permutations():
 
499
    """Return (transport, server) permutations for testing."""
 
500
    from bzrlib.smart import server
 
501
    ### We may need a little more test framework support to construct an
 
502
    ### appropriate RemoteTransport in the future.
 
503
    return [(RemoteTCPTransport, server.SmartTCPServer_for_testing)]