1
# Copyright (C) 2005, 2006, 2007, 2008 Canonical Ltd
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.
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.
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
20
from bzrlib.lazy_import import lazy_import
21
lazy_import(globals(), """
22
from itertools import izip
36
from bzrlib.index import (
40
GraphIndexPrefixAdapter,
43
from bzrlib.knit import (
49
from bzrlib import tsort
59
from bzrlib.decorators import needs_write_lock
60
from bzrlib.btree_index import (
64
from bzrlib.index import (
68
from bzrlib.repofmt.knitrepo import KnitRepository
69
from bzrlib.repository import (
71
MetaDirRepositoryFormat,
75
import bzrlib.revision as _mod_revision
76
from bzrlib.trace import (
82
class PackCommitBuilder(CommitBuilder):
83
"""A subclass of CommitBuilder to add texts with pack semantics.
85
Specifically this uses one knit object rather than one knit object per
86
added text, reducing memory and object pressure.
89
def __init__(self, repository, parents, config, timestamp=None,
90
timezone=None, committer=None, revprops=None,
92
CommitBuilder.__init__(self, repository, parents, config,
93
timestamp=timestamp, timezone=timezone, committer=committer,
94
revprops=revprops, revision_id=revision_id)
95
self._file_graph = graph.Graph(
96
repository._pack_collection.text_index.combined_index)
98
def _heads(self, file_id, revision_ids):
99
keys = [(file_id, revision_id) for revision_id in revision_ids]
100
return set([key[1] for key in self._file_graph.heads(keys)])
103
class PackRootCommitBuilder(RootCommitBuilder):
104
"""A subclass of RootCommitBuilder to add texts with pack semantics.
106
Specifically this uses one knit object rather than one knit object per
107
added text, reducing memory and object pressure.
110
def __init__(self, repository, parents, config, timestamp=None,
111
timezone=None, committer=None, revprops=None,
113
CommitBuilder.__init__(self, repository, parents, config,
114
timestamp=timestamp, timezone=timezone, committer=committer,
115
revprops=revprops, revision_id=revision_id)
116
self._file_graph = graph.Graph(
117
repository._pack_collection.text_index.combined_index)
119
def _heads(self, file_id, revision_ids):
120
keys = [(file_id, revision_id) for revision_id in revision_ids]
121
return set([key[1] for key in self._file_graph.heads(keys)])
125
"""An in memory proxy for a pack and its indices.
127
This is a base class that is not directly used, instead the classes
128
ExistingPack and NewPack are used.
131
# A map of index 'type' to the file extension and position in the
133
index_definitions = {
134
'revision': ('.rix', 0),
135
'inventory': ('.iix', 1),
137
'signature': ('.six', 3),
140
def __init__(self, revision_index, inventory_index, text_index,
142
"""Create a pack instance.
144
:param revision_index: A GraphIndex for determining what revisions are
145
present in the Pack and accessing the locations of their texts.
146
:param inventory_index: A GraphIndex for determining what inventories are
147
present in the Pack and accessing the locations of their
149
:param text_index: A GraphIndex for determining what file texts
150
are present in the pack and accessing the locations of their
151
texts/deltas (via (fileid, revisionid) tuples).
152
:param signature_index: A GraphIndex for determining what signatures are
153
present in the Pack and accessing the locations of their texts.
155
self.revision_index = revision_index
156
self.inventory_index = inventory_index
157
self.text_index = text_index
158
self.signature_index = signature_index
160
def access_tuple(self):
161
"""Return a tuple (transport, name) for the pack content."""
162
return self.pack_transport, self.file_name()
164
def _check_references(self):
165
"""Make sure our external references are present.
167
Packs are allowed to have deltas whose base is not in the pack, but it
168
must be present somewhere in this collection. It is not allowed to
169
have deltas based on a fallback repository.
170
(See <https://bugs.launchpad.net/bzr/+bug/288751>)
173
for (index_name, external_refs, index) in [
175
self._get_external_refs(self.text_index),
176
self._pack_collection.text_index.combined_index),
178
self._get_external_refs(self.inventory_index),
179
self._pack_collection.inventory_index.combined_index),
181
missing = external_refs.difference(
182
k for (idx, k, v, r) in
183
index.iter_entries(external_refs))
185
missing_items[index_name] = sorted(list(missing))
187
from pprint import pformat
188
raise errors.BzrCheckError(
189
"Newly created pack file %r has delta references to "
190
"items not in its repository:\n%s"
191
% (self, pformat(missing_items)))
194
"""Get the file name for the pack on disk."""
195
return self.name + '.pack'
197
def get_revision_count(self):
198
return self.revision_index.key_count()
200
def index_name(self, index_type, name):
201
"""Get the disk name of an index type for pack name 'name'."""
202
return name + Pack.index_definitions[index_type][0]
204
def index_offset(self, index_type):
205
"""Get the position in a index_size array for a given index type."""
206
return Pack.index_definitions[index_type][1]
208
def inventory_index_name(self, name):
209
"""The inv index is the name + .iix."""
210
return self.index_name('inventory', name)
212
def revision_index_name(self, name):
213
"""The revision index is the name + .rix."""
214
return self.index_name('revision', name)
216
def signature_index_name(self, name):
217
"""The signature index is the name + .six."""
218
return self.index_name('signature', name)
220
def text_index_name(self, name):
221
"""The text index is the name + .tix."""
222
return self.index_name('text', name)
224
def _replace_index_with_readonly(self, index_type):
225
setattr(self, index_type + '_index',
226
self.index_class(self.index_transport,
227
self.index_name(index_type, self.name),
228
self.index_sizes[self.index_offset(index_type)]))
231
class ExistingPack(Pack):
232
"""An in memory proxy for an existing .pack and its disk indices."""
234
def __init__(self, pack_transport, name, revision_index, inventory_index,
235
text_index, signature_index):
236
"""Create an ExistingPack object.
238
:param pack_transport: The transport where the pack file resides.
239
:param name: The name of the pack on disk in the pack_transport.
241
Pack.__init__(self, revision_index, inventory_index, text_index,
244
self.pack_transport = pack_transport
245
if None in (revision_index, inventory_index, text_index,
246
signature_index, name, pack_transport):
247
raise AssertionError()
249
def __eq__(self, other):
250
return self.__dict__ == other.__dict__
252
def __ne__(self, other):
253
return not self.__eq__(other)
256
return "<%s.%s object at 0x%x, %s, %s" % (
257
self.__class__.__module__, self.__class__.__name__, id(self),
258
self.pack_transport, self.name)
261
class ResumedPack(ExistingPack):
263
def __init__(self, name, revision_index, inventory_index, text_index,
264
signature_index, upload_transport, pack_transport, index_transport,
266
"""Create a ResumedPack object."""
267
ExistingPack.__init__(self, pack_transport, name, revision_index,
268
inventory_index, text_index, signature_index)
269
self.upload_transport = upload_transport
270
self.index_transport = index_transport
271
self.index_sizes = [None, None, None, None]
273
('revision', revision_index),
274
('inventory', inventory_index),
275
('text', text_index),
276
('signature', signature_index),
278
for index_type, index in indices:
279
offset = self.index_offset(index_type)
280
self.index_sizes[offset] = index._size
281
self.index_class = pack_collection._index_class
282
self._pack_collection = pack_collection
283
self._state = 'resumed'
284
# XXX: perhaps check that the .pack file exists?
286
def access_tuple(self):
287
if self._state == 'finished':
288
return Pack.access_tuple(self)
289
elif self._state == 'resumed':
290
return self.upload_transport, self.file_name()
292
raise AssertionError(self._state)
295
self.upload_transport.delete(self.file_name())
296
indices = [self.revision_index, self.inventory_index, self.text_index,
297
self.signature_index]
298
for index in indices:
299
index._transport.delete(index._name)
302
self._check_references()
303
new_name = '../packs/' + self.file_name()
304
self.upload_transport.rename(self.file_name(), new_name)
305
for index_type in ['revision', 'inventory', 'text', 'signature']:
306
old_name = self.index_name(index_type, self.name)
307
new_name = '../indices/' + old_name
308
self.upload_transport.rename(old_name, new_name)
309
self._replace_index_with_readonly(index_type)
310
self._state = 'finished'
312
def _get_external_refs(self, index):
313
return index.external_references(1)
317
"""An in memory proxy for a pack which is being created."""
319
def __init__(self, pack_collection, upload_suffix='', file_mode=None):
320
"""Create a NewPack instance.
322
:param pack_collection: A PackCollection into which this is being inserted.
323
:param upload_suffix: An optional suffix to be given to any temporary
324
files created during the pack creation. e.g '.autopack'
325
:param file_mode: Unix permissions for newly created file.
327
# The relative locations of the packs are constrained, but all are
328
# passed in because the caller has them, so as to avoid object churn.
329
index_builder_class = pack_collection._index_builder_class
331
# Revisions: parents list, no text compression.
332
index_builder_class(reference_lists=1),
333
# Inventory: We want to map compression only, but currently the
334
# knit code hasn't been updated enough to understand that, so we
335
# have a regular 2-list index giving parents and compression
337
index_builder_class(reference_lists=2),
338
# Texts: compression and per file graph, for all fileids - so two
339
# reference lists and two elements in the key tuple.
340
index_builder_class(reference_lists=2, key_elements=2),
341
# Signatures: Just blobs to store, no compression, no parents
343
index_builder_class(reference_lists=0),
345
self._pack_collection = pack_collection
346
# When we make readonly indices, we need this.
347
self.index_class = pack_collection._index_class
348
# where should the new pack be opened
349
self.upload_transport = pack_collection._upload_transport
350
# where are indices written out to
351
self.index_transport = pack_collection._index_transport
352
# where is the pack renamed to when it is finished?
353
self.pack_transport = pack_collection._pack_transport
354
# What file mode to upload the pack and indices with.
355
self._file_mode = file_mode
356
# tracks the content written to the .pack file.
357
self._hash = osutils.md5()
358
# a four-tuple with the length in bytes of the indices, once the pack
359
# is finalised. (rev, inv, text, sigs)
360
self.index_sizes = None
361
# How much data to cache when writing packs. Note that this is not
362
# synchronised with reads, because it's not in the transport layer, so
363
# is not safe unless the client knows it won't be reading from the pack
365
self._cache_limit = 0
366
# the temporary pack file name.
367
self.random_name = osutils.rand_chars(20) + upload_suffix
368
# when was this pack started ?
369
self.start_time = time.time()
370
# open an output stream for the data added to the pack.
371
self.write_stream = self.upload_transport.open_write_stream(
372
self.random_name, mode=self._file_mode)
373
if 'pack' in debug.debug_flags:
374
mutter('%s: create_pack: pack stream open: %s%s t+%6.3fs',
375
time.ctime(), self.upload_transport.base, self.random_name,
376
time.time() - self.start_time)
377
# A list of byte sequences to be written to the new pack, and the
378
# aggregate size of them. Stored as a list rather than separate
379
# variables so that the _write_data closure below can update them.
380
self._buffer = [[], 0]
381
# create a callable for adding data
383
# robertc says- this is a closure rather than a method on the object
384
# so that the variables are locals, and faster than accessing object
386
def _write_data(bytes, flush=False, _buffer=self._buffer,
387
_write=self.write_stream.write, _update=self._hash.update):
388
_buffer[0].append(bytes)
389
_buffer[1] += len(bytes)
391
if _buffer[1] > self._cache_limit or flush:
392
bytes = ''.join(_buffer[0])
396
# expose this on self, for the occasion when clients want to add data.
397
self._write_data = _write_data
398
# a pack writer object to serialise pack records.
399
self._writer = pack.ContainerWriter(self._write_data)
401
# what state is the pack in? (open, finished, aborted)
405
"""Cancel creating this pack."""
406
self._state = 'aborted'
407
self.write_stream.close()
408
# Remove the temporary pack file.
409
self.upload_transport.delete(self.random_name)
410
# The indices have no state on disk.
412
def access_tuple(self):
413
"""Return a tuple (transport, name) for the pack content."""
414
if self._state == 'finished':
415
return Pack.access_tuple(self)
416
elif self._state == 'open':
417
return self.upload_transport, self.random_name
419
raise AssertionError(self._state)
421
def data_inserted(self):
422
"""True if data has been added to this pack."""
423
return bool(self.get_revision_count() or
424
self.inventory_index.key_count() or
425
self.text_index.key_count() or
426
self.signature_index.key_count())
428
def finish(self, suspend=False):
429
"""Finish the new pack.
432
- finalises the content
433
- assigns a name (the md5 of the content, currently)
434
- writes out the associated indices
435
- renames the pack into place.
436
- stores the index size tuple for the pack in the index_sizes
441
self._write_data('', flush=True)
442
self.name = self._hash.hexdigest()
444
self._check_references()
446
# XXX: It'd be better to write them all to temporary names, then
447
# rename them all into place, so that the window when only some are
448
# visible is smaller. On the other hand none will be seen until
449
# they're in the names list.
450
self.index_sizes = [None, None, None, None]
451
self._write_index('revision', self.revision_index, 'revision', suspend)
452
self._write_index('inventory', self.inventory_index, 'inventory',
454
self._write_index('text', self.text_index, 'file texts', suspend)
455
self._write_index('signature', self.signature_index,
456
'revision signatures', suspend)
457
self.write_stream.close()
458
# Note that this will clobber an existing pack with the same name,
459
# without checking for hash collisions. While this is undesirable this
460
# is something that can be rectified in a subsequent release. One way
461
# to rectify it may be to leave the pack at the original name, writing
462
# its pack-names entry as something like 'HASH: index-sizes
463
# temporary-name'. Allocate that and check for collisions, if it is
464
# collision free then rename it into place. If clients know this scheme
465
# they can handle missing-file errors by:
466
# - try for HASH.pack
467
# - try for temporary-name
468
# - refresh the pack-list to see if the pack is now absent
469
new_name = self.name + '.pack'
471
new_name = '../packs/' + new_name
472
self.upload_transport.rename(self.random_name, new_name)
473
self._state = 'finished'
474
if 'pack' in debug.debug_flags:
475
# XXX: size might be interesting?
476
mutter('%s: create_pack: pack finished: %s%s->%s t+%6.3fs',
477
time.ctime(), self.upload_transport.base, self.random_name,
478
new_name, time.time() - self.start_time)
481
"""Flush any current data."""
483
bytes = ''.join(self._buffer[0])
484
self.write_stream.write(bytes)
485
self._hash.update(bytes)
486
self._buffer[:] = [[], 0]
488
def _get_external_refs(self, index):
489
return index._external_references()
491
def set_write_cache_size(self, size):
492
self._cache_limit = size
494
def _write_index(self, index_type, index, label, suspend=False):
495
"""Write out an index.
497
:param index_type: The type of index to write - e.g. 'revision'.
498
:param index: The index object to serialise.
499
:param label: What label to give the index e.g. 'revision'.
501
index_name = self.index_name(index_type, self.name)
503
transport = self.upload_transport
505
transport = self.index_transport
506
self.index_sizes[self.index_offset(index_type)] = transport.put_file(
507
index_name, index.finish(), mode=self._file_mode)
508
if 'pack' in debug.debug_flags:
509
# XXX: size might be interesting?
510
mutter('%s: create_pack: wrote %s index: %s%s t+%6.3fs',
511
time.ctime(), label, self.upload_transport.base,
512
self.random_name, time.time() - self.start_time)
513
# Replace the writable index on this object with a readonly,
514
# presently unloaded index. We should alter
515
# the index layer to make its finish() error if add_node is
516
# subsequently used. RBC
517
self._replace_index_with_readonly(index_type)
520
class AggregateIndex(object):
521
"""An aggregated index for the RepositoryPackCollection.
523
AggregateIndex is reponsible for managing the PackAccess object,
524
Index-To-Pack mapping, and all indices list for a specific type of index
525
such as 'revision index'.
527
A CombinedIndex provides an index on a single key space built up
528
from several on-disk indices. The AggregateIndex builds on this
529
to provide a knit access layer, and allows having up to one writable
530
index within the collection.
532
# XXX: Probably 'can be written to' could/should be separated from 'acts
533
# like a knit index' -- mbp 20071024
535
def __init__(self, reload_func=None):
536
"""Create an AggregateIndex.
538
:param reload_func: A function to call if we find we are missing an
539
index. Should have the form reload_func() => True if the list of
540
active pack files has changed.
542
self._reload_func = reload_func
543
self.index_to_pack = {}
544
self.combined_index = CombinedGraphIndex([], reload_func=reload_func)
545
self.data_access = _DirectPackAccess(self.index_to_pack,
546
reload_func=reload_func)
547
self.add_callback = None
549
def replace_indices(self, index_to_pack, indices):
550
"""Replace the current mappings with fresh ones.
552
This should probably not be used eventually, rather incremental add and
553
removal of indices. It has been added during refactoring of existing
556
:param index_to_pack: A mapping from index objects to
557
(transport, name) tuples for the pack file data.
558
:param indices: A list of indices.
560
# refresh the revision pack map dict without replacing the instance.
561
self.index_to_pack.clear()
562
self.index_to_pack.update(index_to_pack)
563
# XXX: API break - clearly a 'replace' method would be good?
564
self.combined_index._indices[:] = indices
565
# the current add nodes callback for the current writable index if
567
self.add_callback = None
569
def add_index(self, index, pack):
570
"""Add index to the aggregate, which is an index for Pack pack.
572
Future searches on the aggregate index will seach this new index
573
before all previously inserted indices.
575
:param index: An Index for the pack.
576
:param pack: A Pack instance.
578
# expose it to the index map
579
self.index_to_pack[index] = pack.access_tuple()
580
# put it at the front of the linear index list
581
self.combined_index.insert_index(0, index)
583
def add_writable_index(self, index, pack):
584
"""Add an index which is able to have data added to it.
586
There can be at most one writable index at any time. Any
587
modifications made to the knit are put into this index.
589
:param index: An index from the pack parameter.
590
:param pack: A Pack instance.
592
if self.add_callback is not None:
593
raise AssertionError(
594
"%s already has a writable index through %s" % \
595
(self, self.add_callback))
596
# allow writing: queue writes to a new index
597
self.add_index(index, pack)
598
# Updates the index to packs mapping as a side effect,
599
self.data_access.set_writer(pack._writer, index, pack.access_tuple())
600
self.add_callback = index.add_nodes
603
"""Reset all the aggregate data to nothing."""
604
self.data_access.set_writer(None, None, (None, None))
605
self.index_to_pack.clear()
606
del self.combined_index._indices[:]
607
self.add_callback = None
609
def remove_index(self, index, pack):
610
"""Remove index from the indices used to answer queries.
612
:param index: An index from the pack parameter.
613
:param pack: A Pack instance.
615
del self.index_to_pack[index]
616
self.combined_index._indices.remove(index)
617
if (self.add_callback is not None and
618
getattr(index, 'add_nodes', None) == self.add_callback):
619
self.add_callback = None
620
self.data_access.set_writer(None, None, (None, None))
623
class Packer(object):
624
"""Create a pack from packs."""
626
def __init__(self, pack_collection, packs, suffix, revision_ids=None,
630
:param pack_collection: A RepositoryPackCollection object where the
631
new pack is being written to.
632
:param packs: The packs to combine.
633
:param suffix: The suffix to use on the temporary files for the pack.
634
:param revision_ids: Revision ids to limit the pack to.
635
:param reload_func: A function to call if a pack file/index goes
636
missing. The side effect of calling this function should be to
637
update self.packs. See also AggregateIndex
641
self.revision_ids = revision_ids
642
# The pack object we are creating.
644
self._pack_collection = pack_collection
645
self._reload_func = reload_func
646
# The index layer keys for the revisions being copied. None for 'all
648
self._revision_keys = None
649
# What text keys to copy. None for 'all texts'. This is set by
650
# _copy_inventory_texts
651
self._text_filter = None
654
def _extra_init(self):
655
"""A template hook to allow extending the constructor trivially."""
657
def _pack_map_and_index_list(self, index_attribute):
658
"""Convert a list of packs to an index pack map and index list.
660
:param index_attribute: The attribute that the desired index is found
662
:return: A tuple (map, list) where map contains the dict from
663
index:pack_tuple, and list contains the indices in the preferred
668
for pack_obj in self.packs:
669
index = getattr(pack_obj, index_attribute)
670
indices.append(index)
671
pack_map[index] = pack_obj
672
return pack_map, indices
674
def _index_contents(self, indices, key_filter=None):
675
"""Get an iterable of the index contents from a pack_map.
677
:param indices: The list of indices to query
678
:param key_filter: An optional filter to limit the keys returned.
680
all_index = CombinedGraphIndex(indices)
681
if key_filter is None:
682
return all_index.iter_all_entries()
684
return all_index.iter_entries(key_filter)
686
def pack(self, pb=None):
687
"""Create a new pack by reading data from other packs.
689
This does little more than a bulk copy of data. One key difference
690
is that data with the same item key across multiple packs is elided
691
from the output. The new pack is written into the current pack store
692
along with its indices, and the name added to the pack names. The
693
source packs are not altered and are not required to be in the current
696
:param pb: An optional progress bar to use. A nested bar is created if
698
:return: A Pack object, or None if nothing was copied.
700
# open a pack - using the same name as the last temporary file
701
# - which has already been flushed, so its safe.
702
# XXX: - duplicate code warning with start_write_group; fix before
703
# considering 'done'.
704
if self._pack_collection._new_pack is not None:
705
raise errors.BzrError('call to %s.pack() while another pack is'
707
% (self.__class__.__name__,))
708
if self.revision_ids is not None:
709
if len(self.revision_ids) == 0:
710
# silly fetch request.
713
self.revision_ids = frozenset(self.revision_ids)
714
self.revision_keys = frozenset((revid,) for revid in
717
self.pb = ui.ui_factory.nested_progress_bar()
721
return self._create_pack_from_packs()
727
"""Open a pack for the pack we are creating."""
728
return NewPack(self._pack_collection, upload_suffix=self.suffix,
729
file_mode=self._pack_collection.repo.bzrdir._get_file_mode())
731
def _update_pack_order(self, entries, index_to_pack_map):
732
"""Determine how we want our packs to be ordered.
734
This changes the sort order of the self.packs list so that packs unused
735
by 'entries' will be at the end of the list, so that future requests
736
can avoid probing them. Used packs will be at the front of the
737
self.packs list, in the order of their first use in 'entries'.
739
:param entries: A list of (index, ...) tuples
740
:param index_to_pack_map: A mapping from index objects to pack objects.
744
for entry in entries:
746
if index not in seen_indexes:
747
packs.append(index_to_pack_map[index])
748
seen_indexes.add(index)
749
if len(packs) == len(self.packs):
750
if 'pack' in debug.debug_flags:
751
mutter('Not changing pack list, all packs used.')
753
seen_packs = set(packs)
754
for pack in self.packs:
755
if pack not in seen_packs:
758
if 'pack' in debug.debug_flags:
759
old_names = [p.access_tuple()[1] for p in self.packs]
760
new_names = [p.access_tuple()[1] for p in packs]
761
mutter('Reordering packs\nfrom: %s\n to: %s',
762
old_names, new_names)
765
def _copy_revision_texts(self):
766
"""Copy revision data to the new pack."""
768
if self.revision_ids:
769
revision_keys = [(revision_id,) for revision_id in self.revision_ids]
772
# select revision keys
773
revision_index_map, revision_indices = self._pack_map_and_index_list(
775
revision_nodes = self._index_contents(revision_indices, revision_keys)
776
revision_nodes = list(revision_nodes)
777
self._update_pack_order(revision_nodes, revision_index_map)
778
# copy revision keys and adjust values
779
self.pb.update("Copying revision texts", 1)
780
total_items, readv_group_iter = self._revision_node_readv(revision_nodes)
781
list(self._copy_nodes_graph(revision_index_map, self.new_pack._writer,
782
self.new_pack.revision_index, readv_group_iter, total_items))
783
if 'pack' in debug.debug_flags:
784
mutter('%s: create_pack: revisions copied: %s%s %d items t+%6.3fs',
785
time.ctime(), self._pack_collection._upload_transport.base,
786
self.new_pack.random_name,
787
self.new_pack.revision_index.key_count(),
788
time.time() - self.new_pack.start_time)
789
self._revision_keys = revision_keys
791
def _copy_inventory_texts(self):
792
"""Copy the inventory texts to the new pack.
794
self._revision_keys is used to determine what inventories to copy.
796
Sets self._text_filter appropriately.
798
# select inventory keys
799
inv_keys = self._revision_keys # currently the same keyspace, and note that
800
# querying for keys here could introduce a bug where an inventory item
801
# is missed, so do not change it to query separately without cross
802
# checking like the text key check below.
803
inventory_index_map, inventory_indices = self._pack_map_and_index_list(
805
inv_nodes = self._index_contents(inventory_indices, inv_keys)
806
# copy inventory keys and adjust values
807
# XXX: Should be a helper function to allow different inv representation
809
self.pb.update("Copying inventory texts", 2)
810
total_items, readv_group_iter = self._least_readv_node_readv(inv_nodes)
811
# Only grab the output lines if we will be processing them
812
output_lines = bool(self.revision_ids)
813
inv_lines = self._copy_nodes_graph(inventory_index_map,
814
self.new_pack._writer, self.new_pack.inventory_index,
815
readv_group_iter, total_items, output_lines=output_lines)
816
if self.revision_ids:
817
self._process_inventory_lines(inv_lines)
819
# eat the iterator to cause it to execute.
821
self._text_filter = None
822
if 'pack' in debug.debug_flags:
823
mutter('%s: create_pack: inventories copied: %s%s %d items t+%6.3fs',
824
time.ctime(), self._pack_collection._upload_transport.base,
825
self.new_pack.random_name,
826
self.new_pack.inventory_index.key_count(),
827
time.time() - self.new_pack.start_time)
829
def _copy_text_texts(self):
831
text_index_map, text_nodes = self._get_text_nodes()
832
if self._text_filter is not None:
833
# We could return the keys copied as part of the return value from
834
# _copy_nodes_graph but this doesn't work all that well with the
835
# need to get line output too, so we check separately, and as we're
836
# going to buffer everything anyway, we check beforehand, which
837
# saves reading knit data over the wire when we know there are
839
text_nodes = set(text_nodes)
840
present_text_keys = set(_node[1] for _node in text_nodes)
841
missing_text_keys = set(self._text_filter) - present_text_keys
842
if missing_text_keys:
843
# TODO: raise a specific error that can handle many missing
845
mutter("missing keys during fetch: %r", missing_text_keys)
846
a_missing_key = missing_text_keys.pop()
847
raise errors.RevisionNotPresent(a_missing_key[1],
849
# copy text keys and adjust values
850
self.pb.update("Copying content texts", 3)
851
total_items, readv_group_iter = self._least_readv_node_readv(text_nodes)
852
list(self._copy_nodes_graph(text_index_map, self.new_pack._writer,
853
self.new_pack.text_index, readv_group_iter, total_items))
854
self._log_copied_texts()
856
def _create_pack_from_packs(self):
857
self.pb.update("Opening pack", 0, 5)
858
self.new_pack = self.open_pack()
859
new_pack = self.new_pack
860
# buffer data - we won't be reading-back during the pack creation and
861
# this makes a significant difference on sftp pushes.
862
new_pack.set_write_cache_size(1024*1024)
863
if 'pack' in debug.debug_flags:
864
plain_pack_list = ['%s%s' % (a_pack.pack_transport.base, a_pack.name)
865
for a_pack in self.packs]
866
if self.revision_ids is not None:
867
rev_count = len(self.revision_ids)
870
mutter('%s: create_pack: creating pack from source packs: '
871
'%s%s %s revisions wanted %s t=0',
872
time.ctime(), self._pack_collection._upload_transport.base, new_pack.random_name,
873
plain_pack_list, rev_count)
874
self._copy_revision_texts()
875
self._copy_inventory_texts()
876
self._copy_text_texts()
877
# select signature keys
878
signature_filter = self._revision_keys # same keyspace
879
signature_index_map, signature_indices = self._pack_map_and_index_list(
881
signature_nodes = self._index_contents(signature_indices,
883
# copy signature keys and adjust values
884
self.pb.update("Copying signature texts", 4)
885
self._copy_nodes(signature_nodes, signature_index_map, new_pack._writer,
886
new_pack.signature_index)
887
if 'pack' in debug.debug_flags:
888
mutter('%s: create_pack: revision signatures copied: %s%s %d items t+%6.3fs',
889
time.ctime(), self._pack_collection._upload_transport.base, new_pack.random_name,
890
new_pack.signature_index.key_count(),
891
time.time() - new_pack.start_time)
892
new_pack._check_references()
893
if not self._use_pack(new_pack):
896
self.pb.update("Finishing pack", 5)
898
self._pack_collection.allocate(new_pack)
901
def _copy_nodes(self, nodes, index_map, writer, write_index):
902
"""Copy knit nodes between packs with no graph references."""
903
pb = ui.ui_factory.nested_progress_bar()
905
return self._do_copy_nodes(nodes, index_map, writer,
910
def _do_copy_nodes(self, nodes, index_map, writer, write_index, pb):
911
# for record verification
912
knit = KnitVersionedFiles(None, None)
913
# plan a readv on each source pack:
915
nodes = sorted(nodes)
916
# how to map this into knit.py - or knit.py into this?
917
# we don't want the typical knit logic, we want grouping by pack
918
# at this point - perhaps a helper library for the following code
919
# duplication points?
921
for index, key, value in nodes:
922
if index not in request_groups:
923
request_groups[index] = []
924
request_groups[index].append((key, value))
926
pb.update("Copied record", record_index, len(nodes))
927
for index, items in request_groups.iteritems():
928
pack_readv_requests = []
929
for key, value in items:
930
# ---- KnitGraphIndex.get_position
931
bits = value[1:].split(' ')
932
offset, length = int(bits[0]), int(bits[1])
933
pack_readv_requests.append((offset, length, (key, value[0])))
934
# linear scan up the pack
935
pack_readv_requests.sort()
937
pack_obj = index_map[index]
938
transport, path = pack_obj.access_tuple()
940
reader = pack.make_readv_reader(transport, path,
941
[offset[0:2] for offset in pack_readv_requests])
942
except errors.NoSuchFile:
943
if self._reload_func is not None:
946
for (names, read_func), (_1, _2, (key, eol_flag)) in \
947
izip(reader.iter_records(), pack_readv_requests):
948
raw_data = read_func(None)
949
# check the header only
950
df, _ = knit._parse_record_header(key, raw_data)
952
pos, size = writer.add_bytes_record(raw_data, names)
953
write_index.add_node(key, eol_flag + "%d %d" % (pos, size))
954
pb.update("Copied record", record_index)
957
def _copy_nodes_graph(self, index_map, writer, write_index,
958
readv_group_iter, total_items, output_lines=False):
959
"""Copy knit nodes between packs.
961
:param output_lines: Return lines present in the copied data as
962
an iterator of line,version_id.
964
pb = ui.ui_factory.nested_progress_bar()
966
for result in self._do_copy_nodes_graph(index_map, writer,
967
write_index, output_lines, pb, readv_group_iter, total_items):
970
# Python 2.4 does not permit try:finally: in a generator.
976
def _do_copy_nodes_graph(self, index_map, writer, write_index,
977
output_lines, pb, readv_group_iter, total_items):
978
# for record verification
979
knit = KnitVersionedFiles(None, None)
980
# for line extraction when requested (inventories only)
982
factory = KnitPlainFactory()
984
pb.update("Copied record", record_index, total_items)
985
for index, readv_vector, node_vector in readv_group_iter:
987
pack_obj = index_map[index]
988
transport, path = pack_obj.access_tuple()
990
reader = pack.make_readv_reader(transport, path, readv_vector)
991
except errors.NoSuchFile:
992
if self._reload_func is not None:
995
for (names, read_func), (key, eol_flag, references) in \
996
izip(reader.iter_records(), node_vector):
997
raw_data = read_func(None)
999
# read the entire thing
1000
content, _ = knit._parse_record(key[-1], raw_data)
1001
if len(references[-1]) == 0:
1002
line_iterator = factory.get_fulltext_content(content)
1004
line_iterator = factory.get_linedelta_content(content)
1005
for line in line_iterator:
1008
# check the header only
1009
df, _ = knit._parse_record_header(key, raw_data)
1011
pos, size = writer.add_bytes_record(raw_data, names)
1012
write_index.add_node(key, eol_flag + "%d %d" % (pos, size), references)
1013
pb.update("Copied record", record_index)
1016
def _get_text_nodes(self):
1017
text_index_map, text_indices = self._pack_map_and_index_list(
1019
return text_index_map, self._index_contents(text_indices,
1022
def _least_readv_node_readv(self, nodes):
1023
"""Generate request groups for nodes using the least readv's.
1025
:param nodes: An iterable of graph index nodes.
1026
:return: Total node count and an iterator of the data needed to perform
1027
readvs to obtain the data for nodes. Each item yielded by the
1028
iterator is a tuple with:
1029
index, readv_vector, node_vector. readv_vector is a list ready to
1030
hand to the transport readv method, and node_vector is a list of
1031
(key, eol_flag, references) for the the node retrieved by the
1032
matching readv_vector.
1034
# group by pack so we do one readv per pack
1035
nodes = sorted(nodes)
1038
for index, key, value, references in nodes:
1039
if index not in request_groups:
1040
request_groups[index] = []
1041
request_groups[index].append((key, value, references))
1043
for index, items in request_groups.iteritems():
1044
pack_readv_requests = []
1045
for key, value, references in items:
1046
# ---- KnitGraphIndex.get_position
1047
bits = value[1:].split(' ')
1048
offset, length = int(bits[0]), int(bits[1])
1049
pack_readv_requests.append(
1050
((offset, length), (key, value[0], references)))
1051
# linear scan up the pack to maximum range combining.
1052
pack_readv_requests.sort()
1053
# split out the readv and the node data.
1054
pack_readv = [readv for readv, node in pack_readv_requests]
1055
node_vector = [node for readv, node in pack_readv_requests]
1056
result.append((index, pack_readv, node_vector))
1057
return total, result
1059
def _log_copied_texts(self):
1060
if 'pack' in debug.debug_flags:
1061
mutter('%s: create_pack: file texts copied: %s%s %d items t+%6.3fs',
1062
time.ctime(), self._pack_collection._upload_transport.base,
1063
self.new_pack.random_name,
1064
self.new_pack.text_index.key_count(),
1065
time.time() - self.new_pack.start_time)
1067
def _process_inventory_lines(self, inv_lines):
1068
"""Use up the inv_lines generator and setup a text key filter."""
1069
repo = self._pack_collection.repo
1070
fileid_revisions = repo._find_file_ids_from_xml_inventory_lines(
1071
inv_lines, self.revision_keys)
1073
for fileid, file_revids in fileid_revisions.iteritems():
1074
text_filter.extend([(fileid, file_revid) for file_revid in file_revids])
1075
self._text_filter = text_filter
1077
def _revision_node_readv(self, revision_nodes):
1078
"""Return the total revisions and the readv's to issue.
1080
:param revision_nodes: The revision index contents for the packs being
1081
incorporated into the new pack.
1082
:return: As per _least_readv_node_readv.
1084
return self._least_readv_node_readv(revision_nodes)
1086
def _use_pack(self, new_pack):
1087
"""Return True if new_pack should be used.
1089
:param new_pack: The pack that has just been created.
1090
:return: True if the pack should be used.
1092
return new_pack.data_inserted()
1095
class OptimisingPacker(Packer):
1096
"""A packer which spends more time to create better disk layouts."""
1098
def _revision_node_readv(self, revision_nodes):
1099
"""Return the total revisions and the readv's to issue.
1101
This sort places revisions in topological order with the ancestors
1104
:param revision_nodes: The revision index contents for the packs being
1105
incorporated into the new pack.
1106
:return: As per _least_readv_node_readv.
1108
# build an ancestors dict
1111
for index, key, value, references in revision_nodes:
1112
ancestors[key] = references[0]
1113
by_key[key] = (index, value, references)
1114
order = tsort.topo_sort(ancestors)
1116
# Single IO is pathological, but it will work as a starting point.
1118
for key in reversed(order):
1119
index, value, references = by_key[key]
1120
# ---- KnitGraphIndex.get_position
1121
bits = value[1:].split(' ')
1122
offset, length = int(bits[0]), int(bits[1])
1124
(index, [(offset, length)], [(key, value[0], references)]))
1125
# TODO: combine requests in the same index that are in ascending order.
1126
return total, requests
1128
def open_pack(self):
1129
"""Open a pack for the pack we are creating."""
1130
new_pack = super(OptimisingPacker, self).open_pack()
1131
# Turn on the optimization flags for all the index builders.
1132
new_pack.revision_index.set_optimize(for_size=True)
1133
new_pack.inventory_index.set_optimize(for_size=True)
1134
new_pack.text_index.set_optimize(for_size=True)
1135
new_pack.signature_index.set_optimize(for_size=True)
1139
class ReconcilePacker(Packer):
1140
"""A packer which regenerates indices etc as it copies.
1142
This is used by ``bzr reconcile`` to cause parent text pointers to be
1146
def _extra_init(self):
1147
self._data_changed = False
1149
def _process_inventory_lines(self, inv_lines):
1150
"""Generate a text key reference map rather for reconciling with."""
1151
repo = self._pack_collection.repo
1152
refs = repo._find_text_key_references_from_xml_inventory_lines(
1154
self._text_refs = refs
1155
# during reconcile we:
1156
# - convert unreferenced texts to full texts
1157
# - correct texts which reference a text not copied to be full texts
1158
# - copy all others as-is but with corrected parents.
1159
# - so at this point we don't know enough to decide what becomes a full
1161
self._text_filter = None
1163
def _copy_text_texts(self):
1164
"""generate what texts we should have and then copy."""
1165
self.pb.update("Copying content texts", 3)
1166
# we have three major tasks here:
1167
# 1) generate the ideal index
1168
repo = self._pack_collection.repo
1169
ancestors = dict([(key[0], tuple(ref[0] for ref in refs[0])) for
1170
_1, key, _2, refs in
1171
self.new_pack.revision_index.iter_all_entries()])
1172
ideal_index = repo._generate_text_key_index(self._text_refs, ancestors)
1173
# 2) generate a text_nodes list that contains all the deltas that can
1174
# be used as-is, with corrected parents.
1177
discarded_nodes = []
1178
NULL_REVISION = _mod_revision.NULL_REVISION
1179
text_index_map, text_nodes = self._get_text_nodes()
1180
for node in text_nodes:
1186
ideal_parents = tuple(ideal_index[node[1]])
1188
discarded_nodes.append(node)
1189
self._data_changed = True
1191
if ideal_parents == (NULL_REVISION,):
1193
if ideal_parents == node[3][0]:
1195
ok_nodes.append(node)
1196
elif ideal_parents[0:1] == node[3][0][0:1]:
1197
# the left most parent is the same, or there are no parents
1198
# today. Either way, we can preserve the representation as
1199
# long as we change the refs to be inserted.
1200
self._data_changed = True
1201
ok_nodes.append((node[0], node[1], node[2],
1202
(ideal_parents, node[3][1])))
1203
self._data_changed = True
1205
# Reinsert this text completely
1206
bad_texts.append((node[1], ideal_parents))
1207
self._data_changed = True
1208
# we're finished with some data.
1211
# 3) bulk copy the ok data
1212
total_items, readv_group_iter = self._least_readv_node_readv(ok_nodes)
1213
list(self._copy_nodes_graph(text_index_map, self.new_pack._writer,
1214
self.new_pack.text_index, readv_group_iter, total_items))
1215
# 4) adhoc copy all the other texts.
1216
# We have to topologically insert all texts otherwise we can fail to
1217
# reconcile when parts of a single delta chain are preserved intact,
1218
# and other parts are not. E.g. Discarded->d1->d2->d3. d1 will be
1219
# reinserted, and if d3 has incorrect parents it will also be
1220
# reinserted. If we insert d3 first, d2 is present (as it was bulk
1221
# copied), so we will try to delta, but d2 is not currently able to be
1222
# extracted because it's basis d1 is not present. Topologically sorting
1223
# addresses this. The following generates a sort for all the texts that
1224
# are being inserted without having to reference the entire text key
1225
# space (we only topo sort the revisions, which is smaller).
1226
topo_order = tsort.topo_sort(ancestors)
1227
rev_order = dict(zip(topo_order, range(len(topo_order))))
1228
bad_texts.sort(key=lambda key:rev_order[key[0][1]])
1229
transaction = repo.get_transaction()
1230
file_id_index = GraphIndexPrefixAdapter(
1231
self.new_pack.text_index,
1233
add_nodes_callback=self.new_pack.text_index.add_nodes)
1234
data_access = _DirectPackAccess(
1235
{self.new_pack.text_index:self.new_pack.access_tuple()})
1236
data_access.set_writer(self.new_pack._writer, self.new_pack.text_index,
1237
self.new_pack.access_tuple())
1238
output_texts = KnitVersionedFiles(
1239
_KnitGraphIndex(self.new_pack.text_index,
1240
add_callback=self.new_pack.text_index.add_nodes,
1241
deltas=True, parents=True, is_locked=repo.is_locked),
1242
data_access=data_access, max_delta_chain=200)
1243
for key, parent_keys in bad_texts:
1244
# We refer to the new pack to delta data being output.
1245
# A possible improvement would be to catch errors on short reads
1246
# and only flush then.
1247
self.new_pack.flush()
1249
for parent_key in parent_keys:
1250
if parent_key[0] != key[0]:
1251
# Graph parents must match the fileid
1252
raise errors.BzrError('Mismatched key parent %r:%r' %
1254
parents.append(parent_key[1])
1255
text_lines = osutils.split_lines(repo.texts.get_record_stream(
1256
[key], 'unordered', True).next().get_bytes_as('fulltext'))
1257
output_texts.add_lines(key, parent_keys, text_lines,
1258
random_id=True, check_content=False)
1259
# 5) check that nothing inserted has a reference outside the keyspace.
1260
missing_text_keys = self.new_pack.text_index._external_references()
1261
if missing_text_keys:
1262
raise errors.BzrCheckError('Reference to missing compression parents %r'
1263
% (missing_text_keys,))
1264
self._log_copied_texts()
1266
def _use_pack(self, new_pack):
1267
"""Override _use_pack to check for reconcile having changed content."""
1268
# XXX: we might be better checking this at the copy time.
1269
original_inventory_keys = set()
1270
inv_index = self._pack_collection.inventory_index.combined_index
1271
for entry in inv_index.iter_all_entries():
1272
original_inventory_keys.add(entry[1])
1273
new_inventory_keys = set()
1274
for entry in new_pack.inventory_index.iter_all_entries():
1275
new_inventory_keys.add(entry[1])
1276
if new_inventory_keys != original_inventory_keys:
1277
self._data_changed = True
1278
return new_pack.data_inserted() and self._data_changed
1281
class RepositoryPackCollection(object):
1282
"""Management of packs within a repository.
1284
:ivar _names: map of {pack_name: (index_size,)}
1287
def __init__(self, repo, transport, index_transport, upload_transport,
1288
pack_transport, index_builder_class, index_class):
1289
"""Create a new RepositoryPackCollection.
1291
:param transport: Addresses the repository base directory
1292
(typically .bzr/repository/).
1293
:param index_transport: Addresses the directory containing indices.
1294
:param upload_transport: Addresses the directory into which packs are written
1295
while they're being created.
1296
:param pack_transport: Addresses the directory of existing complete packs.
1297
:param index_builder_class: The index builder class to use.
1298
:param index_class: The index class to use.
1300
# XXX: This should call self.reset()
1302
self.transport = transport
1303
self._index_transport = index_transport
1304
self._upload_transport = upload_transport
1305
self._pack_transport = pack_transport
1306
self._index_builder_class = index_builder_class
1307
self._index_class = index_class
1308
self._suffix_offsets = {'.rix': 0, '.iix': 1, '.tix': 2, '.six': 3}
1312
self._packs_by_name = {}
1313
# the previous pack-names content
1314
self._packs_at_load = None
1315
# when a pack is being created by this object, the state of that pack.
1316
self._new_pack = None
1317
# aggregated revision index data
1318
self.revision_index = AggregateIndex(self.reload_pack_names)
1319
self.inventory_index = AggregateIndex(self.reload_pack_names)
1320
self.text_index = AggregateIndex(self.reload_pack_names)
1321
self.signature_index = AggregateIndex(self.reload_pack_names)
1323
self._resumed_packs = []
1325
def add_pack_to_memory(self, pack):
1326
"""Make a Pack object available to the repository to satisfy queries.
1328
:param pack: A Pack object.
1330
if pack.name in self._packs_by_name:
1331
raise AssertionError(
1332
'pack %s already in _packs_by_name' % (pack.name,))
1333
self.packs.append(pack)
1334
self._packs_by_name[pack.name] = pack
1335
self.revision_index.add_index(pack.revision_index, pack)
1336
self.inventory_index.add_index(pack.inventory_index, pack)
1337
self.text_index.add_index(pack.text_index, pack)
1338
self.signature_index.add_index(pack.signature_index, pack)
1340
def all_packs(self):
1341
"""Return a list of all the Pack objects this repository has.
1343
Note that an in-progress pack being created is not returned.
1345
:return: A list of Pack objects for all the packs in the repository.
1348
for name in self.names():
1349
result.append(self.get_pack_by_name(name))
1353
"""Pack the pack collection incrementally.
1355
This will not attempt global reorganisation or recompression,
1356
rather it will just ensure that the total number of packs does
1357
not grow without bound. It uses the _max_pack_count method to
1358
determine if autopacking is needed, and the pack_distribution
1359
method to determine the number of revisions in each pack.
1361
If autopacking takes place then the packs name collection will have
1362
been flushed to disk - packing requires updating the name collection
1363
in synchronisation with certain steps. Otherwise the names collection
1366
:return: True if packing took place.
1370
return self._do_autopack()
1371
except errors.RetryAutopack, e:
1372
# If we get a RetryAutopack exception, we should abort the
1373
# current action, and retry.
1376
def _do_autopack(self):
1377
# XXX: Should not be needed when the management of indices is sane.
1378
total_revisions = self.revision_index.combined_index.key_count()
1379
total_packs = len(self._names)
1380
if self._max_pack_count(total_revisions) >= total_packs:
1382
# XXX: the following may want to be a class, to pack with a given
1384
# determine which packs need changing
1385
pack_distribution = self.pack_distribution(total_revisions)
1387
for pack in self.all_packs():
1388
revision_count = pack.get_revision_count()
1389
if revision_count == 0:
1390
# revision less packs are not generated by normal operation,
1391
# only by operations like sign-my-commits, and thus will not
1392
# tend to grow rapdily or without bound like commit containing
1393
# packs do - leave them alone as packing them really should
1394
# group their data with the relevant commit, and that may
1395
# involve rewriting ancient history - which autopack tries to
1396
# avoid. Alternatively we could not group the data but treat
1397
# each of these as having a single revision, and thus add
1398
# one revision for each to the total revision count, to get
1399
# a matching distribution.
1401
existing_packs.append((revision_count, pack))
1402
pack_operations = self.plan_autopack_combinations(
1403
existing_packs, pack_distribution)
1404
num_new_packs = len(pack_operations)
1405
num_old_packs = sum([len(po[1]) for po in pack_operations])
1406
num_revs_affected = sum([po[0] for po in pack_operations])
1407
mutter('Auto-packing repository %s, which has %d pack files, '
1408
'containing %d revisions. Packing %d files into %d affecting %d'
1409
' revisions', self, total_packs, total_revisions, num_old_packs,
1410
num_new_packs, num_revs_affected)
1411
self._execute_pack_operations(pack_operations,
1412
reload_func=self._restart_autopack)
1415
def _execute_pack_operations(self, pack_operations, _packer_class=Packer,
1417
"""Execute a series of pack operations.
1419
:param pack_operations: A list of [revision_count, packs_to_combine].
1420
:param _packer_class: The class of packer to use (default: Packer).
1423
for revision_count, packs in pack_operations:
1424
# we may have no-ops from the setup logic
1427
packer = _packer_class(self, packs, '.autopack',
1428
reload_func=reload_func)
1431
except errors.RetryWithNewPacks:
1432
# An exception is propagating out of this context, make sure
1433
# this packer has cleaned up. Packer() doesn't set its new_pack
1434
# state into the RepositoryPackCollection object, so we only
1435
# have access to it directly here.
1436
if packer.new_pack is not None:
1437
packer.new_pack.abort()
1440
self._remove_pack_from_memory(pack)
1441
# record the newly available packs and stop advertising the old
1443
self._save_pack_names(clear_obsolete_packs=True)
1444
# Move the old packs out of the way now they are no longer referenced.
1445
for revision_count, packs in pack_operations:
1446
self._obsolete_packs(packs)
1448
def lock_names(self):
1449
"""Acquire the mutex around the pack-names index.
1451
This cannot be used in the middle of a read-only transaction on the
1454
self.repo.control_files.lock_write()
1457
"""Pack the pack collection totally."""
1458
self.ensure_loaded()
1459
total_packs = len(self._names)
1461
# This is arguably wrong because we might not be optimal, but for
1462
# now lets leave it in. (e.g. reconcile -> one pack. But not
1465
total_revisions = self.revision_index.combined_index.key_count()
1466
# XXX: the following may want to be a class, to pack with a given
1468
mutter('Packing repository %s, which has %d pack files, '
1469
'containing %d revisions into 1 packs.', self, total_packs,
1471
# determine which packs need changing
1472
pack_distribution = [1]
1473
pack_operations = [[0, []]]
1474
for pack in self.all_packs():
1475
pack_operations[-1][0] += pack.get_revision_count()
1476
pack_operations[-1][1].append(pack)
1477
self._execute_pack_operations(pack_operations, OptimisingPacker)
1479
def plan_autopack_combinations(self, existing_packs, pack_distribution):
1480
"""Plan a pack operation.
1482
:param existing_packs: The packs to pack. (A list of (revcount, Pack)
1484
:param pack_distribution: A list with the number of revisions desired
1487
if len(existing_packs) <= len(pack_distribution):
1489
existing_packs.sort(reverse=True)
1490
pack_operations = [[0, []]]
1491
# plan out what packs to keep, and what to reorganise
1492
while len(existing_packs):
1493
# take the largest pack, and if its less than the head of the
1494
# distribution chart we will include its contents in the new pack
1495
# for that position. If its larger, we remove its size from the
1496
# distribution chart
1497
next_pack_rev_count, next_pack = existing_packs.pop(0)
1498
if next_pack_rev_count >= pack_distribution[0]:
1499
# this is already packed 'better' than this, so we can
1500
# not waste time packing it.
1501
while next_pack_rev_count > 0:
1502
next_pack_rev_count -= pack_distribution[0]
1503
if next_pack_rev_count >= 0:
1505
del pack_distribution[0]
1507
# didn't use that entire bucket up
1508
pack_distribution[0] = -next_pack_rev_count
1510
# add the revisions we're going to add to the next output pack
1511
pack_operations[-1][0] += next_pack_rev_count
1512
# allocate this pack to the next pack sub operation
1513
pack_operations[-1][1].append(next_pack)
1514
if pack_operations[-1][0] >= pack_distribution[0]:
1515
# this pack is used up, shift left.
1516
del pack_distribution[0]
1517
pack_operations.append([0, []])
1518
# Now that we know which pack files we want to move, shove them all
1519
# into a single pack file.
1521
final_pack_list = []
1522
for num_revs, pack_files in pack_operations:
1523
final_rev_count += num_revs
1524
final_pack_list.extend(pack_files)
1525
if len(final_pack_list) == 1:
1526
raise AssertionError('We somehow generated an autopack with a'
1527
' single pack file being moved.')
1529
return [[final_rev_count, final_pack_list]]
1531
def ensure_loaded(self):
1532
"""Ensure we have read names from disk.
1534
:return: True if the disk names had not been previously read.
1536
# NB: if you see an assertion error here, its probably access against
1537
# an unlocked repo. Naughty.
1538
if not self.repo.is_locked():
1539
raise errors.ObjectNotLocked(self.repo)
1540
if self._names is None:
1542
self._packs_at_load = set()
1543
for index, key, value in self._iter_disk_pack_index():
1545
self._names[name] = self._parse_index_sizes(value)
1546
self._packs_at_load.add((key, value))
1550
# populate all the metadata.
1554
def _parse_index_sizes(self, value):
1555
"""Parse a string of index sizes."""
1556
return tuple([int(digits) for digits in value.split(' ')])
1558
def get_pack_by_name(self, name):
1559
"""Get a Pack object by name.
1561
:param name: The name of the pack - e.g. '123456'
1562
:return: A Pack object.
1565
return self._packs_by_name[name]
1567
rev_index = self._make_index(name, '.rix')
1568
inv_index = self._make_index(name, '.iix')
1569
txt_index = self._make_index(name, '.tix')
1570
sig_index = self._make_index(name, '.six')
1571
result = ExistingPack(self._pack_transport, name, rev_index,
1572
inv_index, txt_index, sig_index)
1573
self.add_pack_to_memory(result)
1576
def _resume_pack(self, name):
1577
"""Get a suspended Pack object by name.
1579
:param name: The name of the pack - e.g. '123456'
1580
:return: A Pack object.
1582
if not re.match('[a-f0-9]{32}', name):
1583
# Tokens should be md5sums of the suspended pack file, i.e. 32 hex
1585
raise errors.UnresumableWriteGroup(
1586
self.repo, [name], 'Malformed write group token')
1588
rev_index = self._make_index(name, '.rix', resume=True)
1589
inv_index = self._make_index(name, '.iix', resume=True)
1590
txt_index = self._make_index(name, '.tix', resume=True)
1591
sig_index = self._make_index(name, '.six', resume=True)
1592
result = ResumedPack(name, rev_index, inv_index, txt_index,
1593
sig_index, self._upload_transport, self._pack_transport,
1594
self._index_transport, self)
1595
except errors.NoSuchFile, e:
1596
raise errors.UnresumableWriteGroup(self.repo, [name], str(e))
1597
self.add_pack_to_memory(result)
1598
self._resumed_packs.append(result)
1601
def allocate(self, a_new_pack):
1602
"""Allocate name in the list of packs.
1604
:param a_new_pack: A NewPack instance to be added to the collection of
1605
packs for this repository.
1607
self.ensure_loaded()
1608
if a_new_pack.name in self._names:
1609
raise errors.BzrError(
1610
'Pack %r already exists in %s' % (a_new_pack.name, self))
1611
self._names[a_new_pack.name] = tuple(a_new_pack.index_sizes)
1612
self.add_pack_to_memory(a_new_pack)
1614
def _iter_disk_pack_index(self):
1615
"""Iterate over the contents of the pack-names index.
1617
This is used when loading the list from disk, and before writing to
1618
detect updates from others during our write operation.
1619
:return: An iterator of the index contents.
1621
return self._index_class(self.transport, 'pack-names', None
1622
).iter_all_entries()
1624
def _make_index(self, name, suffix, resume=False):
1625
size_offset = self._suffix_offsets[suffix]
1626
index_name = name + suffix
1628
transport = self._upload_transport
1629
index_size = transport.stat(index_name).st_size
1631
transport = self._index_transport
1632
index_size = self._names[name][size_offset]
1633
return self._index_class(transport, index_name, index_size)
1635
def _max_pack_count(self, total_revisions):
1636
"""Return the maximum number of packs to use for total revisions.
1638
:param total_revisions: The total number of revisions in the
1641
if not total_revisions:
1643
digits = str(total_revisions)
1645
for digit in digits:
1646
result += int(digit)
1650
"""Provide an order to the underlying names."""
1651
return sorted(self._names.keys())
1653
def _obsolete_packs(self, packs):
1654
"""Move a number of packs which have been obsoleted out of the way.
1656
Each pack and its associated indices are moved out of the way.
1658
Note: for correctness this function should only be called after a new
1659
pack names index has been written without these pack names, and with
1660
the names of packs that contain the data previously available via these
1663
:param packs: The packs to obsolete.
1664
:param return: None.
1667
pack.pack_transport.rename(pack.file_name(),
1668
'../obsolete_packs/' + pack.file_name())
1669
# TODO: Probably needs to know all possible indices for this pack
1670
# - or maybe list the directory and move all indices matching this
1671
# name whether we recognize it or not?
1672
for suffix in ('.iix', '.six', '.tix', '.rix'):
1673
self._index_transport.rename(pack.name + suffix,
1674
'../obsolete_packs/' + pack.name + suffix)
1676
def pack_distribution(self, total_revisions):
1677
"""Generate a list of the number of revisions to put in each pack.
1679
:param total_revisions: The total number of revisions in the
1682
if total_revisions == 0:
1684
digits = reversed(str(total_revisions))
1686
for exponent, count in enumerate(digits):
1687
size = 10 ** exponent
1688
for pos in range(int(count)):
1690
return list(reversed(result))
1692
def _pack_tuple(self, name):
1693
"""Return a tuple with the transport and file name for a pack name."""
1694
return self._pack_transport, name + '.pack'
1696
def _remove_pack_from_memory(self, pack):
1697
"""Remove pack from the packs accessed by this repository.
1699
Only affects memory state, until self._save_pack_names() is invoked.
1701
self._names.pop(pack.name)
1702
self._packs_by_name.pop(pack.name)
1703
self._remove_pack_indices(pack)
1704
self.packs.remove(pack)
1706
def _remove_pack_indices(self, pack):
1707
"""Remove the indices for pack from the aggregated indices."""
1708
self.revision_index.remove_index(pack.revision_index, pack)
1709
self.inventory_index.remove_index(pack.inventory_index, pack)
1710
self.text_index.remove_index(pack.text_index, pack)
1711
self.signature_index.remove_index(pack.signature_index, pack)
1714
"""Clear all cached data."""
1715
# cached revision data
1716
self.repo._revision_knit = None
1717
self.revision_index.clear()
1718
# cached signature data
1719
self.repo._signature_knit = None
1720
self.signature_index.clear()
1721
# cached file text data
1722
self.text_index.clear()
1723
self.repo._text_knit = None
1724
# cached inventory data
1725
self.inventory_index.clear()
1726
# remove the open pack
1727
self._new_pack = None
1728
# information about packs.
1731
self._packs_by_name = {}
1732
self._packs_at_load = None
1734
def _unlock_names(self):
1735
"""Release the mutex around the pack-names index."""
1736
self.repo.control_files.unlock()
1738
def _diff_pack_names(self):
1739
"""Read the pack names from disk, and compare it to the one in memory.
1741
:return: (disk_nodes, deleted_nodes, new_nodes)
1742
disk_nodes The final set of nodes that should be referenced
1743
deleted_nodes Nodes which have been removed from when we started
1744
new_nodes Nodes that are newly introduced
1746
# load the disk nodes across
1748
for index, key, value in self._iter_disk_pack_index():
1749
disk_nodes.add((key, value))
1751
# do a two-way diff against our original content
1752
current_nodes = set()
1753
for name, sizes in self._names.iteritems():
1755
((name, ), ' '.join(str(size) for size in sizes)))
1757
# Packs no longer present in the repository, which were present when we
1758
# locked the repository
1759
deleted_nodes = self._packs_at_load - current_nodes
1760
# Packs which this process is adding
1761
new_nodes = current_nodes - self._packs_at_load
1763
# Update the disk_nodes set to include the ones we are adding, and
1764
# remove the ones which were removed by someone else
1765
disk_nodes.difference_update(deleted_nodes)
1766
disk_nodes.update(new_nodes)
1768
return disk_nodes, deleted_nodes, new_nodes
1770
def _syncronize_pack_names_from_disk_nodes(self, disk_nodes):
1771
"""Given the correct set of pack files, update our saved info.
1773
:return: (removed, added, modified)
1774
removed pack names removed from self._names
1775
added pack names added to self._names
1776
modified pack names that had changed value
1781
## self._packs_at_load = disk_nodes
1782
new_names = dict(disk_nodes)
1783
# drop no longer present nodes
1784
for pack in self.all_packs():
1785
if (pack.name,) not in new_names:
1786
removed.append(pack.name)
1787
self._remove_pack_from_memory(pack)
1788
# add new nodes/refresh existing ones
1789
for key, value in disk_nodes:
1791
sizes = self._parse_index_sizes(value)
1792
if name in self._names:
1794
if sizes != self._names[name]:
1795
# the pack for name has had its indices replaced - rare but
1796
# important to handle. XXX: probably can never happen today
1797
# because the three-way merge code above does not handle it
1798
# - you may end up adding the same key twice to the new
1799
# disk index because the set values are the same, unless
1800
# the only index shows up as deleted by the set difference
1801
# - which it may. Until there is a specific test for this,
1802
# assume its broken. RBC 20071017.
1803
self._remove_pack_from_memory(self.get_pack_by_name(name))
1804
self._names[name] = sizes
1805
self.get_pack_by_name(name)
1806
modified.append(name)
1809
self._names[name] = sizes
1810
self.get_pack_by_name(name)
1812
return removed, added, modified
1814
def _save_pack_names(self, clear_obsolete_packs=False):
1815
"""Save the list of packs.
1817
This will take out the mutex around the pack names list for the
1818
duration of the method call. If concurrent updates have been made, a
1819
three-way merge between the current list and the current in memory list
1822
:param clear_obsolete_packs: If True, clear out the contents of the
1823
obsolete_packs directory.
1827
builder = self._index_builder_class()
1828
disk_nodes, deleted_nodes, new_nodes = self._diff_pack_names()
1829
# TODO: handle same-name, index-size-changes here -
1830
# e.g. use the value from disk, not ours, *unless* we're the one
1832
for key, value in disk_nodes:
1833
builder.add_node(key, value)
1834
self.transport.put_file('pack-names', builder.finish(),
1835
mode=self.repo.bzrdir._get_file_mode())
1836
# move the baseline forward
1837
self._packs_at_load = disk_nodes
1838
if clear_obsolete_packs:
1839
self._clear_obsolete_packs()
1841
self._unlock_names()
1842
# synchronise the memory packs list with what we just wrote:
1843
self._syncronize_pack_names_from_disk_nodes(disk_nodes)
1845
def reload_pack_names(self):
1846
"""Sync our pack listing with what is present in the repository.
1848
This should be called when we find out that something we thought was
1849
present is now missing. This happens when another process re-packs the
1852
:return: True if the in-memory list of packs has been altered at all.
1854
# The ensure_loaded call is to handle the case where the first call
1855
# made involving the collection was to reload_pack_names, where we
1856
# don't have a view of disk contents. Its a bit of a bandaid, and
1857
# causes two reads of pack-names, but its a rare corner case not struck
1858
# with regular push/pull etc.
1859
first_read = self.ensure_loaded()
1862
# out the new value.
1863
disk_nodes, _, _ = self._diff_pack_names()
1864
self._packs_at_load = disk_nodes
1866
modified) = self._syncronize_pack_names_from_disk_nodes(disk_nodes)
1867
if removed or added or modified:
1871
def _restart_autopack(self):
1872
"""Reload the pack names list, and restart the autopack code."""
1873
if not self.reload_pack_names():
1874
# Re-raise the original exception, because something went missing
1875
# and a restart didn't find it
1877
raise errors.RetryAutopack(self.repo, False, sys.exc_info())
1879
def _clear_obsolete_packs(self):
1880
"""Delete everything from the obsolete-packs directory.
1882
obsolete_pack_transport = self.transport.clone('obsolete_packs')
1883
for filename in obsolete_pack_transport.list_dir('.'):
1885
obsolete_pack_transport.delete(filename)
1886
except (errors.PathError, errors.TransportError), e:
1887
warning("couldn't delete obsolete pack, skipping it:\n%s" % (e,))
1889
def _start_write_group(self):
1890
# Do not permit preparation for writing if we're not in a 'write lock'.
1891
if not self.repo.is_write_locked():
1892
raise errors.NotWriteLocked(self)
1893
self._new_pack = NewPack(self, upload_suffix='.pack',
1894
file_mode=self.repo.bzrdir._get_file_mode())
1895
# allow writing: queue writes to a new index
1896
self.revision_index.add_writable_index(self._new_pack.revision_index,
1898
self.inventory_index.add_writable_index(self._new_pack.inventory_index,
1900
self.text_index.add_writable_index(self._new_pack.text_index,
1902
self.signature_index.add_writable_index(self._new_pack.signature_index,
1905
self.repo.inventories._index._add_callback = self.inventory_index.add_callback
1906
self.repo.revisions._index._add_callback = self.revision_index.add_callback
1907
self.repo.signatures._index._add_callback = self.signature_index.add_callback
1908
self.repo.texts._index._add_callback = self.text_index.add_callback
1910
def _abort_write_group(self):
1911
# FIXME: just drop the transient index.
1912
# forget what names there are
1913
if self._new_pack is not None:
1915
self._new_pack.abort()
1917
# XXX: If we aborted while in the middle of finishing the write
1918
# group, _remove_pack_indices can fail because the indexes are
1919
# already gone. If they're not there we shouldn't fail in this
1920
# case. -- mbp 20081113
1921
self._remove_pack_indices(self._new_pack)
1922
self._new_pack = None
1923
for resumed_pack in self._resumed_packs:
1925
resumed_pack.abort()
1927
# See comment in previous finally block.
1929
self._remove_pack_indices(resumed_pack)
1932
del self._resumed_packs[:]
1933
self.repo._text_knit = None
1935
def _remove_resumed_pack_indices(self):
1936
for resumed_pack in self._resumed_packs:
1937
self._remove_pack_indices(resumed_pack)
1938
del self._resumed_packs[:]
1940
def _commit_write_group(self):
1942
for prefix, versioned_file in (
1943
('revisions', self.repo.revisions),
1944
('inventories', self.repo.inventories),
1945
('texts', self.repo.texts),
1946
('signatures', self.repo.signatures),
1948
missing = versioned_file.get_missing_compression_parent_keys()
1949
all_missing.update([(prefix,) + key for key in missing])
1951
raise errors.BzrCheckError(
1952
"Repository %s has missing compression parent(s) %r "
1953
% (self.repo, sorted(all_missing)))
1954
self._remove_pack_indices(self._new_pack)
1955
should_autopack = False
1956
if self._new_pack.data_inserted():
1957
# get all the data to disk and read to use
1958
self._new_pack.finish()
1959
self.allocate(self._new_pack)
1960
self._new_pack = None
1961
should_autopack = True
1963
self._new_pack.abort()
1964
self._new_pack = None
1965
for resumed_pack in self._resumed_packs:
1966
# XXX: this is a pretty ugly way to turn the resumed pack into a
1967
# properly committed pack.
1968
self._names[resumed_pack.name] = None
1969
self._remove_pack_from_memory(resumed_pack)
1970
resumed_pack.finish()
1971
self.allocate(resumed_pack)
1972
should_autopack = True
1973
del self._resumed_packs[:]
1975
if not self.autopack():
1976
# when autopack takes no steps, the names list is still
1978
self._save_pack_names()
1979
self.repo._text_knit = None
1981
def _suspend_write_group(self):
1982
tokens = [pack.name for pack in self._resumed_packs]
1983
self._remove_pack_indices(self._new_pack)
1984
if self._new_pack.data_inserted():
1985
# get all the data to disk and read to use
1986
self._new_pack.finish(suspend=True)
1987
tokens.append(self._new_pack.name)
1988
self._new_pack = None
1990
self._new_pack.abort()
1991
self._new_pack = None
1992
self._remove_resumed_pack_indices()
1993
self.repo._text_knit = None
1996
def _resume_write_group(self, tokens):
1997
for token in tokens:
1998
self._resume_pack(token)
2001
class KnitPackRepository(KnitRepository):
2002
"""Repository with knit objects stored inside pack containers.
2004
The layering for a KnitPackRepository is:
2006
Graph | HPSS | Repository public layer |
2007
===================================================
2008
Tuple based apis below, string based, and key based apis above
2009
---------------------------------------------------
2011
Provides .texts, .revisions etc
2012
This adapts the N-tuple keys to physical knit records which only have a
2013
single string identifier (for historical reasons), which in older formats
2014
was always the revision_id, and in the mapped code for packs is always
2015
the last element of key tuples.
2016
---------------------------------------------------
2018
A separate GraphIndex is used for each of the
2019
texts/inventories/revisions/signatures contained within each individual
2020
pack file. The GraphIndex layer works in N-tuples and is unaware of any
2022
===================================================
2026
def __init__(self, _format, a_bzrdir, control_files, _commit_builder_class,
2028
KnitRepository.__init__(self, _format, a_bzrdir, control_files,
2029
_commit_builder_class, _serializer)
2030
index_transport = self._transport.clone('indices')
2031
self._pack_collection = RepositoryPackCollection(self, self._transport,
2033
self._transport.clone('upload'),
2034
self._transport.clone('packs'),
2035
_format.index_builder_class,
2036
_format.index_class)
2037
self.inventories = KnitVersionedFiles(
2038
_KnitGraphIndex(self._pack_collection.inventory_index.combined_index,
2039
add_callback=self._pack_collection.inventory_index.add_callback,
2040
deltas=True, parents=True, is_locked=self.is_locked),
2041
data_access=self._pack_collection.inventory_index.data_access,
2042
max_delta_chain=200)
2043
self.revisions = KnitVersionedFiles(
2044
_KnitGraphIndex(self._pack_collection.revision_index.combined_index,
2045
add_callback=self._pack_collection.revision_index.add_callback,
2046
deltas=False, parents=True, is_locked=self.is_locked),
2047
data_access=self._pack_collection.revision_index.data_access,
2049
self.signatures = KnitVersionedFiles(
2050
_KnitGraphIndex(self._pack_collection.signature_index.combined_index,
2051
add_callback=self._pack_collection.signature_index.add_callback,
2052
deltas=False, parents=False, is_locked=self.is_locked),
2053
data_access=self._pack_collection.signature_index.data_access,
2055
self.texts = KnitVersionedFiles(
2056
_KnitGraphIndex(self._pack_collection.text_index.combined_index,
2057
add_callback=self._pack_collection.text_index.add_callback,
2058
deltas=True, parents=True, is_locked=self.is_locked),
2059
data_access=self._pack_collection.text_index.data_access,
2060
max_delta_chain=200)
2061
# True when the repository object is 'write locked' (as opposed to the
2062
# physical lock only taken out around changes to the pack-names list.)
2063
# Another way to represent this would be a decorator around the control
2064
# files object that presents logical locks as physical ones - if this
2065
# gets ugly consider that alternative design. RBC 20071011
2066
self._write_lock_count = 0
2067
self._transaction = None
2069
self._reconcile_does_inventory_gc = True
2070
self._reconcile_fixes_text_parents = True
2071
self._reconcile_backsup_inventory = False
2073
def _warn_if_deprecated(self):
2074
# This class isn't deprecated, but one sub-format is
2075
if isinstance(self._format, RepositoryFormatKnitPack5RichRootBroken):
2076
from bzrlib import repository
2077
if repository._deprecation_warning_done:
2079
repository._deprecation_warning_done = True
2080
warning("Format %s for %s is deprecated - please use"
2081
" 'bzr upgrade --1.6.1-rich-root'"
2082
% (self._format, self.bzrdir.transport.base))
2084
def _abort_write_group(self):
2085
self._pack_collection._abort_write_group()
2087
def _find_inconsistent_revision_parents(self):
2088
"""Find revisions with incorrectly cached parents.
2090
:returns: an iterator yielding tuples of (revison-id, parents-in-index,
2091
parents-in-revision).
2093
if not self.is_locked():
2094
raise errors.ObjectNotLocked(self)
2095
pb = ui.ui_factory.nested_progress_bar()
2098
revision_nodes = self._pack_collection.revision_index \
2099
.combined_index.iter_all_entries()
2100
index_positions = []
2101
# Get the cached index values for all revisions, and also the location
2102
# in each index of the revision text so we can perform linear IO.
2103
for index, key, value, refs in revision_nodes:
2104
pos, length = value[1:].split(' ')
2105
index_positions.append((index, int(pos), key[0],
2106
tuple(parent[0] for parent in refs[0])))
2107
pb.update("Reading revision index", 0, 0)
2108
index_positions.sort()
2109
batch_count = len(index_positions) / 1000 + 1
2110
pb.update("Checking cached revision graph", 0, batch_count)
2111
for offset in xrange(batch_count):
2112
pb.update("Checking cached revision graph", offset)
2113
to_query = index_positions[offset * 1000:(offset + 1) * 1000]
2116
rev_ids = [item[2] for item in to_query]
2117
revs = self.get_revisions(rev_ids)
2118
for revision, item in zip(revs, to_query):
2119
index_parents = item[3]
2120
rev_parents = tuple(revision.parent_ids)
2121
if index_parents != rev_parents:
2122
result.append((revision.revision_id, index_parents, rev_parents))
2127
@symbol_versioning.deprecated_method(symbol_versioning.one_one)
2128
def get_parents(self, revision_ids):
2129
"""See graph._StackedParentsProvider.get_parents."""
2130
parent_map = self.get_parent_map(revision_ids)
2131
return [parent_map.get(r, None) for r in revision_ids]
2133
def _make_parents_provider(self):
2134
return graph.CachingParentsProvider(self)
2136
def _refresh_data(self):
2137
if not self.is_locked():
2139
self._pack_collection.reload_pack_names()
2141
def _start_write_group(self):
2142
self._pack_collection._start_write_group()
2144
def _commit_write_group(self):
2145
return self._pack_collection._commit_write_group()
2147
def suspend_write_group(self):
2148
# XXX check self._write_group is self.get_transaction()?
2149
tokens = self._pack_collection._suspend_write_group()
2150
self._write_group = None
2153
def _resume_write_group(self, tokens):
2154
self._start_write_group()
2155
self._pack_collection._resume_write_group(tokens)
2157
def get_transaction(self):
2158
if self._write_lock_count:
2159
return self._transaction
2161
return self.control_files.get_transaction()
2163
def is_locked(self):
2164
return self._write_lock_count or self.control_files.is_locked()
2166
def is_write_locked(self):
2167
return self._write_lock_count
2169
def lock_write(self, token=None):
2170
locked = self.is_locked()
2171
if not self._write_lock_count and locked:
2172
raise errors.ReadOnlyError(self)
2173
self._write_lock_count += 1
2174
if self._write_lock_count == 1:
2175
self._transaction = transactions.WriteTransaction()
2176
for repo in self._fallback_repositories:
2177
# Writes don't affect fallback repos
2180
self._refresh_data()
2182
def lock_read(self):
2183
locked = self.is_locked()
2184
if self._write_lock_count:
2185
self._write_lock_count += 1
2187
self.control_files.lock_read()
2188
for repo in self._fallback_repositories:
2189
# Writes don't affect fallback repos
2192
self._refresh_data()
2194
def leave_lock_in_place(self):
2195
# not supported - raise an error
2196
raise NotImplementedError(self.leave_lock_in_place)
2198
def dont_leave_lock_in_place(self):
2199
# not supported - raise an error
2200
raise NotImplementedError(self.dont_leave_lock_in_place)
2204
"""Compress the data within the repository.
2206
This will pack all the data to a single pack. In future it may
2207
recompress deltas or do other such expensive operations.
2209
self._pack_collection.pack()
2212
def reconcile(self, other=None, thorough=False):
2213
"""Reconcile this repository."""
2214
from bzrlib.reconcile import PackReconciler
2215
reconciler = PackReconciler(self, thorough=thorough)
2216
reconciler.reconcile()
2220
if self._write_lock_count == 1 and self._write_group is not None:
2221
self.abort_write_group()
2222
self._transaction = None
2223
self._write_lock_count = 0
2224
raise errors.BzrError(
2225
'Must end write group before releasing write lock on %s'
2227
if self._write_lock_count:
2228
self._write_lock_count -= 1
2229
if not self._write_lock_count:
2230
transaction = self._transaction
2231
self._transaction = None
2232
transaction.finish()
2233
for repo in self._fallback_repositories:
2236
self.control_files.unlock()
2237
for repo in self._fallback_repositories:
2241
class RepositoryFormatPack(MetaDirRepositoryFormat):
2242
"""Format logic for pack structured repositories.
2244
This repository format has:
2245
- a list of packs in pack-names
2246
- packs in packs/NAME.pack
2247
- indices in indices/NAME.{iix,six,tix,rix}
2248
- knit deltas in the packs, knit indices mapped to the indices.
2249
- thunk objects to support the knits programming API.
2250
- a format marker of its own
2251
- an optional 'shared-storage' flag
2252
- an optional 'no-working-trees' flag
2256
# Set this attribute in derived classes to control the repository class
2257
# created by open and initialize.
2258
repository_class = None
2259
# Set this attribute in derived classes to control the
2260
# _commit_builder_class that the repository objects will have passed to
2261
# their constructor.
2262
_commit_builder_class = None
2263
# Set this attribute in derived clases to control the _serializer that the
2264
# repository objects will have passed to their constructor.
2266
# Packs are not confused by ghosts.
2267
supports_ghosts = True
2268
# External references are not supported in pack repositories yet.
2269
supports_external_lookups = False
2270
# What index classes to use
2271
index_builder_class = None
2273
_fetch_uses_deltas = True
2275
def initialize(self, a_bzrdir, shared=False):
2276
"""Create a pack based repository.
2278
:param a_bzrdir: bzrdir to contain the new repository; must already
2280
:param shared: If true the repository will be initialized as a shared
2283
mutter('creating repository in %s.', a_bzrdir.transport.base)
2284
dirs = ['indices', 'obsolete_packs', 'packs', 'upload']
2285
builder = self.index_builder_class()
2286
files = [('pack-names', builder.finish())]
2287
utf8_files = [('format', self.get_format_string())]
2289
self._upload_blank_content(a_bzrdir, dirs, files, utf8_files, shared)
2290
return self.open(a_bzrdir=a_bzrdir, _found=True)
2292
def open(self, a_bzrdir, _found=False, _override_transport=None):
2293
"""See RepositoryFormat.open().
2295
:param _override_transport: INTERNAL USE ONLY. Allows opening the
2296
repository at a slightly different url
2297
than normal. I.e. during 'upgrade'.
2300
format = RepositoryFormat.find_format(a_bzrdir)
2301
if _override_transport is not None:
2302
repo_transport = _override_transport
2304
repo_transport = a_bzrdir.get_repository_transport(None)
2305
control_files = lockable_files.LockableFiles(repo_transport,
2306
'lock', lockdir.LockDir)
2307
return self.repository_class(_format=self,
2309
control_files=control_files,
2310
_commit_builder_class=self._commit_builder_class,
2311
_serializer=self._serializer)
2314
class RepositoryFormatKnitPack1(RepositoryFormatPack):
2315
"""A no-subtrees parameterized Pack repository.
2317
This format was introduced in 0.92.
2320
repository_class = KnitPackRepository
2321
_commit_builder_class = PackCommitBuilder
2323
def _serializer(self):
2324
return xml5.serializer_v5
2325
# What index classes to use
2326
index_builder_class = InMemoryGraphIndex
2327
index_class = GraphIndex
2329
def _get_matching_bzrdir(self):
2330
return bzrdir.format_registry.make_bzrdir('pack-0.92')
2332
def _ignore_setting_bzrdir(self, format):
2335
_matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
2337
def get_format_string(self):
2338
"""See RepositoryFormat.get_format_string()."""
2339
return "Bazaar pack repository format 1 (needs bzr 0.92)\n"
2341
def get_format_description(self):
2342
"""See RepositoryFormat.get_format_description()."""
2343
return "Packs containing knits without subtree support"
2345
def check_conversion_target(self, target_format):
2349
class RepositoryFormatKnitPack3(RepositoryFormatPack):
2350
"""A subtrees parameterized Pack repository.
2352
This repository format uses the xml7 serializer to get:
2353
- support for recording full info about the tree root
2354
- support for recording tree-references
2356
This format was introduced in 0.92.
2359
repository_class = KnitPackRepository
2360
_commit_builder_class = PackRootCommitBuilder
2361
rich_root_data = True
2362
supports_tree_reference = True
2364
def _serializer(self):
2365
return xml7.serializer_v7
2366
# What index classes to use
2367
index_builder_class = InMemoryGraphIndex
2368
index_class = GraphIndex
2370
def _get_matching_bzrdir(self):
2371
return bzrdir.format_registry.make_bzrdir(
2372
'pack-0.92-subtree')
2374
def _ignore_setting_bzrdir(self, format):
2377
_matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
2379
def check_conversion_target(self, target_format):
2380
if not target_format.rich_root_data:
2381
raise errors.BadConversionTarget(
2382
'Does not support rich root data.', target_format)
2383
if not getattr(target_format, 'supports_tree_reference', False):
2384
raise errors.BadConversionTarget(
2385
'Does not support nested trees', target_format)
2387
def get_format_string(self):
2388
"""See RepositoryFormat.get_format_string()."""
2389
return "Bazaar pack repository format 1 with subtree support (needs bzr 0.92)\n"
2391
def get_format_description(self):
2392
"""See RepositoryFormat.get_format_description()."""
2393
return "Packs containing knits with subtree support\n"
2396
class RepositoryFormatKnitPack4(RepositoryFormatPack):
2397
"""A rich-root, no subtrees parameterized Pack repository.
2399
This repository format uses the xml6 serializer to get:
2400
- support for recording full info about the tree root
2402
This format was introduced in 1.0.
2405
repository_class = KnitPackRepository
2406
_commit_builder_class = PackRootCommitBuilder
2407
rich_root_data = True
2408
supports_tree_reference = False
2410
def _serializer(self):
2411
return xml6.serializer_v6
2412
# What index classes to use
2413
index_builder_class = InMemoryGraphIndex
2414
index_class = GraphIndex
2416
def _get_matching_bzrdir(self):
2417
return bzrdir.format_registry.make_bzrdir(
2420
def _ignore_setting_bzrdir(self, format):
2423
_matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
2425
def check_conversion_target(self, target_format):
2426
if not target_format.rich_root_data:
2427
raise errors.BadConversionTarget(
2428
'Does not support rich root data.', target_format)
2430
def get_format_string(self):
2431
"""See RepositoryFormat.get_format_string()."""
2432
return ("Bazaar pack repository format 1 with rich root"
2433
" (needs bzr 1.0)\n")
2435
def get_format_description(self):
2436
"""See RepositoryFormat.get_format_description()."""
2437
return "Packs containing knits with rich root support\n"
2440
class RepositoryFormatKnitPack5(RepositoryFormatPack):
2441
"""Repository that supports external references to allow stacking.
2445
Supports external lookups, which results in non-truncated ghosts after
2446
reconcile compared to pack-0.92 formats.
2449
repository_class = KnitPackRepository
2450
_commit_builder_class = PackCommitBuilder
2451
supports_external_lookups = True
2452
# What index classes to use
2453
index_builder_class = InMemoryGraphIndex
2454
index_class = GraphIndex
2457
def _serializer(self):
2458
return xml5.serializer_v5
2460
def _get_matching_bzrdir(self):
2461
return bzrdir.format_registry.make_bzrdir('1.6')
2463
def _ignore_setting_bzrdir(self, format):
2466
_matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
2468
def get_format_string(self):
2469
"""See RepositoryFormat.get_format_string()."""
2470
return "Bazaar RepositoryFormatKnitPack5 (bzr 1.6)\n"
2472
def get_format_description(self):
2473
"""See RepositoryFormat.get_format_description()."""
2474
return "Packs 5 (adds stacking support, requires bzr 1.6)"
2476
def check_conversion_target(self, target_format):
2480
class RepositoryFormatKnitPack5RichRoot(RepositoryFormatPack):
2481
"""A repository with rich roots and stacking.
2483
New in release 1.6.1.
2485
Supports stacking on other repositories, allowing data to be accessed
2486
without being stored locally.
2489
repository_class = KnitPackRepository
2490
_commit_builder_class = PackRootCommitBuilder
2491
rich_root_data = True
2492
supports_tree_reference = False # no subtrees
2493
supports_external_lookups = True
2494
# What index classes to use
2495
index_builder_class = InMemoryGraphIndex
2496
index_class = GraphIndex
2499
def _serializer(self):
2500
return xml6.serializer_v6
2502
def _get_matching_bzrdir(self):
2503
return bzrdir.format_registry.make_bzrdir(
2506
def _ignore_setting_bzrdir(self, format):
2509
_matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
2511
def check_conversion_target(self, target_format):
2512
if not target_format.rich_root_data:
2513
raise errors.BadConversionTarget(
2514
'Does not support rich root data.', target_format)
2516
def get_format_string(self):
2517
"""See RepositoryFormat.get_format_string()."""
2518
return "Bazaar RepositoryFormatKnitPack5RichRoot (bzr 1.6.1)\n"
2520
def get_format_description(self):
2521
return "Packs 5 rich-root (adds stacking support, requires bzr 1.6.1)"
2524
class RepositoryFormatKnitPack5RichRootBroken(RepositoryFormatPack):
2525
"""A repository with rich roots and external references.
2529
Supports external lookups, which results in non-truncated ghosts after
2530
reconcile compared to pack-0.92 formats.
2532
This format was deprecated because the serializer it uses accidentally
2533
supported subtrees, when the format was not intended to. This meant that
2534
someone could accidentally fetch from an incorrect repository.
2537
repository_class = KnitPackRepository
2538
_commit_builder_class = PackRootCommitBuilder
2539
rich_root_data = True
2540
supports_tree_reference = False # no subtrees
2542
supports_external_lookups = True
2543
# What index classes to use
2544
index_builder_class = InMemoryGraphIndex
2545
index_class = GraphIndex
2548
def _serializer(self):
2549
return xml7.serializer_v7
2551
def _get_matching_bzrdir(self):
2552
matching = bzrdir.format_registry.make_bzrdir(
2554
matching.repository_format = self
2557
def _ignore_setting_bzrdir(self, format):
2560
_matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
2562
def check_conversion_target(self, target_format):
2563
if not target_format.rich_root_data:
2564
raise errors.BadConversionTarget(
2565
'Does not support rich root data.', target_format)
2567
def get_format_string(self):
2568
"""See RepositoryFormat.get_format_string()."""
2569
return "Bazaar RepositoryFormatKnitPack5RichRoot (bzr 1.6)\n"
2571
def get_format_description(self):
2572
return ("Packs 5 rich-root (adds stacking support, requires bzr 1.6)"
2576
class RepositoryFormatKnitPack6(RepositoryFormatPack):
2577
"""A repository with stacking and btree indexes,
2578
without rich roots or subtrees.
2580
This is equivalent to pack-1.6 with B+Tree indices.
2583
repository_class = KnitPackRepository
2584
_commit_builder_class = PackCommitBuilder
2585
supports_external_lookups = True
2586
# What index classes to use
2587
index_builder_class = BTreeBuilder
2588
index_class = BTreeGraphIndex
2591
def _serializer(self):
2592
return xml5.serializer_v5
2594
def _get_matching_bzrdir(self):
2595
return bzrdir.format_registry.make_bzrdir('1.9')
2597
def _ignore_setting_bzrdir(self, format):
2600
_matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
2602
def get_format_string(self):
2603
"""See RepositoryFormat.get_format_string()."""
2604
return "Bazaar RepositoryFormatKnitPack6 (bzr 1.9)\n"
2606
def get_format_description(self):
2607
"""See RepositoryFormat.get_format_description()."""
2608
return "Packs 6 (uses btree indexes, requires bzr 1.9)"
2610
def check_conversion_target(self, target_format):
2614
class RepositoryFormatKnitPack6RichRoot(RepositoryFormatPack):
2615
"""A repository with rich roots, no subtrees, stacking and btree indexes.
2617
1.6-rich-root with B+Tree indices.
2620
repository_class = KnitPackRepository
2621
_commit_builder_class = PackRootCommitBuilder
2622
rich_root_data = True
2623
supports_tree_reference = False # no subtrees
2624
supports_external_lookups = True
2625
# What index classes to use
2626
index_builder_class = BTreeBuilder
2627
index_class = BTreeGraphIndex
2630
def _serializer(self):
2631
return xml6.serializer_v6
2633
def _get_matching_bzrdir(self):
2634
return bzrdir.format_registry.make_bzrdir(
2637
def _ignore_setting_bzrdir(self, format):
2640
_matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
2642
def check_conversion_target(self, target_format):
2643
if not target_format.rich_root_data:
2644
raise errors.BadConversionTarget(
2645
'Does not support rich root data.', target_format)
2647
def get_format_string(self):
2648
"""See RepositoryFormat.get_format_string()."""
2649
return "Bazaar RepositoryFormatKnitPack6RichRoot (bzr 1.9)\n"
2651
def get_format_description(self):
2652
return "Packs 6 rich-root (uses btree indexes, requires bzr 1.9)"
2655
class RepositoryFormatPackDevelopment2(RepositoryFormatPack):
2656
"""A no-subtrees development repository.
2658
This format should be retained until the second release after bzr 1.7.
2660
This is pack-1.6.1 with B+Tree indices.
2663
repository_class = KnitPackRepository
2664
_commit_builder_class = PackCommitBuilder
2665
supports_external_lookups = True
2666
# What index classes to use
2667
index_builder_class = BTreeBuilder
2668
index_class = BTreeGraphIndex
2671
def _serializer(self):
2672
return xml5.serializer_v5
2674
def _get_matching_bzrdir(self):
2675
return bzrdir.format_registry.make_bzrdir('development2')
2677
def _ignore_setting_bzrdir(self, format):
2680
_matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
2682
def get_format_string(self):
2683
"""See RepositoryFormat.get_format_string()."""
2684
return "Bazaar development format 2 (needs bzr.dev from before 1.8)\n"
2686
def get_format_description(self):
2687
"""See RepositoryFormat.get_format_description()."""
2688
return ("Development repository format, currently the same as "
2689
"1.6.1 with B+Trees.\n")
2691
def check_conversion_target(self, target_format):
2695
class RepositoryFormatPackDevelopment2Subtree(RepositoryFormatPack):
2696
"""A subtrees development repository.
2698
This format should be retained until the second release after bzr 1.7.
2700
1.6.1-subtree[as it might have been] with B+Tree indices.
2703
repository_class = KnitPackRepository
2704
_commit_builder_class = PackRootCommitBuilder
2705
rich_root_data = True
2706
supports_tree_reference = True
2707
supports_external_lookups = True
2708
# What index classes to use
2709
index_builder_class = BTreeBuilder
2710
index_class = BTreeGraphIndex
2713
def _serializer(self):
2714
return xml7.serializer_v7
2716
def _get_matching_bzrdir(self):
2717
return bzrdir.format_registry.make_bzrdir(
2718
'development2-subtree')
2720
def _ignore_setting_bzrdir(self, format):
2723
_matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
2725
def check_conversion_target(self, target_format):
2726
if not target_format.rich_root_data:
2727
raise errors.BadConversionTarget(
2728
'Does not support rich root data.', target_format)
2729
if not getattr(target_format, 'supports_tree_reference', False):
2730
raise errors.BadConversionTarget(
2731
'Does not support nested trees', target_format)
2733
def get_format_string(self):
2734
"""See RepositoryFormat.get_format_string()."""
2735
return ("Bazaar development format 2 with subtree support "
2736
"(needs bzr.dev from before 1.8)\n")
2738
def get_format_description(self):
2739
"""See RepositoryFormat.get_format_description()."""
2740
return ("Development repository format, currently the same as "
2741
"1.6.1-subtree with B+Tree indices.\n")