65
66
method, args, body_bytes)
66
67
except errors.ErrorFromSmartServer, err:
67
68
self._translate_error(err, **err_context)
71
def response_tuple_to_repo_format(response):
72
"""Convert a response tuple describing a repository format to a format."""
73
format = RemoteRepositoryFormat()
74
format._rich_root_data = (response[0] == 'yes')
75
format._supports_tree_reference = (response[1] == 'yes')
76
format._supports_external_lookups = (response[2] == 'yes')
77
format._network_name = response[3]
69
81
# Note: RemoteBzrDirFormat is in bzrdir.py
71
83
class RemoteBzrDir(BzrDir, _RpcHelper):
72
84
"""Control directory on a remote server, accessed via bzr:// or similar."""
74
def __init__(self, transport, _client=None):
86
def __init__(self, transport, format, _client=None):
75
87
"""Construct a RemoteBzrDir.
77
89
:param _client: Private parameter for testing. Disables probing and the
78
90
use of a real bzrdir.
80
BzrDir.__init__(self, transport, RemoteBzrDirFormat())
92
BzrDir.__init__(self, transport, format)
81
93
# this object holds a delegated bzrdir that uses file-level operations
82
94
# to talk to the other side
83
95
self._real_bzrdir = None
96
# 1-shot cache for the call pattern 'create_branch; open_branch' - see
97
# create_branch for details.
98
self._next_open_branch_result = None
85
100
if _client is None:
86
101
medium = transport.get_smart_medium()
104
119
if not self._real_bzrdir:
105
120
self._real_bzrdir = BzrDir.open_from_transport(
106
121
self.root_transport, _server_formats=False)
122
self._format._network_name = \
123
self._real_bzrdir._format.network_name()
108
125
def _translate_error(self, err, **context):
109
126
_translate_error(err, bzrdir=self, **context)
111
def cloning_metadir(self, stacked=False):
128
def break_lock(self):
129
# Prevent aliasing problems in the next_open_branch_result cache.
130
# See create_branch for rationale.
131
self._next_open_branch_result = None
132
return BzrDir.break_lock(self)
134
def _vfs_cloning_metadir(self, require_stacking=False):
112
135
self._ensure_real()
113
return self._real_bzrdir.cloning_metadir(stacked)
136
return self._real_bzrdir.cloning_metadir(
137
require_stacking=require_stacking)
139
def cloning_metadir(self, require_stacking=False):
140
medium = self._client._medium
141
if medium._is_remote_before((1, 13)):
142
return self._vfs_cloning_metadir(require_stacking=require_stacking)
143
verb = 'BzrDir.cloning_metadir'
148
path = self._path_for_remote_call(self._client)
150
response = self._call(verb, path, stacking)
151
except errors.UnknownSmartMethod:
152
medium._remember_remote_is_before((1, 13))
153
return self._vfs_cloning_metadir(require_stacking=require_stacking)
154
except errors.UnknownErrorFromSmartServer, err:
155
if err.error_tuple != ('BranchReference',):
157
# We need to resolve the branch reference to determine the
158
# cloning_metadir. This causes unnecessary RPCs to open the
159
# referenced branch (and bzrdir, etc) but only when the caller
160
# didn't already resolve the branch reference.
161
referenced_branch = self.open_branch()
162
return referenced_branch.bzrdir.cloning_metadir()
163
if len(response) != 3:
164
raise errors.UnexpectedSmartServerResponse(response)
165
control_name, repo_name, branch_info = response
166
if len(branch_info) != 2:
167
raise errors.UnexpectedSmartServerResponse(response)
168
branch_ref, branch_name = branch_info
169
format = bzrdir.network_format_registry.get(control_name)
171
format.repository_format = repository.network_format_registry.get(
173
if branch_ref == 'ref':
174
# XXX: we need possible_transports here to avoid reopening the
175
# connection to the referenced location
176
ref_bzrdir = BzrDir.open(branch_name)
177
branch_format = ref_bzrdir.cloning_metadir().get_branch_format()
178
format.set_branch_format(branch_format)
179
elif branch_ref == 'branch':
181
format.set_branch_format(
182
branch.network_format_registry.get(branch_name))
184
raise errors.UnexpectedSmartServerResponse(response)
115
187
def create_repository(self, shared=False):
117
self._real_bzrdir.create_repository(shared=shared)
118
return self.open_repository()
188
# as per meta1 formats - just delegate to the format object which may
190
result = self._format.repository_format.initialize(self, shared)
191
if not isinstance(result, RemoteRepository):
192
return self.open_repository()
120
196
def destroy_repository(self):
121
197
"""See BzrDir.destroy_repository"""
146
235
def get_branch_reference(self):
147
236
"""See BzrDir.get_branch_reference()."""
237
response = self._get_branch_reference()
238
if response[0] == 'ref':
243
def _get_branch_reference(self):
148
244
path = self._path_for_remote_call(self._client)
245
medium = self._client._medium
246
if not medium._is_remote_before((1, 13)):
248
response = self._call('BzrDir.open_branchV2', path)
249
if response[0] not in ('ref', 'branch'):
250
raise errors.UnexpectedSmartServerResponse(response)
252
except errors.UnknownSmartMethod:
253
medium._remember_remote_is_before((1, 13))
149
254
response = self._call('BzrDir.open_branch', path)
150
if response[0] == 'ok':
151
if response[1] == '':
152
# branch at this location.
155
# a branch reference, use the existing BranchReference logic.
255
if response[0] != 'ok':
256
raise errors.UnexpectedSmartServerResponse(response)
257
if response[1] != '':
258
return ('ref', response[1])
158
raise errors.UnexpectedSmartServerResponse(response)
260
return ('branch', '')
160
262
def _get_tree_branch(self):
161
263
"""See BzrDir._get_tree_branch()."""
162
264
return None, self.open_branch()
164
def open_branch(self, _unsupported=False):
266
def open_branch(self, _unsupported=False, ignore_fallbacks=False):
166
268
raise NotImplementedError('unsupported flag support not implemented yet.')
167
reference_url = self.get_branch_reference()
168
if reference_url is None:
169
# branch at this location.
170
return RemoteBranch(self, self.find_repository())
269
if self._next_open_branch_result is not None:
270
# See create_branch for details.
271
result = self._next_open_branch_result
272
self._next_open_branch_result = None
274
response = self._get_branch_reference()
275
if response[0] == 'ref':
172
276
# a branch reference, use the existing BranchReference logic.
173
277
format = BranchReferenceFormat()
174
return format.open(self, _found=True, location=reference_url)
278
return format.open(self, _found=True, location=response[1],
279
ignore_fallbacks=ignore_fallbacks)
280
branch_format_name = response[1]
281
if not branch_format_name:
282
branch_format_name = None
283
format = RemoteBranchFormat(network_name=branch_format_name)
284
return RemoteBranch(self, self.find_repository(), format=format,
285
setup_stacking=not ignore_fallbacks)
287
def _open_repo_v1(self, path):
288
verb = 'BzrDir.find_repository'
289
response = self._call(verb, path)
290
if response[0] != 'ok':
291
raise errors.UnexpectedSmartServerResponse(response)
292
# servers that only support the v1 method don't support external
295
repo = self._real_bzrdir.open_repository()
296
response = response + ('no', repo._format.network_name())
297
return response, repo
299
def _open_repo_v2(self, path):
300
verb = 'BzrDir.find_repositoryV2'
301
response = self._call(verb, path)
302
if response[0] != 'ok':
303
raise errors.UnexpectedSmartServerResponse(response)
305
repo = self._real_bzrdir.open_repository()
306
response = response + (repo._format.network_name(),)
307
return response, repo
309
def _open_repo_v3(self, path):
310
verb = 'BzrDir.find_repositoryV3'
311
medium = self._client._medium
312
if medium._is_remote_before((1, 13)):
313
raise errors.UnknownSmartMethod(verb)
315
response = self._call(verb, path)
316
except errors.UnknownSmartMethod:
317
medium._remember_remote_is_before((1, 13))
319
if response[0] != 'ok':
320
raise errors.UnexpectedSmartServerResponse(response)
321
return response, None
176
323
def open_repository(self):
177
324
path = self._path_for_remote_call(self._client)
178
verb = 'BzrDir.find_repositoryV2'
180
response = self._call(verb, path)
181
except errors.UnknownSmartMethod:
182
verb = 'BzrDir.find_repository'
183
response = self._call(verb, path)
326
for probe in [self._open_repo_v3, self._open_repo_v2,
329
response, real_repo = probe(path)
331
except errors.UnknownSmartMethod:
334
raise errors.UnknownSmartMethod('BzrDir.find_repository{3,2,}')
184
335
if response[0] != 'ok':
185
336
raise errors.UnexpectedSmartServerResponse(response)
186
if verb == 'BzrDir.find_repository':
187
# servers that don't support the V2 method don't support external
189
response = response + ('no', )
190
if not (len(response) == 5):
337
if len(response) != 6:
191
338
raise SmartProtocolError('incorrect response length %s' % (response,))
192
339
if response[1] == '':
193
format = RemoteRepositoryFormat()
194
format.rich_root_data = (response[2] == 'yes')
195
format.supports_tree_reference = (response[3] == 'yes')
196
# No wire format to check this yet.
197
format.supports_external_lookups = (response[4] == 'yes')
340
# repo is at this dir.
341
format = response_tuple_to_repo_format(response[2:])
198
342
# Used to support creating a real format instance when needed.
199
343
format._creating_bzrdir = self
200
return RemoteRepository(self, format)
344
remote_repo = RemoteRepository(self, format)
345
format._creating_repo = remote_repo
346
if real_repo is not None:
347
remote_repo._set_real_repository(real_repo)
202
350
raise errors.NoRepositoryPresent(self)
257
404
the attributes rich_root_data and supports_tree_reference are set
258
405
on a per instance basis, and are not set (and should not be) at
408
:ivar _custom_format: If set, a specific concrete repository format that
409
will be used when initializing a repository with this
410
RemoteRepositoryFormat.
411
:ivar _creating_repo: If set, the repository object that this
412
RemoteRepositoryFormat was created for: it can be called into
413
to obtain data like the network name.
262
416
_matchingbzrdir = RemoteBzrDirFormat()
264
def initialize(self, a_bzrdir, shared=False):
265
if not isinstance(a_bzrdir, RemoteBzrDir):
419
repository.RepositoryFormat.__init__(self)
420
self._custom_format = None
421
self._network_name = None
422
self._creating_bzrdir = None
423
self._supports_external_lookups = None
424
self._supports_tree_reference = None
425
self._rich_root_data = None
428
def fast_deltas(self):
430
return self._custom_format.fast_deltas
433
def rich_root_data(self):
434
if self._rich_root_data is None:
436
self._rich_root_data = self._custom_format.rich_root_data
437
return self._rich_root_data
440
def supports_external_lookups(self):
441
if self._supports_external_lookups is None:
443
self._supports_external_lookups = \
444
self._custom_format.supports_external_lookups
445
return self._supports_external_lookups
448
def supports_tree_reference(self):
449
if self._supports_tree_reference is None:
451
self._supports_tree_reference = \
452
self._custom_format.supports_tree_reference
453
return self._supports_tree_reference
455
def _vfs_initialize(self, a_bzrdir, shared):
456
"""Helper for common code in initialize."""
457
if self._custom_format:
458
# Custom format requested
459
result = self._custom_format.initialize(a_bzrdir, shared=shared)
460
elif self._creating_bzrdir is not None:
461
# Use the format that the repository we were created to back
266
463
prior_repo = self._creating_bzrdir.open_repository()
267
464
prior_repo._ensure_real()
268
return prior_repo._real_repository._format.initialize(
465
result = prior_repo._real_repository._format.initialize(
269
466
a_bzrdir, shared=shared)
270
return a_bzrdir.create_repository(shared=shared)
468
# assume that a_bzr is a RemoteBzrDir but the smart server didn't
469
# support remote initialization.
470
# We delegate to a real object at this point (as RemoteBzrDir
471
# delegate to the repository format which would lead to infinite
472
# recursion if we just called a_bzrdir.create_repository.
473
a_bzrdir._ensure_real()
474
result = a_bzrdir._real_bzrdir.create_repository(shared=shared)
475
if not isinstance(result, RemoteRepository):
476
return self.open(a_bzrdir)
480
def initialize(self, a_bzrdir, shared=False):
481
# Being asked to create on a non RemoteBzrDir:
482
if not isinstance(a_bzrdir, RemoteBzrDir):
483
return self._vfs_initialize(a_bzrdir, shared)
484
medium = a_bzrdir._client._medium
485
if medium._is_remote_before((1, 13)):
486
return self._vfs_initialize(a_bzrdir, shared)
487
# Creating on a remote bzr dir.
488
# 1) get the network name to use.
489
if self._custom_format:
490
network_name = self._custom_format.network_name()
491
elif self._network_name:
492
network_name = self._network_name
494
# Select the current bzrlib default and ask for that.
495
reference_bzrdir_format = bzrdir.format_registry.get('default')()
496
reference_format = reference_bzrdir_format.repository_format
497
network_name = reference_format.network_name()
498
# 2) try direct creation via RPC
499
path = a_bzrdir._path_for_remote_call(a_bzrdir._client)
500
verb = 'BzrDir.create_repository'
506
response = a_bzrdir._call(verb, path, network_name, shared_str)
507
except errors.UnknownSmartMethod:
508
# Fallback - use vfs methods
509
medium._remember_remote_is_before((1, 13))
510
return self._vfs_initialize(a_bzrdir, shared)
512
# Turn the response into a RemoteRepository object.
513
format = response_tuple_to_repo_format(response[1:])
514
# Used to support creating a real format instance when needed.
515
format._creating_bzrdir = a_bzrdir
516
remote_repo = RemoteRepository(a_bzrdir, format)
517
format._creating_repo = remote_repo
272
520
def open(self, a_bzrdir):
273
521
if not isinstance(a_bzrdir, RemoteBzrDir):
274
522
raise AssertionError('%r is not a RemoteBzrDir' % (a_bzrdir,))
275
523
return a_bzrdir.open_repository()
525
def _ensure_real(self):
526
if self._custom_format is None:
527
self._custom_format = repository.network_format_registry.get(
531
def _fetch_order(self):
533
return self._custom_format._fetch_order
536
def _fetch_uses_deltas(self):
538
return self._custom_format._fetch_uses_deltas
541
def _fetch_reconcile(self):
543
return self._custom_format._fetch_reconcile
277
545
def get_format_description(self):
278
546
return 'bzr remote repository'
280
548
def __eq__(self, other):
281
return self.__class__ == other.__class__
549
return self.__class__ is other.__class__
283
551
def check_conversion_target(self, target_format):
284
552
if self.rich_root_data and not target_format.rich_root_data:
367
663
self._ensure_real()
368
664
return self._real_repository.commit_write_group()
666
def resume_write_group(self, tokens):
668
return self._real_repository.resume_write_group(tokens)
670
def suspend_write_group(self):
672
return self._real_repository.suspend_write_group()
674
def get_missing_parent_inventories(self, check_for_missing_texts=True):
676
return self._real_repository.get_missing_parent_inventories(
677
check_for_missing_texts=check_for_missing_texts)
679
def _get_rev_id_for_revno_vfs(self, revno, known_pair):
681
return self._real_repository.get_rev_id_for_revno(
684
def get_rev_id_for_revno(self, revno, known_pair):
685
"""See Repository.get_rev_id_for_revno."""
686
path = self.bzrdir._path_for_remote_call(self._client)
688
if self._client._medium._is_remote_before((1, 17)):
689
return self._get_rev_id_for_revno_vfs(revno, known_pair)
690
response = self._call(
691
'Repository.get_rev_id_for_revno', path, revno, known_pair)
692
except errors.UnknownSmartMethod:
693
self._client._medium._remember_remote_is_before((1, 17))
694
return self._get_rev_id_for_revno_vfs(revno, known_pair)
695
if response[0] == 'ok':
696
return True, response[1]
697
elif response[0] == 'history-incomplete':
698
known_pair = response[1:3]
699
for fallback in self._fallback_repositories:
700
found, result = fallback.get_rev_id_for_revno(revno, known_pair)
705
# Not found in any fallbacks
706
return False, known_pair
708
raise errors.UnexpectedSmartServerResponse(response)
370
710
def _ensure_real(self):
371
711
"""Ensure that there is a _real_repository set.
373
713
Used before calls to self._real_repository.
715
Note that _ensure_real causes many roundtrips to the server which are
716
not desirable, and prevents the use of smart one-roundtrip RPC's to
717
perform complex operations (such as accessing parent data, streaming
718
revisions etc). Adding calls to _ensure_real should only be done when
719
bringing up new functionality, adding fallbacks for smart methods that
720
require a fallback path, and never to replace an existing smart method
721
invocation. If in doubt chat to the bzr network team.
375
723
if self._real_repository is None:
724
if 'hpssvfs' in debug.debug_flags:
726
warning('VFS Repository access triggered\n%s',
727
''.join(traceback.format_stack()))
728
self._unstacked_provider.missing_keys.clear()
376
729
self.bzrdir._ensure_real()
377
730
self._set_real_repository(
378
731
self.bzrdir._real_bzrdir.open_repository())
432
780
for line in lines:
433
781
d = tuple(line.split())
434
782
revision_graph[d[0]] = d[1:]
436
784
return revision_graph
787
"""See Repository._get_sink()."""
788
return RemoteStreamSink(self)
790
def _get_source(self, to_format):
791
"""Return a source for streaming from this repository."""
792
return RemoteStreamSource(self, to_format)
438
795
def has_revision(self, revision_id):
439
"""See Repository.has_revision()."""
440
if revision_id == NULL_REVISION:
441
# The null revision is always present.
443
path = self.bzrdir._path_for_remote_call(self._client)
444
response = self._call('Repository.has_revision', path, revision_id)
445
if response[0] not in ('yes', 'no'):
446
raise errors.UnexpectedSmartServerResponse(response)
447
if response[0] == 'yes':
449
for fallback_repo in self._fallback_repositories:
450
if fallback_repo.has_revision(revision_id):
796
"""True if this repository has a copy of the revision."""
797
# Copy of bzrlib.repository.Repository.has_revision
798
return revision_id in self.has_revisions((revision_id,))
454
801
def has_revisions(self, revision_ids):
455
"""See Repository.has_revisions()."""
456
# FIXME: This does many roundtrips, particularly when there are
457
# fallback repositories. -- mbp 20080905
459
for revision_id in revision_ids:
460
if self.has_revision(revision_id):
461
result.add(revision_id)
802
"""Probe to find out the presence of multiple revisions.
804
:param revision_ids: An iterable of revision_ids.
805
:return: A set of the revision_ids that were present.
807
# Copy of bzrlib.repository.Repository.has_revisions
808
parent_map = self.get_parent_map(revision_ids)
809
result = set(parent_map)
810
if _mod_revision.NULL_REVISION in revision_ids:
811
result.add(_mod_revision.NULL_REVISION)
814
def _has_same_fallbacks(self, other_repo):
815
"""Returns true if the repositories have the same fallbacks."""
816
# XXX: copied from Repository; it should be unified into a base class
817
# <https://bugs.edge.launchpad.net/bzr/+bug/401622>
818
my_fb = self._fallback_repositories
819
other_fb = other_repo._fallback_repositories
820
if len(my_fb) != len(other_fb):
822
for f, g in zip(my_fb, other_fb):
823
if not f.has_same_location(g):
464
827
def has_same_location(self, other):
465
return (self.__class__ == other.__class__ and
828
# TODO: Move to RepositoryBase and unify with the regular Repository
829
# one; unfortunately the tests rely on slightly different behaviour at
830
# present -- mbp 20090710
831
return (self.__class__ is other.__class__ and
466
832
self.bzrdir.transport.base == other.bzrdir.transport.base)
468
834
def get_graph(self, other_repository=None):
604
976
implemented operations.
606
978
if self._real_repository is not None:
607
raise AssertionError('_real_repository is already set')
979
# Replacing an already set real repository.
980
# We cannot do this [currently] if the repository is locked -
981
# synchronised state might be lost.
983
raise AssertionError('_real_repository is already set')
608
984
if isinstance(repository, RemoteRepository):
609
985
raise AssertionError()
610
986
self._real_repository = repository
987
# three code paths happen here:
988
# 1) old servers, RemoteBranch.open() calls _ensure_real before setting
989
# up stacking. In this case self._fallback_repositories is [], and the
990
# real repo is already setup. Preserve the real repo and
991
# RemoteRepository.add_fallback_repository will avoid adding
993
# 2) new servers, RemoteBranch.open() sets up stacking, and when
994
# ensure_real is triggered from a branch, the real repository to
995
# set already has a matching list with separate instances, but
996
# as they are also RemoteRepositories we don't worry about making the
997
# lists be identical.
998
# 3) new servers, RemoteRepository.ensure_real is triggered before
999
# RemoteBranch.ensure real, in this case we get a repo with no fallbacks
1000
# and need to populate it.
1001
if (self._fallback_repositories and
1002
len(self._real_repository._fallback_repositories) !=
1003
len(self._fallback_repositories)):
1004
if len(self._real_repository._fallback_repositories):
1005
raise AssertionError(
1006
"cannot cleanly remove existing _fallback_repositories")
611
1007
for fb in self._fallback_repositories:
612
1008
self._real_repository.add_fallback_repository(fb)
613
1009
if self._lock_mode == 'w':
727
1129
def add_fallback_repository(self, repository):
728
1130
"""Add a repository to use for looking up data not held locally.
730
1132
:param repository: A repository.
732
# XXX: At the moment the RemoteRepository will allow fallbacks
733
# unconditionally - however, a _real_repository will usually exist,
734
# and may raise an error if it's not accommodated by the underlying
735
# format. Eventually we should check when opening the repository
736
# whether it's willing to allow them or not.
1134
if not self._format.supports_external_lookups:
1135
raise errors.UnstackableRepositoryFormat(
1136
self._format.network_name(), self.base)
738
1137
# We need to accumulate additional repositories here, to pass them in
739
1138
# on various RPC's.
1140
if self.is_locked():
1141
# We will call fallback.unlock() when we transition to the unlocked
1142
# state, so always add a lock here. If a caller passes us a locked
1143
# repository, they are responsible for unlocking it later.
1144
repository.lock_read()
740
1145
self._fallback_repositories.append(repository)
741
# They are also seen by the fallback repository. If it doesn't exist
742
# yet they'll be added then. This implicitly copies them.
1146
# If self._real_repository was parameterised already (e.g. because a
1147
# _real_branch had its get_stacked_on_url method called), then the
1148
# repository to be added may already be in the _real_repositories list.
1149
if self._real_repository is not None:
1150
fallback_locations = [repo.bzrdir.root_transport.base for repo in
1151
self._real_repository._fallback_repositories]
1152
if repository.bzrdir.root_transport.base not in fallback_locations:
1153
self._real_repository.add_fallback_repository(repository)
745
1155
def add_inventory(self, revid, inv, parents):
746
1156
self._ensure_real()
809
1233
return repository.InterRepository.get(
810
1234
other, self).search_missing_revision_ids(revision_id, find_ghosts)
812
def fetch(self, source, revision_id=None, pb=None, find_ghosts=False):
813
# Not delegated to _real_repository so that InterRepository.get has a
814
# chance to find an InterRepository specialised for RemoteRepository.
815
if self.has_same_location(source):
1236
def fetch(self, source, revision_id=None, pb=None, find_ghosts=False,
1238
# No base implementation to use as RemoteRepository is not a subclass
1239
# of Repository; so this is a copy of Repository.fetch().
1240
if fetch_spec is not None and revision_id is not None:
1241
raise AssertionError(
1242
"fetch_spec and revision_id are mutually exclusive.")
1243
if self.is_in_write_group():
1244
raise errors.InternalBzrError(
1245
"May not fetch while in a write group.")
1246
# fast path same-url fetch operations
1247
if (self.has_same_location(source)
1248
and fetch_spec is None
1249
and self._has_same_fallbacks(source)):
816
1250
# check that last_revision is in 'from' and then return a
818
1252
if (revision_id is not None and
819
1253
not revision.is_null(revision_id)):
820
1254
self.get_revision(revision_id)
1256
# if there is no specific appropriate InterRepository, this will get
1257
# the InterRepository base class, which raises an
1258
# IncompatibleRepositories when asked to fetch.
822
1259
inter = repository.InterRepository.get(source, self)
824
return inter.fetch(revision_id=revision_id, pb=pb, find_ghosts=find_ghosts)
825
except NotImplementedError:
826
raise errors.IncompatibleRepositories(source, self)
1260
return inter.fetch(revision_id=revision_id, pb=pb,
1261
find_ghosts=find_ghosts, fetch_spec=fetch_spec)
828
1263
def create_bundle(self, target, base, fileobj, format=None):
829
1264
self._ensure_real()
931
1337
# TODO: Manage this incrementally to avoid covering the same path
932
1338
# repeatedly. (The server will have to on each request, but the less
933
1339
# work done the better).
1341
# Negative caching notes:
1342
# new server sends missing when a request including the revid
1343
# 'include-missing:' is present in the request.
1344
# missing keys are serialised as missing:X, and we then call
1345
# provider.note_missing(X) for-all X
934
1346
parents_map = self._unstacked_provider.get_cached_map()
935
1347
if parents_map is None:
936
1348
# Repository is not locked, so there's no cache.
937
1349
parents_map = {}
1350
# start_set is all the keys in the cache
938
1351
start_set = set(parents_map)
1352
# result set is all the references to keys in the cache
939
1353
result_parents = set()
940
1354
for parents in parents_map.itervalues():
941
1355
result_parents.update(parents)
942
1356
stop_keys = result_parents.difference(start_set)
1357
# We don't need to send ghosts back to the server as a position to
1359
stop_keys.difference_update(self._unstacked_provider.missing_keys)
1360
key_count = len(parents_map)
1361
if (NULL_REVISION in result_parents
1362
and NULL_REVISION in self._unstacked_provider.missing_keys):
1363
# If we pruned NULL_REVISION from the stop_keys because it's also
1364
# in our cache of "missing" keys we need to increment our key count
1365
# by 1, because the reconsitituted SearchResult on the server will
1366
# still consider NULL_REVISION to be an included key.
943
1368
included_keys = start_set.intersection(result_parents)
944
1369
start_set.difference_update(included_keys)
945
recipe = (start_set, stop_keys, len(parents_map))
1370
recipe = ('manual', start_set, stop_keys, key_count)
946
1371
body = self._serialise_search_recipe(recipe)
947
1372
path = self.bzrdir._path_for_remote_call(self._client)
948
1373
for key in keys:
1210
1656
self._ensure_real()
1211
1657
self._real_repository._pack_collection.autopack()
1213
if self._real_repository is not None:
1214
# Reset the real repository's cache of pack names.
1215
# XXX: At some point we may be able to skip this and just rely on
1216
# the automatic retry logic to do the right thing, but for now we
1217
# err on the side of being correct rather than being optimal.
1218
self._real_repository._pack_collection.reload_pack_names()
1219
1660
if response[0] != 'ok':
1220
1661
raise errors.UnexpectedSmartServerResponse(response)
1664
class RemoteStreamSink(repository.StreamSink):
1666
def _insert_real(self, stream, src_format, resume_tokens):
1667
self.target_repo._ensure_real()
1668
sink = self.target_repo._real_repository._get_sink()
1669
result = sink.insert_stream(stream, src_format, resume_tokens)
1671
self.target_repo.autopack()
1674
def insert_stream(self, stream, src_format, resume_tokens):
1675
target = self.target_repo
1676
target._unstacked_provider.missing_keys.clear()
1677
if target._lock_token:
1678
verb = 'Repository.insert_stream_locked'
1679
extra_args = (target._lock_token or '',)
1680
required_version = (1, 14)
1682
verb = 'Repository.insert_stream'
1684
required_version = (1, 13)
1685
client = target._client
1686
medium = client._medium
1687
if medium._is_remote_before(required_version):
1688
# No possible way this can work.
1689
return self._insert_real(stream, src_format, resume_tokens)
1690
path = target.bzrdir._path_for_remote_call(client)
1691
if not resume_tokens:
1692
# XXX: Ugly but important for correctness, *will* be fixed during
1693
# 1.13 cycle. Pushing a stream that is interrupted results in a
1694
# fallback to the _real_repositories sink *with a partial stream*.
1695
# Thats bad because we insert less data than bzr expected. To avoid
1696
# this we do a trial push to make sure the verb is accessible, and
1697
# do not fallback when actually pushing the stream. A cleanup patch
1698
# is going to look at rewinding/restarting the stream/partial
1700
byte_stream = smart_repo._stream_to_byte_stream([], src_format)
1702
response = client.call_with_body_stream(
1703
(verb, path, '') + extra_args, byte_stream)
1704
except errors.UnknownSmartMethod:
1705
medium._remember_remote_is_before(required_version)
1706
return self._insert_real(stream, src_format, resume_tokens)
1707
byte_stream = smart_repo._stream_to_byte_stream(
1709
resume_tokens = ' '.join(resume_tokens)
1710
response = client.call_with_body_stream(
1711
(verb, path, resume_tokens) + extra_args, byte_stream)
1712
if response[0][0] not in ('ok', 'missing-basis'):
1713
raise errors.UnexpectedSmartServerResponse(response)
1714
if response[0][0] == 'missing-basis':
1715
tokens, missing_keys = bencode.bdecode_as_tuple(response[0][1])
1716
resume_tokens = tokens
1717
return resume_tokens, set(missing_keys)
1719
self.target_repo.refresh_data()
1723
class RemoteStreamSource(repository.StreamSource):
1724
"""Stream data from a remote server."""
1726
def get_stream(self, search):
1727
if (self.from_repository._fallback_repositories and
1728
self.to_format._fetch_order == 'topological'):
1729
return self._real_stream(self.from_repository, search)
1730
return self.missing_parents_chain(search, [self.from_repository] +
1731
self.from_repository._fallback_repositories)
1733
def _real_stream(self, repo, search):
1734
"""Get a stream for search from repo.
1736
This never called RemoteStreamSource.get_stream, and is a heler
1737
for RemoteStreamSource._get_stream to allow getting a stream
1738
reliably whether fallback back because of old servers or trying
1739
to stream from a non-RemoteRepository (which the stacked support
1742
source = repo._get_source(self.to_format)
1743
if isinstance(source, RemoteStreamSource):
1744
return repository.StreamSource.get_stream(source, search)
1745
return source.get_stream(search)
1747
def _get_stream(self, repo, search):
1748
"""Core worker to get a stream from repo for search.
1750
This is used by both get_stream and the stacking support logic. It
1751
deliberately gets a stream for repo which does not need to be
1752
self.from_repository. In the event that repo is not Remote, or
1753
cannot do a smart stream, a fallback is made to the generic
1754
repository._get_stream() interface, via self._real_stream.
1756
In the event of stacking, streams from _get_stream will not
1757
contain all the data for search - this is normal (see get_stream).
1759
:param repo: A repository.
1760
:param search: A search.
1762
# Fallbacks may be non-smart
1763
if not isinstance(repo, RemoteRepository):
1764
return self._real_stream(repo, search)
1765
client = repo._client
1766
medium = client._medium
1767
if medium._is_remote_before((1, 13)):
1768
# streaming was added in 1.13
1769
return self._real_stream(repo, search)
1770
path = repo.bzrdir._path_for_remote_call(client)
1772
search_bytes = repo._serialise_search_result(search)
1773
response = repo._call_with_body_bytes_expecting_body(
1774
'Repository.get_stream',
1775
(path, self.to_format.network_name()), search_bytes)
1776
response_tuple, response_handler = response
1777
except errors.UnknownSmartMethod:
1778
medium._remember_remote_is_before((1,13))
1779
return self._real_stream(repo, search)
1780
if response_tuple[0] != 'ok':
1781
raise errors.UnexpectedSmartServerResponse(response_tuple)
1782
byte_stream = response_handler.read_streamed_body()
1783
src_format, stream = smart_repo._byte_stream_to_stream(byte_stream)
1784
if src_format.network_name() != repo._format.network_name():
1785
raise AssertionError(
1786
"Mismatched RemoteRepository and stream src %r, %r" % (
1787
src_format.network_name(), repo._format.network_name()))
1790
def missing_parents_chain(self, search, sources):
1791
"""Chain multiple streams together to handle stacking.
1793
:param search: The overall search to satisfy with streams.
1794
:param sources: A list of Repository objects to query.
1796
self.serialiser = self.to_format._serializer
1797
self.seen_revs = set()
1798
self.referenced_revs = set()
1799
# If there are heads in the search, or the key count is > 0, we are not
1801
while not search.is_empty() and len(sources) > 1:
1802
source = sources.pop(0)
1803
stream = self._get_stream(source, search)
1804
for kind, substream in stream:
1805
if kind != 'revisions':
1806
yield kind, substream
1808
yield kind, self.missing_parents_rev_handler(substream)
1809
search = search.refine(self.seen_revs, self.referenced_revs)
1810
self.seen_revs = set()
1811
self.referenced_revs = set()
1812
if not search.is_empty():
1813
for kind, stream in self._get_stream(sources[0], search):
1816
def missing_parents_rev_handler(self, substream):
1817
for content in substream:
1818
revision_bytes = content.get_bytes_as('fulltext')
1819
revision = self.serialiser.read_revision_from_string(revision_bytes)
1820
self.seen_revs.add(content.key[-1])
1821
self.referenced_revs.update(revision.parent_ids)
1223
1825
class RemoteBranchLockableFiles(LockableFiles):
1224
1826
"""A 'LockableFiles' implementation that talks to a smart server.
1226
1828
This is not a public interface class.
1243
1845
class RemoteBranchFormat(branch.BranchFormat):
1847
def __init__(self, network_name=None):
1246
1848
super(RemoteBranchFormat, self).__init__()
1247
1849
self._matchingbzrdir = RemoteBzrDirFormat()
1248
1850
self._matchingbzrdir.set_branch_format(self)
1851
self._custom_format = None
1852
self._network_name = network_name
1250
1854
def __eq__(self, other):
1251
return (isinstance(other, RemoteBranchFormat) and
1855
return (isinstance(other, RemoteBranchFormat) and
1252
1856
self.__dict__ == other.__dict__)
1858
def _ensure_real(self):
1859
if self._custom_format is None:
1860
self._custom_format = branch.network_format_registry.get(
1254
1863
def get_format_description(self):
1255
1864
return 'Remote BZR Branch'
1257
def get_format_string(self):
1258
return 'Remote BZR Branch'
1260
def open(self, a_bzrdir):
1261
return a_bzrdir.open_branch()
1866
def network_name(self):
1867
return self._network_name
1869
def open(self, a_bzrdir, ignore_fallbacks=False):
1870
return a_bzrdir.open_branch(ignore_fallbacks=ignore_fallbacks)
1872
def _vfs_initialize(self, a_bzrdir):
1873
# Initialisation when using a local bzrdir object, or a non-vfs init
1874
# method is not available on the server.
1875
# self._custom_format is always set - the start of initialize ensures
1877
if isinstance(a_bzrdir, RemoteBzrDir):
1878
a_bzrdir._ensure_real()
1879
result = self._custom_format.initialize(a_bzrdir._real_bzrdir)
1881
# We assume the bzrdir is parameterised; it may not be.
1882
result = self._custom_format.initialize(a_bzrdir)
1883
if (isinstance(a_bzrdir, RemoteBzrDir) and
1884
not isinstance(result, RemoteBranch)):
1885
result = RemoteBranch(a_bzrdir, a_bzrdir.find_repository(), result)
1263
1888
def initialize(self, a_bzrdir):
1264
return a_bzrdir.create_branch()
1889
# 1) get the network name to use.
1890
if self._custom_format:
1891
network_name = self._custom_format.network_name()
1893
# Select the current bzrlib default and ask for that.
1894
reference_bzrdir_format = bzrdir.format_registry.get('default')()
1895
reference_format = reference_bzrdir_format.get_branch_format()
1896
self._custom_format = reference_format
1897
network_name = reference_format.network_name()
1898
# Being asked to create on a non RemoteBzrDir:
1899
if not isinstance(a_bzrdir, RemoteBzrDir):
1900
return self._vfs_initialize(a_bzrdir)
1901
medium = a_bzrdir._client._medium
1902
if medium._is_remote_before((1, 13)):
1903
return self._vfs_initialize(a_bzrdir)
1904
# Creating on a remote bzr dir.
1905
# 2) try direct creation via RPC
1906
path = a_bzrdir._path_for_remote_call(a_bzrdir._client)
1907
verb = 'BzrDir.create_branch'
1909
response = a_bzrdir._call(verb, path, network_name)
1910
except errors.UnknownSmartMethod:
1911
# Fallback - use vfs methods
1912
medium._remember_remote_is_before((1, 13))
1913
return self._vfs_initialize(a_bzrdir)
1914
if response[0] != 'ok':
1915
raise errors.UnexpectedSmartServerResponse(response)
1916
# Turn the response into a RemoteRepository object.
1917
format = RemoteBranchFormat(network_name=response[1])
1918
repo_format = response_tuple_to_repo_format(response[3:])
1919
if response[2] == '':
1920
repo_bzrdir = a_bzrdir
1922
repo_bzrdir = RemoteBzrDir(
1923
a_bzrdir.root_transport.clone(response[2]), a_bzrdir._format,
1925
remote_repo = RemoteRepository(repo_bzrdir, repo_format)
1926
remote_branch = RemoteBranch(a_bzrdir, remote_repo,
1927
format=format, setup_stacking=False)
1928
# XXX: We know this is a new branch, so it must have revno 0, revid
1929
# NULL_REVISION. Creating the branch locked would make this be unable
1930
# to be wrong; here its simply very unlikely to be wrong. RBC 20090225
1931
remote_branch._last_revision_info_cache = 0, NULL_REVISION
1932
return remote_branch
1934
def make_tags(self, branch):
1936
return self._custom_format.make_tags(branch)
1266
1938
def supports_tags(self):
1267
1939
# Remote branches might support tags, but we won't know until we
1268
1940
# access the real remote branch.
1942
return self._custom_format.supports_tags()
1944
def supports_stacking(self):
1946
return self._custom_format.supports_stacking()
1948
def supports_set_append_revisions_only(self):
1950
return self._custom_format.supports_set_append_revisions_only()
1272
1953
class RemoteBranch(branch.Branch, _RpcHelper):
1590
2342
raise errors.UnexpectedSmartServerResponse(response)
1591
2343
new_revno, new_revision_id = response[1:]
1592
2344
self._last_revision_info_cache = new_revno, new_revision_id
2345
self._run_post_change_branch_tip_hooks(old_revno, old_revid)
1593
2346
if self._real_branch is not None:
1594
2347
cache = new_revno, new_revision_id
1595
2348
self._real_branch._last_revision_info_cache = cache
1597
2350
def _set_last_revision(self, revision_id):
2351
old_revno, old_revid = self.last_revision_info()
2352
# This performs additional work to meet the hook contract; while its
2353
# undesirable, we have to synthesise the revno to call the hook, and
2354
# not calling the hook is worse as it means changes can't be prevented.
2355
# Having calculated this though, we can't just call into
2356
# set_last_revision_info as a simple call, because there is a set_rh
2357
# hook that some folk may still be using.
2358
history = self._lefthand_history(revision_id)
2359
self._run_pre_change_branch_tip_hooks(len(history), revision_id)
1598
2360
self._clear_cached_state()
1599
2361
response = self._call('Branch.set_last_revision',
1600
2362
self._remote_path(), self._lock_token, self._repo_lock_token,
1602
2364
if response != ('ok',):
1603
2365
raise errors.UnexpectedSmartServerResponse(response)
2366
self._run_post_change_branch_tip_hooks(old_revno, old_revid)
1605
2368
@needs_write_lock
1606
2369
def set_revision_history(self, rev_history):
1613
2376
rev_id = rev_history[-1]
1614
2377
self._set_last_revision(rev_id)
2378
for hook in branch.Branch.hooks['set_rh']:
2379
hook(self, rev_history)
1615
2380
self._cache_revision_history(rev_history)
1617
def get_parent(self):
1619
return self._real_branch.get_parent()
1621
def set_parent(self, url):
1623
return self._real_branch.set_parent(url)
1625
def set_stacked_on_url(self, stacked_location):
1626
"""Set the URL this branch is stacked against.
1628
:raises UnstackableBranchFormat: If the branch does not support
1630
:raises UnstackableRepositoryFormat: If the repository does not support
1634
return self._real_branch.set_stacked_on_url(stacked_location)
1636
def sprout(self, to_bzrdir, revision_id=None):
1637
branch_format = to_bzrdir._format._branch_format
1638
if (branch_format is None or
1639
isinstance(branch_format, RemoteBranchFormat)):
1640
# The to_bzrdir specifies RemoteBranchFormat (or no format, which
1641
# implies the same thing), but RemoteBranches can't be created at
1642
# arbitrary URLs. So create a branch in the same format as
1643
# _real_branch instead.
1644
# XXX: if to_bzrdir is a RemoteBzrDir, this should perhaps do
1645
# to_bzrdir.create_branch to create a RemoteBranch after all...
1647
result = self._real_branch._format.initialize(to_bzrdir)
1648
self.copy_content_into(result, revision_id=revision_id)
1649
result.set_parent(self.bzrdir.root_transport.base)
1651
result = branch.Branch.sprout(
1652
self, to_bzrdir, revision_id=revision_id)
2382
def _get_parent_location(self):
2383
medium = self._client._medium
2384
if medium._is_remote_before((1, 13)):
2385
return self._vfs_get_parent_location()
2387
response = self._call('Branch.get_parent', self._remote_path())
2388
except errors.UnknownSmartMethod:
2389
medium._remember_remote_is_before((1, 13))
2390
return self._vfs_get_parent_location()
2391
if len(response) != 1:
2392
raise errors.UnexpectedSmartServerResponse(response)
2393
parent_location = response[0]
2394
if parent_location == '':
2396
return parent_location
2398
def _vfs_get_parent_location(self):
2400
return self._real_branch._get_parent_location()
2402
def _set_parent_location(self, url):
2403
medium = self._client._medium
2404
if medium._is_remote_before((1, 15)):
2405
return self._vfs_set_parent_location(url)
2407
call_url = url or ''
2408
if type(call_url) is not str:
2409
raise AssertionError('url must be a str or None (%s)' % url)
2410
response = self._call('Branch.set_parent_location',
2411
self._remote_path(), self._lock_token, self._repo_lock_token,
2413
except errors.UnknownSmartMethod:
2414
medium._remember_remote_is_before((1, 15))
2415
return self._vfs_set_parent_location(url)
2417
raise errors.UnexpectedSmartServerResponse(response)
2419
def _vfs_set_parent_location(self, url):
2421
return self._real_branch._set_parent_location(url)
1655
2423
@needs_write_lock
1656
2424
def pull(self, source, overwrite=False, stop_revision=None,
1711
2484
except errors.UnknownSmartMethod:
1712
2485
medium._remember_remote_is_before((1, 6))
1713
2486
self._clear_cached_state_of_remote_branch_only()
1715
self._real_branch.generate_revision_history(
1716
revision_id, last_rev=last_rev, other_branch=other_branch)
1721
return self._real_branch.tags
2487
self.set_revision_history(self._lefthand_history(revision_id,
2488
last_rev=last_rev,other_branch=other_branch))
1723
2490
def set_push_location(self, location):
1724
2491
self._ensure_real()
1725
2492
return self._real_branch.set_push_location(location)
1728
def update_revisions(self, other, stop_revision=None, overwrite=False,
1730
"""See Branch.update_revisions."""
2495
class RemoteConfig(object):
2496
"""A Config that reads and writes from smart verbs.
2498
It is a low-level object that considers config data to be name/value pairs
2499
that may be associated with a section. Assigning meaning to the these
2500
values is done at higher levels like bzrlib.config.TreeConfig.
2503
def get_option(self, name, section=None, default=None):
2504
"""Return the value associated with a named option.
2506
:param name: The name of the value
2507
:param section: The section the option is in (if any)
2508
:param default: The value to return if the value is not set
2509
:return: The value or default value
1733
if stop_revision is None:
1734
stop_revision = other.last_revision()
1735
if revision.is_null(stop_revision):
1736
# if there are no commits, we're done.
1738
self.fetch(other, stop_revision)
1741
# Just unconditionally set the new revision. We don't care if
1742
# the branches have diverged.
1743
self._set_last_revision(stop_revision)
2512
configobj = self._get_configobj()
2514
section_obj = configobj
1745
medium = self._client._medium
1746
if not medium._is_remote_before((1, 6)):
1748
self._set_last_revision_descendant(stop_revision, other)
1750
except errors.UnknownSmartMethod:
1751
medium._remember_remote_is_before((1, 6))
1752
# Fallback for pre-1.6 servers: check for divergence
1753
# client-side, then do _set_last_revision.
1754
last_rev = revision.ensure_null(self.last_revision())
1756
graph = self.repository.get_graph()
1757
if self._check_if_descendant_or_diverged(
1758
stop_revision, last_rev, graph, other):
1759
# stop_revision is a descendant of last_rev, but we aren't
1760
# overwriting, so we're done.
1762
self._set_last_revision(stop_revision)
2517
section_obj = configobj[section]
2520
return section_obj.get(name, default)
2521
except errors.UnknownSmartMethod:
2522
return self._vfs_get_option(name, section, default)
2524
def _response_to_configobj(self, response):
2525
if len(response[0]) and response[0][0] != 'ok':
2526
raise errors.UnexpectedSmartServerResponse(response)
2527
lines = response[1].read_body_bytes().splitlines()
2528
return config.ConfigObj(lines, encoding='utf-8')
2531
class RemoteBranchConfig(RemoteConfig):
2532
"""A RemoteConfig for Branches."""
2534
def __init__(self, branch):
2535
self._branch = branch
2537
def _get_configobj(self):
2538
path = self._branch._remote_path()
2539
response = self._branch._client.call_expecting_body(
2540
'Branch.get_config_file', path)
2541
return self._response_to_configobj(response)
2543
def set_option(self, value, name, section=None):
2544
"""Set the value associated with a named option.
2546
:param value: The value to set
2547
:param name: The name of the value to set
2548
:param section: The section the option is in (if any)
2550
medium = self._branch._client._medium
2551
if medium._is_remote_before((1, 14)):
2552
return self._vfs_set_option(value, name, section)
2554
path = self._branch._remote_path()
2555
response = self._branch._client.call('Branch.set_config_option',
2556
path, self._branch._lock_token, self._branch._repo_lock_token,
2557
value.encode('utf8'), name, section or '')
2558
except errors.UnknownSmartMethod:
2559
medium._remember_remote_is_before((1, 14))
2560
return self._vfs_set_option(value, name, section)
2562
raise errors.UnexpectedSmartServerResponse(response)
2564
def _real_object(self):
2565
self._branch._ensure_real()
2566
return self._branch._real_branch
2568
def _vfs_set_option(self, value, name, section=None):
2569
return self._real_object()._get_config().set_option(
2570
value, name, section)
2573
class RemoteBzrDirConfig(RemoteConfig):
2574
"""A RemoteConfig for BzrDirs."""
2576
def __init__(self, bzrdir):
2577
self._bzrdir = bzrdir
2579
def _get_configobj(self):
2580
medium = self._bzrdir._client._medium
2581
verb = 'BzrDir.get_config_file'
2582
if medium._is_remote_before((1, 15)):
2583
raise errors.UnknownSmartMethod(verb)
2584
path = self._bzrdir._path_for_remote_call(self._bzrdir._client)
2585
response = self._bzrdir._call_expecting_body(
2587
return self._response_to_configobj(response)
2589
def _vfs_get_option(self, name, section, default):
2590
return self._real_object()._get_config().get_option(
2591
name, section, default)
2593
def set_option(self, value, name, section=None):
2594
"""Set the value associated with a named option.
2596
:param value: The value to set
2597
:param name: The name of the value to set
2598
:param section: The section the option is in (if any)
2600
return self._real_object()._get_config().set_option(
2601
value, name, section)
2603
def _real_object(self):
2604
self._bzrdir._ensure_real()
2605
return self._bzrdir._real_bzrdir
1767
2609
def _extract_tar(tar, to_dir):