13
13
# You should have received a copy of the GNU General Public License
14
14
# along with this program; if not, write to the Free Software
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
17
from __future__ import absolute_import
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
22
17
from bzrlib.lazy_import import lazy_import
23
18
lazy_import(globals(), """
24
19
from itertools import izip
27
24
from bzrlib import (
39
29
from bzrlib.index import (
40
33
CombinedGraphIndex,
41
34
GraphIndexPrefixAdapter,
36
from bzrlib.knit import KnitGraphIndex, _PackAccess, _KnitData
37
from bzrlib.osutils import rand_chars
38
from bzrlib.pack import ContainerWriter
39
from bzrlib.store import revision
44
41
from bzrlib import (
51
from bzrlib.decorators import (
56
from bzrlib.lock import LogicalLockResult
54
from bzrlib.decorators import needs_read_lock, needs_write_lock
55
from bzrlib.repofmt.knitrepo import KnitRepository
57
56
from bzrlib.repository import (
60
RepositoryFormatMetaDir,
61
RepositoryWriteLockResult,
63
from bzrlib.vf_repository import (
64
MetaDirVersionedFileRepository,
65
MetaDirVersionedFileRepositoryFormat,
66
VersionedFileCommitBuilder,
67
VersionedFileRootCommitBuilder,
69
from bzrlib.trace import (
76
class PackCommitBuilder(VersionedFileCommitBuilder):
77
"""Subclass of VersionedFileCommitBuilder to add texts with pack semantics.
59
MetaDirRepositoryFormat,
62
import bzrlib.revision as _mod_revision
63
from bzrlib.store.revision.knit import KnitRevisionStore
64
from bzrlib.store.versioned import VersionedFileStore
65
from bzrlib.trace import mutter, note, warning
68
class PackCommitBuilder(CommitBuilder):
69
"""A subclass of CommitBuilder to add texts with pack semantics.
79
71
Specifically this uses one knit object rather than one knit object per
80
72
added text, reducing memory and object pressure.
83
def __init__(self, repository, parents, config, timestamp=None,
84
timezone=None, committer=None, revprops=None,
85
revision_id=None, lossy=False):
86
VersionedFileCommitBuilder.__init__(self, repository, parents, config,
87
timestamp=timestamp, timezone=timezone, committer=committer,
88
revprops=revprops, revision_id=revision_id, lossy=lossy)
89
self._file_graph = graph.Graph(
90
repository._pack_collection.text_index.combined_index)
92
def _heads(self, file_id, revision_ids):
93
keys = [(file_id, revision_id) for revision_id in revision_ids]
94
return set([key[1] for key in self._file_graph.heads(keys)])
97
class PackRootCommitBuilder(VersionedFileRootCommitBuilder):
75
def _add_text_to_weave(self, file_id, new_lines, parents, nostore_sha):
76
return self.repository._pack_collection._add_text_to_weave(file_id,
77
self._new_revision_id, new_lines, parents, nostore_sha,
81
class PackRootCommitBuilder(RootCommitBuilder):
98
82
"""A subclass of RootCommitBuilder to add texts with pack semantics.
100
84
Specifically this uses one knit object rather than one knit object per
101
85
added text, reducing memory and object pressure.
104
def __init__(self, repository, parents, config, timestamp=None,
105
timezone=None, committer=None, revprops=None,
106
revision_id=None, lossy=False):
107
super(PackRootCommitBuilder, self).__init__(repository, parents,
108
config, timestamp=timestamp, timezone=timezone,
109
committer=committer, revprops=revprops, revision_id=revision_id,
111
self._file_graph = graph.Graph(
112
repository._pack_collection.text_index.combined_index)
114
def _heads(self, file_id, revision_ids):
115
keys = [(file_id, revision_id) for revision_id in revision_ids]
116
return set([key[1] for key in self._file_graph.heads(keys)])
88
def _add_text_to_weave(self, file_id, new_lines, parents, nostore_sha):
89
return self.repository._pack_collection._add_text_to_weave(file_id,
90
self._new_revision_id, new_lines, parents, nostore_sha,
119
94
class Pack(object):
258
170
return not self.__eq__(other)
260
172
def __repr__(self):
261
return "<%s.%s object at 0x%x, %s, %s" % (
262
self.__class__.__module__, self.__class__.__name__, id(self),
263
self.pack_transport, self.name)
266
class ResumedPack(ExistingPack):
268
def __init__(self, name, revision_index, inventory_index, text_index,
269
signature_index, upload_transport, pack_transport, index_transport,
270
pack_collection, chk_index=None):
271
"""Create a ResumedPack object."""
272
ExistingPack.__init__(self, pack_transport, name, revision_index,
273
inventory_index, text_index, signature_index,
275
self.upload_transport = upload_transport
276
self.index_transport = index_transport
277
self.index_sizes = [None, None, None, None]
279
('revision', revision_index),
280
('inventory', inventory_index),
281
('text', text_index),
282
('signature', signature_index),
284
if chk_index is not None:
285
indices.append(('chk', chk_index))
286
self.index_sizes.append(None)
287
for index_type, index in indices:
288
offset = self.index_offset(index_type)
289
self.index_sizes[offset] = index._size
290
self.index_class = pack_collection._index_class
291
self._pack_collection = pack_collection
292
self._state = 'resumed'
293
# XXX: perhaps check that the .pack file exists?
295
def access_tuple(self):
296
if self._state == 'finished':
297
return Pack.access_tuple(self)
298
elif self._state == 'resumed':
299
return self.upload_transport, self.file_name()
301
raise AssertionError(self._state)
304
self.upload_transport.delete(self.file_name())
305
indices = [self.revision_index, self.inventory_index, self.text_index,
306
self.signature_index]
307
if self.chk_index is not None:
308
indices.append(self.chk_index)
309
for index in indices:
310
index._transport.delete(index._name)
313
self._check_references()
314
index_types = ['revision', 'inventory', 'text', 'signature']
315
if self.chk_index is not None:
316
index_types.append('chk')
317
for index_type in index_types:
318
old_name = self.index_name(index_type, self.name)
319
new_name = '../indices/' + old_name
320
self.upload_transport.move(old_name, new_name)
321
self._replace_index_with_readonly(index_type)
322
new_name = '../packs/' + self.file_name()
323
self.upload_transport.move(self.file_name(), new_name)
324
self._state = 'finished'
326
def _get_external_refs(self, index):
327
"""Return compression parents for this index that are not present.
329
This returns any compression parents that are referenced by this index,
330
which are not contained *in* this index. They may be present elsewhere.
332
return index.external_references(1)
173
return "<bzrlib.repofmt.pack_repo.Pack object at 0x%x, %s, %s" % (
174
id(self), self.transport, self.name)
335
177
class NewPack(Pack):
336
178
"""An in memory proxy for a pack which is being created."""
338
def __init__(self, pack_collection, upload_suffix='', file_mode=None):
180
# A map of index 'type' to the file extension and position in the
182
index_definitions = {
183
'revision': ('.rix', 0),
184
'inventory': ('.iix', 1),
186
'signature': ('.six', 3),
189
def __init__(self, upload_transport, index_transport, pack_transport,
339
191
"""Create a NewPack instance.
341
:param pack_collection: A PackCollection into which this is being inserted.
193
:param upload_transport: A writable transport for the pack to be
194
incrementally uploaded to.
195
:param index_transport: A writable transport for the pack's indices to
196
be written to when the pack is finished.
197
:param pack_transport: A writable transport for the pack to be renamed
198
to when the upload is complete. This *must* be the same as
199
upload_transport.clone('../packs').
342
200
:param upload_suffix: An optional suffix to be given to any temporary
343
201
files created during the pack creation. e.g '.autopack'
344
:param file_mode: Unix permissions for newly created file.
346
203
# The relative locations of the packs are constrained, but all are
347
204
# passed in because the caller has them, so as to avoid object churn.
348
index_builder_class = pack_collection._index_builder_class
349
if pack_collection.chk_index is not None:
350
chk_index = index_builder_class(reference_lists=0)
353
205
Pack.__init__(self,
354
206
# Revisions: parents list, no text compression.
355
index_builder_class(reference_lists=1),
207
InMemoryGraphIndex(reference_lists=1),
356
208
# Inventory: We want to map compression only, but currently the
357
209
# knit code hasn't been updated enough to understand that, so we
358
210
# have a regular 2-list index giving parents and compression
360
index_builder_class(reference_lists=2),
212
InMemoryGraphIndex(reference_lists=2),
361
213
# Texts: compression and per file graph, for all fileids - so two
362
214
# reference lists and two elements in the key tuple.
363
index_builder_class(reference_lists=2, key_elements=2),
215
InMemoryGraphIndex(reference_lists=2, key_elements=2),
364
216
# Signatures: Just blobs to store, no compression, no parents
366
index_builder_class(reference_lists=0),
367
# CHK based storage - just blobs, no compression or parents.
218
InMemoryGraphIndex(reference_lists=0),
370
self._pack_collection = pack_collection
371
# When we make readonly indices, we need this.
372
self.index_class = pack_collection._index_class
373
220
# where should the new pack be opened
374
self.upload_transport = pack_collection._upload_transport
221
self.upload_transport = upload_transport
375
222
# where are indices written out to
376
self.index_transport = pack_collection._index_transport
223
self.index_transport = index_transport
377
224
# where is the pack renamed to when it is finished?
378
self.pack_transport = pack_collection._pack_transport
379
# What file mode to upload the pack and indices with.
380
self._file_mode = file_mode
225
self.pack_transport = pack_transport
381
226
# tracks the content written to the .pack file.
382
self._hash = osutils.md5()
383
# a tuple with the length in bytes of the indices, once the pack
384
# is finalised. (rev, inv, text, sigs, chk_if_in_use)
227
self._hash = md5.new()
228
# a four-tuple with the length in bytes of the indices, once the pack
229
# is finalised. (rev, inv, text, sigs)
385
230
self.index_sizes = None
386
231
# How much data to cache when writing packs. Note that this is not
387
232
# synchronised with reads, because it's not in the transport layer, so
721
532
def open_pack(self):
722
533
"""Open a pack for the pack we are creating."""
723
new_pack = self._pack_collection.pack_factory(self._pack_collection,
724
upload_suffix=self.suffix,
725
file_mode=self._pack_collection.repo.bzrdir._get_file_mode())
726
# We know that we will process all nodes in order, and don't need to
727
# query, so don't combine any indices spilled to disk until we are done
728
new_pack.revision_index.set_optimize(combine_backing_indices=False)
729
new_pack.inventory_index.set_optimize(combine_backing_indices=False)
730
new_pack.text_index.set_optimize(combine_backing_indices=False)
731
new_pack.signature_index.set_optimize(combine_backing_indices=False)
734
def _copy_revision_texts(self):
735
"""Copy revision data to the new pack."""
736
raise NotImplementedError(self._copy_revision_texts)
738
def _copy_inventory_texts(self):
739
"""Copy the inventory texts to the new pack.
741
self._revision_keys is used to determine what inventories to copy.
743
Sets self._text_filter appropriately.
745
raise NotImplementedError(self._copy_inventory_texts)
747
def _copy_text_texts(self):
748
raise NotImplementedError(self._copy_text_texts)
534
return NewPack(self._pack_collection._upload_transport,
535
self._pack_collection._index_transport,
536
self._pack_collection._pack_transport, upload_suffix=self.suffix)
750
538
def _create_pack_from_packs(self):
751
raise NotImplementedError(self._create_pack_from_packs)
539
self.pb.update("Opening pack", 0, 5)
540
new_pack = self.open_pack()
541
# buffer data - we won't be reading-back during the pack creation and
542
# this makes a significant difference on sftp pushes.
543
new_pack.set_write_cache_size(1024*1024)
544
if 'pack' in debug.debug_flags:
545
plain_pack_list = ['%s%s' % (a_pack.pack_transport.base, a_pack.name)
546
for a_pack in self.packs]
547
if self.revision_ids is not None:
548
rev_count = len(self.revision_ids)
551
mutter('%s: create_pack: creating pack from source packs: '
552
'%s%s %s revisions wanted %s t=0',
553
time.ctime(), self._pack_collection._upload_transport.base, new_pack.random_name,
554
plain_pack_list, rev_count)
556
if self.revision_ids:
557
revision_keys = [(revision_id,) for revision_id in self.revision_ids]
753
def _log_copied_texts(self):
561
# select revision keys
562
revision_index_map = self._pack_collection._packs_list_to_pack_map_and_index_list(
563
self.packs, 'revision_index')[0]
564
revision_nodes = self._pack_collection._index_contents(revision_index_map, revision_keys)
565
# copy revision keys and adjust values
566
self.pb.update("Copying revision texts", 1)
567
list(self._copy_nodes_graph(revision_nodes, revision_index_map,
568
new_pack._writer, new_pack.revision_index))
569
if 'pack' in debug.debug_flags:
570
mutter('%s: create_pack: revisions copied: %s%s %d items t+%6.3fs',
571
time.ctime(), self._pack_collection._upload_transport.base, new_pack.random_name,
572
new_pack.revision_index.key_count(),
573
time.time() - new_pack.start_time)
574
# select inventory keys
575
inv_keys = revision_keys # currently the same keyspace, and note that
576
# querying for keys here could introduce a bug where an inventory item
577
# is missed, so do not change it to query separately without cross
578
# checking like the text key check below.
579
inventory_index_map = self._pack_collection._packs_list_to_pack_map_and_index_list(
580
self.packs, 'inventory_index')[0]
581
inv_nodes = self._pack_collection._index_contents(inventory_index_map, inv_keys)
582
# copy inventory keys and adjust values
583
# XXX: Should be a helper function to allow different inv representation
585
self.pb.update("Copying inventory texts", 2)
586
inv_lines = self._copy_nodes_graph(inv_nodes, inventory_index_map,
587
new_pack._writer, new_pack.inventory_index, output_lines=True)
588
if self.revision_ids:
589
fileid_revisions = self._pack_collection.repo._find_file_ids_from_xml_inventory_lines(
590
inv_lines, self.revision_ids)
592
for fileid, file_revids in fileid_revisions.iteritems():
594
[(fileid, file_revid) for file_revid in file_revids])
596
# eat the iterator to cause it to execute.
599
if 'pack' in debug.debug_flags:
600
mutter('%s: create_pack: inventories copied: %s%s %d items t+%6.3fs',
601
time.ctime(), self._pack_collection._upload_transport.base, new_pack.random_name,
602
new_pack.inventory_index.key_count(),
603
time.time() - new_pack.start_time)
605
text_index_map = self._pack_collection._packs_list_to_pack_map_and_index_list(
606
self.packs, 'text_index')[0]
607
text_nodes = self._pack_collection._index_contents(text_index_map, text_filter)
608
if text_filter is not None:
609
# We could return the keys copied as part of the return value from
610
# _copy_nodes_graph but this doesn't work all that well with the
611
# need to get line output too, so we check separately, and as we're
612
# going to buffer everything anyway, we check beforehand, which
613
# saves reading knit data over the wire when we know there are
615
text_nodes = set(text_nodes)
616
present_text_keys = set(_node[1] for _node in text_nodes)
617
missing_text_keys = set(text_filter) - present_text_keys
618
if missing_text_keys:
619
# TODO: raise a specific error that can handle many missing
621
a_missing_key = missing_text_keys.pop()
622
raise errors.RevisionNotPresent(a_missing_key[1],
624
# copy text keys and adjust values
625
self.pb.update("Copying content texts", 3)
626
list(self._copy_nodes_graph(text_nodes, text_index_map,
627
new_pack._writer, new_pack.text_index))
754
628
if 'pack' in debug.debug_flags:
755
629
mutter('%s: create_pack: file texts copied: %s%s %d items t+%6.3fs',
756
time.ctime(), self._pack_collection._upload_transport.base,
757
self.new_pack.random_name,
758
self.new_pack.text_index.key_count(),
759
time.time() - self.new_pack.start_time)
761
def _use_pack(self, new_pack):
762
"""Return True if new_pack should be used.
764
:param new_pack: The pack that has just been created.
765
:return: True if the pack should be used.
630
time.ctime(), self._pack_collection._upload_transport.base, new_pack.random_name,
631
new_pack.text_index.key_count(),
632
time.time() - new_pack.start_time)
633
# select signature keys
634
signature_filter = revision_keys # same keyspace
635
signature_index_map = self._pack_collection._packs_list_to_pack_map_and_index_list(
636
self.packs, 'signature_index')[0]
637
signature_nodes = self._pack_collection._index_contents(signature_index_map,
639
# copy signature keys and adjust values
640
self.pb.update("Copying signature texts", 4)
641
self._copy_nodes(signature_nodes, signature_index_map, new_pack._writer,
642
new_pack.signature_index)
643
if 'pack' in debug.debug_flags:
644
mutter('%s: create_pack: revision signatures copied: %s%s %d items t+%6.3fs',
645
time.ctime(), self._pack_collection._upload_transport.base, new_pack.random_name,
646
new_pack.signature_index.key_count(),
647
time.time() - new_pack.start_time)
648
if not new_pack.data_inserted():
651
self.pb.update("Finishing pack", 5)
653
self._pack_collection.allocate(new_pack)
656
def _copy_nodes(self, nodes, index_map, writer, write_index):
657
"""Copy knit nodes between packs with no graph references."""
658
pb = ui.ui_factory.nested_progress_bar()
660
return self._do_copy_nodes(nodes, index_map, writer,
665
def _do_copy_nodes(self, nodes, index_map, writer, write_index, pb):
666
# for record verification
667
knit_data = _KnitData(None)
668
# plan a readv on each source pack:
670
nodes = sorted(nodes)
671
# how to map this into knit.py - or knit.py into this?
672
# we don't want the typical knit logic, we want grouping by pack
673
# at this point - perhaps a helper library for the following code
674
# duplication points?
676
for index, key, value in nodes:
677
if index not in request_groups:
678
request_groups[index] = []
679
request_groups[index].append((key, value))
681
pb.update("Copied record", record_index, len(nodes))
682
for index, items in request_groups.iteritems():
683
pack_readv_requests = []
684
for key, value in items:
685
# ---- KnitGraphIndex.get_position
686
bits = value[1:].split(' ')
687
offset, length = int(bits[0]), int(bits[1])
688
pack_readv_requests.append((offset, length, (key, value[0])))
689
# linear scan up the pack
690
pack_readv_requests.sort()
692
transport, path = index_map[index]
693
reader = pack.make_readv_reader(transport, path,
694
[offset[0:2] for offset in pack_readv_requests])
695
for (names, read_func), (_1, _2, (key, eol_flag)) in \
696
izip(reader.iter_records(), pack_readv_requests):
697
raw_data = read_func(None)
698
# check the header only
699
df, _ = knit_data._parse_record_header(key[-1], raw_data)
701
pos, size = writer.add_bytes_record(raw_data, names)
702
write_index.add_node(key, eol_flag + "%d %d" % (pos, size))
703
pb.update("Copied record", record_index)
706
def _copy_nodes_graph(self, nodes, index_map, writer, write_index,
708
"""Copy knit nodes between packs.
710
:param output_lines: Return lines present in the copied data as
711
an iterator of line,version_id.
767
return new_pack.data_inserted()
713
pb = ui.ui_factory.nested_progress_bar()
715
return self._do_copy_nodes_graph(nodes, index_map, writer,
716
write_index, output_lines, pb)
720
def _do_copy_nodes_graph(self, nodes, index_map, writer, write_index,
722
# for record verification
723
knit_data = _KnitData(None)
724
# for line extraction when requested (inventories only)
726
factory = knit.KnitPlainFactory()
727
# plan a readv on each source pack:
729
nodes = sorted(nodes)
730
# how to map this into knit.py - or knit.py into this?
731
# we don't want the typical knit logic, we want grouping by pack
732
# at this point - perhaps a helper library for the following code
733
# duplication points?
736
pb.update("Copied record", record_index, len(nodes))
737
for index, key, value, references in nodes:
738
if index not in request_groups:
739
request_groups[index] = []
740
request_groups[index].append((key, value, references))
741
for index, items in request_groups.iteritems():
742
pack_readv_requests = []
743
for key, value, references in items:
744
# ---- KnitGraphIndex.get_position
745
bits = value[1:].split(' ')
746
offset, length = int(bits[0]), int(bits[1])
747
pack_readv_requests.append((offset, length, (key, value[0], references)))
748
# linear scan up the pack
749
pack_readv_requests.sort()
751
transport, path = index_map[index]
752
reader = pack.make_readv_reader(transport, path,
753
[offset[0:2] for offset in pack_readv_requests])
754
for (names, read_func), (_1, _2, (key, eol_flag, references)) in \
755
izip(reader.iter_records(), pack_readv_requests):
756
raw_data = read_func(None)
759
# read the entire thing
760
content, _ = knit_data._parse_record(version_id, raw_data)
761
if len(references[-1]) == 0:
762
line_iterator = factory.get_fulltext_content(content)
764
line_iterator = factory.get_linedelta_content(content)
765
for line in line_iterator:
766
yield line, version_id
768
# check the header only
769
df, _ = knit_data._parse_record_header(version_id, raw_data)
771
pos, size = writer.add_bytes_record(raw_data, names)
772
write_index.add_node(key, eol_flag + "%d %d" % (pos, size), references)
773
pb.update("Copied record", record_index)
777
class ReconcilePacker(Packer):
778
"""A packer which regenerates indices etc as it copies.
780
This is used by ``bzr reconcile`` to cause parent text pointers to be
770
785
class RepositoryPackCollection(object):
771
"""Management of packs within a repository.
773
:ivar _names: map of {pack_name: (index_size,)}
777
resumed_pack_factory = None
778
normal_packer_class = None
779
optimising_packer_class = None
786
"""Management of packs within a repository."""
781
788
def __init__(self, repo, transport, index_transport, upload_transport,
782
pack_transport, index_builder_class, index_class,
784
790
"""Create a new RepositoryPackCollection.
786
:param transport: Addresses the repository base directory
792
:param transport: Addresses the repository base directory
787
793
(typically .bzr/repository/).
788
794
:param index_transport: Addresses the directory containing indices.
789
795
:param upload_transport: Addresses the directory into which packs are written
790
796
while they're being created.
791
797
:param pack_transport: Addresses the directory of existing complete packs.
792
:param index_builder_class: The index builder class to use.
793
:param index_class: The index class to use.
794
:param use_chk_index: Whether to setup and manage a CHK index.
796
# XXX: This should call self.reset()
798
800
self.transport = transport
799
801
self._index_transport = index_transport
800
802
self._upload_transport = upload_transport
801
803
self._pack_transport = pack_transport
802
self._index_builder_class = index_builder_class
803
self._index_class = index_class
804
self._suffix_offsets = {'.rix': 0, '.iix': 1, '.tix': 2, '.six': 3,
804
self._suffix_offsets = {'.rix': 0, '.iix': 1, '.tix': 2, '.six': 3}
807
806
# name:Pack mapping
809
807
self._packs_by_name = {}
810
808
# the previous pack-names content
811
809
self._packs_at_load = None
812
810
# when a pack is being created by this object, the state of that pack.
813
811
self._new_pack = None
814
812
# aggregated revision index data
815
flush = self._flush_new_pack
816
self.revision_index = AggregateIndex(self.reload_pack_names, flush)
817
self.inventory_index = AggregateIndex(self.reload_pack_names, flush)
818
self.text_index = AggregateIndex(self.reload_pack_names, flush)
819
self.signature_index = AggregateIndex(self.reload_pack_names, flush)
820
all_indices = [self.revision_index, self.inventory_index,
821
self.text_index, self.signature_index]
823
self.chk_index = AggregateIndex(self.reload_pack_names, flush)
824
all_indices.append(self.chk_index)
826
# used to determine if we're using a chk_index elsewhere.
827
self.chk_index = None
828
# Tell all the CombinedGraphIndex objects about each other, so they can
829
# share hints about which pack names to search first.
830
all_combined = [agg_idx.combined_index for agg_idx in all_indices]
831
for combined_idx in all_combined:
832
combined_idx.set_sibling_indices(
833
set(all_combined).difference([combined_idx]))
835
self._resumed_packs = []
836
self.config_stack = config.LocationStack(self.transport.base)
839
return '%s(%r)' % (self.__class__.__name__, self.repo)
813
self.revision_index = AggregateIndex()
814
self.inventory_index = AggregateIndex()
815
self.text_index = AggregateIndex()
816
self.signature_index = AggregateIndex()
841
818
def add_pack_to_memory(self, pack):
842
819
"""Make a Pack object available to the repository to satisfy queries.
844
821
:param pack: A Pack object.
846
if pack.name in self._packs_by_name:
847
raise AssertionError(
848
'pack %s already in _packs_by_name' % (pack.name,))
823
assert pack.name not in self._packs_by_name
849
824
self.packs.append(pack)
850
825
self._packs_by_name[pack.name] = pack
851
826
self.revision_index.add_index(pack.revision_index, pack)
852
827
self.inventory_index.add_index(pack.inventory_index, pack)
853
828
self.text_index.add_index(pack.text_index, pack)
854
829
self.signature_index.add_index(pack.signature_index, pack)
855
if self.chk_index is not None:
856
self.chk_index.add_index(pack.chk_index, pack)
831
def _add_text_to_weave(self, file_id, revision_id, new_lines, parents,
832
nostore_sha, random_revid):
833
file_id_index = GraphIndexPrefixAdapter(
834
self.text_index.combined_index,
836
add_nodes_callback=self.text_index.add_callback)
837
self.repo._text_knit._index._graph_index = file_id_index
838
self.repo._text_knit._index._add_callback = file_id_index.add_nodes
839
return self.repo._text_knit.add_lines_with_ghosts(
840
revision_id, parents, new_lines, nostore_sha=nostore_sha,
841
random_id=random_revid, check_content=False)[0:2]
858
843
def all_packs(self):
859
844
"""Return a list of all the Pack objects this repository has.
910
891
# group their data with the relevant commit, and that may
911
892
# involve rewriting ancient history - which autopack tries to
912
893
# avoid. Alternatively we could not group the data but treat
913
# each of these as having a single revision, and thus add
894
# each of these as having a single revision, and thus add
914
895
# one revision for each to the total revision count, to get
915
896
# a matching distribution.
917
898
existing_packs.append((revision_count, pack))
918
899
pack_operations = self.plan_autopack_combinations(
919
900
existing_packs, pack_distribution)
920
num_new_packs = len(pack_operations)
921
num_old_packs = sum([len(po[1]) for po in pack_operations])
922
num_revs_affected = sum([po[0] for po in pack_operations])
923
mutter('Auto-packing repository %s, which has %d pack files, '
924
'containing %d revisions. Packing %d files into %d affecting %d'
925
' revisions', self, total_packs, total_revisions, num_old_packs,
926
num_new_packs, num_revs_affected)
927
result = self._execute_pack_operations(pack_operations, packer_class=self.normal_packer_class,
928
reload_func=self._restart_autopack)
929
mutter('Auto-packing repository %s completed', self)
901
self._execute_pack_operations(pack_operations)
932
def _execute_pack_operations(self, pack_operations, packer_class,
904
def _execute_pack_operations(self, pack_operations):
934
905
"""Execute a series of pack operations.
936
907
:param pack_operations: A list of [revision_count, packs_to_combine].
937
:param packer_class: The class of packer to use
938
:return: The new pack names.
940
910
for revision_count, packs in pack_operations:
941
911
# we may have no-ops from the setup logic
942
912
if len(packs) == 0:
944
packer = packer_class(self, packs, '.autopack',
945
reload_func=reload_func)
947
result = packer.pack()
948
except errors.RetryWithNewPacks:
949
# An exception is propagating out of this context, make sure
950
# this packer has cleaned up. Packer() doesn't set its new_pack
951
# state into the RepositoryPackCollection object, so we only
952
# have access to it directly here.
953
if packer.new_pack is not None:
954
packer.new_pack.abort()
914
Packer(self, packs, '.autopack').pack()
958
915
for pack in packs:
959
916
self._remove_pack_from_memory(pack)
960
917
# record the newly available packs and stop advertising the old
963
for _, packs in pack_operations:
964
to_be_obsoleted.extend(packs)
965
result = self._save_pack_names(clear_obsolete_packs=True,
966
obsolete_packs=to_be_obsoleted)
969
def _flush_new_pack(self):
970
if self._new_pack is not None:
971
self._new_pack.flush()
919
self._save_pack_names(clear_obsolete_packs=True)
920
# Move the old packs out of the way now they are no longer referenced.
921
for revision_count, packs in pack_operations:
922
self._obsolete_packs(packs)
973
924
def lock_names(self):
974
925
"""Acquire the mutex around the pack-names index.
976
927
This cannot be used in the middle of a read-only transaction on the
979
930
self.repo.control_files.lock_write()
981
def _already_packed(self):
982
"""Is the collection already packed?"""
983
return not (self.repo._format.pack_compresses or (len(self._names) > 1))
985
def pack(self, hint=None, clean_obsolete_packs=False):
986
933
"""Pack the pack collection totally."""
987
934
self.ensure_loaded()
988
935
total_packs = len(self._names)
989
if self._already_packed():
991
938
total_revisions = self.revision_index.combined_index.key_count()
992
939
# XXX: the following may want to be a class, to pack with a given
994
941
mutter('Packing repository %s, which has %d pack files, '
995
'containing %d revisions with hint %r.', self, total_packs,
996
total_revisions, hint)
999
self._try_pack_operations(hint)
1000
except RetryPackOperations:
1004
if clean_obsolete_packs:
1005
self._clear_obsolete_packs()
1007
def _try_pack_operations(self, hint):
1008
"""Calculate the pack operations based on the hint (if any), and
942
'containing %d revisions into 1 packs.', self, total_packs,
1011
944
# determine which packs need changing
945
pack_distribution = [1]
1012
946
pack_operations = [[0, []]]
1013
947
for pack in self.all_packs():
1014
if hint is None or pack.name in hint:
1015
# Either no hint was provided (so we are packing everything),
1016
# or this pack was included in the hint.
1017
pack_operations[-1][0] += pack.get_revision_count()
1018
pack_operations[-1][1].append(pack)
1019
self._execute_pack_operations(pack_operations,
1020
packer_class=self.optimising_packer_class,
1021
reload_func=self._restart_pack_operations)
948
revision_count = pack.get_revision_count()
949
pack_operations[-1][0] += revision_count
950
pack_operations[-1][1].append(pack)
951
self._execute_pack_operations(pack_operations)
1023
953
def plan_autopack_combinations(self, existing_packs, pack_distribution):
1024
954
"""Plan a pack operation.
1321
1158
self._packs_by_name = {}
1322
1159
self._packs_at_load = None
1161
def _make_index_map(self, index_suffix):
1162
"""Return information on existing indices.
1164
:param suffix: Index suffix added to pack name.
1166
:returns: (pack_map, indices) where indices is a list of GraphIndex
1167
objects, and pack_map is a mapping from those objects to the
1168
pack tuple they describe.
1170
# TODO: stop using this; it creates new indices unnecessarily.
1171
self.ensure_loaded()
1172
suffix_map = {'.rix': 'revision_index',
1173
'.six': 'signature_index',
1174
'.iix': 'inventory_index',
1175
'.tix': 'text_index',
1177
return self._packs_list_to_pack_map_and_index_list(self.all_packs(),
1178
suffix_map[index_suffix])
1180
def _packs_list_to_pack_map_and_index_list(self, packs, index_attribute):
1181
"""Convert a list of packs to an index pack map and index list.
1183
:param packs: The packs list to process.
1184
:param index_attribute: The attribute that the desired index is found
1186
:return: A tuple (map, list) where map contains the dict from
1187
index:pack_tuple, and lsit contains the indices in the same order
1193
index = getattr(pack, index_attribute)
1194
indices.append(index)
1195
pack_map[index] = (pack.pack_transport, pack.file_name())
1196
return pack_map, indices
1198
def _index_contents(self, pack_map, key_filter=None):
1199
"""Get an iterable of the index contents from a pack_map.
1201
:param pack_map: A map from indices to pack details.
1202
:param key_filter: An optional filter to limit the
1205
indices = [index for index in pack_map.iterkeys()]
1206
all_index = CombinedGraphIndex(indices)
1207
if key_filter is None:
1208
return all_index.iter_all_entries()
1210
return all_index.iter_entries(key_filter)
1324
1212
def _unlock_names(self):
1325
1213
"""Release the mutex around the pack-names index."""
1326
1214
self.repo.control_files.unlock()
1328
def _diff_pack_names(self):
1329
"""Read the pack names from disk, and compare it to the one in memory.
1331
:return: (disk_nodes, deleted_nodes, new_nodes)
1332
disk_nodes The final set of nodes that should be referenced
1333
deleted_nodes Nodes which have been removed from when we started
1334
new_nodes Nodes that are newly introduced
1336
# load the disk nodes across
1338
for index, key, value in self._iter_disk_pack_index():
1339
disk_nodes.add((key, value))
1340
orig_disk_nodes = set(disk_nodes)
1342
# do a two-way diff against our original content
1343
current_nodes = set()
1344
for name, sizes in self._names.iteritems():
1346
((name, ), ' '.join(str(size) for size in sizes)))
1348
# Packs no longer present in the repository, which were present when we
1349
# locked the repository
1350
deleted_nodes = self._packs_at_load - current_nodes
1351
# Packs which this process is adding
1352
new_nodes = current_nodes - self._packs_at_load
1354
# Update the disk_nodes set to include the ones we are adding, and
1355
# remove the ones which were removed by someone else
1356
disk_nodes.difference_update(deleted_nodes)
1357
disk_nodes.update(new_nodes)
1359
return disk_nodes, deleted_nodes, new_nodes, orig_disk_nodes
1361
def _syncronize_pack_names_from_disk_nodes(self, disk_nodes):
1362
"""Given the correct set of pack files, update our saved info.
1364
:return: (removed, added, modified)
1365
removed pack names removed from self._names
1366
added pack names added to self._names
1367
modified pack names that had changed value
1372
## self._packs_at_load = disk_nodes
1216
def _save_pack_names(self, clear_obsolete_packs=False):
1217
"""Save the list of packs.
1219
This will take out the mutex around the pack names list for the
1220
duration of the method call. If concurrent updates have been made, a
1221
three-way merge between the current list and the current in memory list
1224
:param clear_obsolete_packs: If True, clear out the contents of the
1225
obsolete_packs directory.
1229
builder = GraphIndexBuilder()
1230
# load the disk nodes across
1232
for index, key, value in self._iter_disk_pack_index():
1233
disk_nodes.add((key, value))
1234
# do a two-way diff against our original content
1235
current_nodes = set()
1236
for name, sizes in self._names.iteritems():
1238
((name, ), ' '.join(str(size) for size in sizes)))
1239
deleted_nodes = self._packs_at_load - current_nodes
1240
new_nodes = current_nodes - self._packs_at_load
1241
disk_nodes.difference_update(deleted_nodes)
1242
disk_nodes.update(new_nodes)
1243
# TODO: handle same-name, index-size-changes here -
1244
# e.g. use the value from disk, not ours, *unless* we're the one
1246
for key, value in disk_nodes:
1247
builder.add_node(key, value)
1248
self.transport.put_file('pack-names', builder.finish())
1249
# move the baseline forward
1250
self._packs_at_load = disk_nodes
1251
# now clear out the obsolete packs directory
1252
if clear_obsolete_packs:
1253
self.transport.clone('obsolete_packs').delete_multi(
1254
self.transport.list_dir('obsolete_packs'))
1256
self._unlock_names()
1257
# synchronise the memory packs list with what we just wrote:
1373
1258
new_names = dict(disk_nodes)
1374
1259
# drop no longer present nodes
1375
1260
for pack in self.all_packs():
1376
1261
if (pack.name,) not in new_names:
1377
removed.append(pack.name)
1378
1262
self._remove_pack_from_memory(pack)
1379
1263
# add new nodes/refresh existing ones
1380
1264
for key, value in disk_nodes:
1390
1274
# disk index because the set values are the same, unless
1391
1275
# the only index shows up as deleted by the set difference
1392
1276
# - which it may. Until there is a specific test for this,
1393
# assume it's broken. RBC 20071017.
1277
# assume its broken. RBC 20071017.
1394
1278
self._remove_pack_from_memory(self.get_pack_by_name(name))
1395
1279
self._names[name] = sizes
1396
1280
self.get_pack_by_name(name)
1397
modified.append(name)
1400
1283
self._names[name] = sizes
1401
1284
self.get_pack_by_name(name)
1403
return removed, added, modified
1405
def _save_pack_names(self, clear_obsolete_packs=False, obsolete_packs=None):
1406
"""Save the list of packs.
1408
This will take out the mutex around the pack names list for the
1409
duration of the method call. If concurrent updates have been made, a
1410
three-way merge between the current list and the current in memory list
1413
:param clear_obsolete_packs: If True, clear out the contents of the
1414
obsolete_packs directory.
1415
:param obsolete_packs: Packs that are obsolete once the new pack-names
1416
file has been written.
1417
:return: A list of the names saved that were not previously on disk.
1419
already_obsolete = []
1422
builder = self._index_builder_class()
1423
(disk_nodes, deleted_nodes, new_nodes,
1424
orig_disk_nodes) = self._diff_pack_names()
1425
# TODO: handle same-name, index-size-changes here -
1426
# e.g. use the value from disk, not ours, *unless* we're the one
1428
for key, value in disk_nodes:
1429
builder.add_node(key, value)
1430
self.transport.put_file('pack-names', builder.finish(),
1431
mode=self.repo.bzrdir._get_file_mode())
1432
self._packs_at_load = disk_nodes
1433
if clear_obsolete_packs:
1436
to_preserve = set([o.name for o in obsolete_packs])
1437
already_obsolete = self._clear_obsolete_packs(to_preserve)
1439
self._unlock_names()
1440
# synchronise the memory packs list with what we just wrote:
1441
self._syncronize_pack_names_from_disk_nodes(disk_nodes)
1443
# TODO: We could add one more condition here. "if o.name not in
1444
# orig_disk_nodes and o != the new_pack we haven't written to
1445
# disk yet. However, the new pack object is not easily
1446
# accessible here (it would have to be passed through the
1447
# autopacking code, etc.)
1448
obsolete_packs = [o for o in obsolete_packs
1449
if o.name not in already_obsolete]
1450
self._obsolete_packs(obsolete_packs)
1451
return [new_node[0][0] for new_node in new_nodes]
1453
def reload_pack_names(self):
1454
"""Sync our pack listing with what is present in the repository.
1456
This should be called when we find out that something we thought was
1457
present is now missing. This happens when another process re-packs the
1460
:return: True if the in-memory list of packs has been altered at all.
1462
# The ensure_loaded call is to handle the case where the first call
1463
# made involving the collection was to reload_pack_names, where we
1464
# don't have a view of disk contents. It's a bit of a bandaid, and
1465
# causes two reads of pack-names, but it's a rare corner case not
1466
# struck with regular push/pull etc.
1467
first_read = self.ensure_loaded()
1470
# out the new value.
1471
(disk_nodes, deleted_nodes, new_nodes,
1472
orig_disk_nodes) = self._diff_pack_names()
1473
# _packs_at_load is meant to be the explicit list of names in
1474
# 'pack-names' at then start. As such, it should not contain any
1475
# pending names that haven't been written out yet.
1476
self._packs_at_load = orig_disk_nodes
1478
modified) = self._syncronize_pack_names_from_disk_nodes(disk_nodes)
1479
if removed or added or modified:
1483
def _restart_autopack(self):
1484
"""Reload the pack names list, and restart the autopack code."""
1485
if not self.reload_pack_names():
1486
# Re-raise the original exception, because something went missing
1487
# and a restart didn't find it
1489
raise errors.RetryAutopack(self.repo, False, sys.exc_info())
1491
def _restart_pack_operations(self):
1492
"""Reload the pack names list, and restart the autopack code."""
1493
if not self.reload_pack_names():
1494
# Re-raise the original exception, because something went missing
1495
# and a restart didn't find it
1497
raise RetryPackOperations(self.repo, False, sys.exc_info())
1499
def _clear_obsolete_packs(self, preserve=None):
1500
"""Delete everything from the obsolete-packs directory.
1502
:return: A list of pack identifiers (the filename without '.pack') that
1503
were found in obsolete_packs.
1506
obsolete_pack_transport = self.transport.clone('obsolete_packs')
1507
if preserve is None:
1510
obsolete_pack_files = obsolete_pack_transport.list_dir('.')
1511
except errors.NoSuchFile:
1513
for filename in obsolete_pack_files:
1514
name, ext = osutils.splitext(filename)
1517
if name in preserve:
1520
obsolete_pack_transport.delete(filename)
1521
except (errors.PathError, errors.TransportError), e:
1522
warning("couldn't delete obsolete pack, skipping it:\n%s"
1526
1286
def _start_write_group(self):
1527
1287
# Do not permit preparation for writing if we're not in a 'write lock'.
1528
1288
if not self.repo.is_write_locked():
1529
1289
raise errors.NotWriteLocked(self)
1530
self._new_pack = self.pack_factory(self, upload_suffix='.pack',
1531
file_mode=self.repo.bzrdir._get_file_mode())
1290
self._new_pack = NewPack(self._upload_transport, self._index_transport,
1291
self._pack_transport, upload_suffix='.pack')
1532
1292
# allow writing: queue writes to a new index
1533
1293
self.revision_index.add_writable_index(self._new_pack.revision_index,
1534
1294
self._new_pack)
1536
1296
self._new_pack)
1537
1297
self.text_index.add_writable_index(self._new_pack.text_index,
1538
1298
self._new_pack)
1539
self._new_pack.text_index.set_optimize(combine_backing_indices=False)
1540
1299
self.signature_index.add_writable_index(self._new_pack.signature_index,
1541
1300
self._new_pack)
1542
if self.chk_index is not None:
1543
self.chk_index.add_writable_index(self._new_pack.chk_index,
1545
self.repo.chk_bytes._index._add_callback = self.chk_index.add_callback
1546
self._new_pack.chk_index.set_optimize(combine_backing_indices=False)
1548
self.repo.inventories._index._add_callback = self.inventory_index.add_callback
1549
self.repo.revisions._index._add_callback = self.revision_index.add_callback
1550
self.repo.signatures._index._add_callback = self.signature_index.add_callback
1551
self.repo.texts._index._add_callback = self.text_index.add_callback
1302
# reused revision and signature knits may need updating
1304
# "Hysterical raisins. client code in bzrlib grabs those knits outside
1305
# of write groups and then mutates it inside the write group."
1306
if self.repo._revision_knit is not None:
1307
self.repo._revision_knit._index._add_callback = \
1308
self.revision_index.add_callback
1309
if self.repo._signature_knit is not None:
1310
self.repo._signature_knit._index._add_callback = \
1311
self.signature_index.add_callback
1312
# create a reused knit object for text addition in commit.
1313
self.repo._text_knit = self.repo.weave_store.get_weave_or_empty(
1553
1316
def _abort_write_group(self):
1554
1317
# FIXME: just drop the transient index.
1555
1318
# forget what names there are
1556
if self._new_pack is not None:
1557
operation = cleanup.OperationWithCleanups(self._new_pack.abort)
1558
operation.add_cleanup(setattr, self, '_new_pack', None)
1559
# If we aborted while in the middle of finishing the write
1560
# group, _remove_pack_indices could fail because the indexes are
1561
# already gone. But they're not there we shouldn't fail in this
1562
# case, so we pass ignore_missing=True.
1563
operation.add_cleanup(self._remove_pack_indices, self._new_pack,
1564
ignore_missing=True)
1565
operation.run_simple()
1566
for resumed_pack in self._resumed_packs:
1567
operation = cleanup.OperationWithCleanups(resumed_pack.abort)
1568
# See comment in previous finally block.
1569
operation.add_cleanup(self._remove_pack_indices, resumed_pack,
1570
ignore_missing=True)
1571
operation.run_simple()
1572
del self._resumed_packs[:]
1574
def _remove_resumed_pack_indices(self):
1575
for resumed_pack in self._resumed_packs:
1576
self._remove_pack_indices(resumed_pack)
1577
del self._resumed_packs[:]
1579
def _check_new_inventories(self):
1580
"""Detect missing inventories in this write group.
1582
:returns: list of strs, summarising any problems found. If the list is
1583
empty no problems were found.
1585
# The base implementation does no checks. GCRepositoryPackCollection
1319
self._new_pack.abort()
1320
self._remove_pack_indices(self._new_pack)
1321
self._new_pack = None
1322
self.repo._text_knit = None
1589
1324
def _commit_write_group(self):
1591
for prefix, versioned_file in (
1592
('revisions', self.repo.revisions),
1593
('inventories', self.repo.inventories),
1594
('texts', self.repo.texts),
1595
('signatures', self.repo.signatures),
1597
missing = versioned_file.get_missing_compression_parent_keys()
1598
all_missing.update([(prefix,) + key for key in missing])
1600
raise errors.BzrCheckError(
1601
"Repository %s has missing compression parent(s) %r "
1602
% (self.repo, sorted(all_missing)))
1603
problems = self._check_new_inventories()
1605
problems_summary = '\n'.join(problems)
1606
raise errors.BzrCheckError(
1607
"Cannot add revision(s) to repository: " + problems_summary)
1608
1325
self._remove_pack_indices(self._new_pack)
1609
any_new_content = False
1610
1326
if self._new_pack.data_inserted():
1611
1327
# get all the data to disk and read to use
1612
1328
self._new_pack.finish()
1613
1329
self.allocate(self._new_pack)
1614
1330
self._new_pack = None
1615
any_new_content = True
1617
self._new_pack.abort()
1618
self._new_pack = None
1619
for resumed_pack in self._resumed_packs:
1620
# XXX: this is a pretty ugly way to turn the resumed pack into a
1621
# properly committed pack.
1622
self._names[resumed_pack.name] = None
1623
self._remove_pack_from_memory(resumed_pack)
1624
resumed_pack.finish()
1625
self.allocate(resumed_pack)
1626
any_new_content = True
1627
del self._resumed_packs[:]
1629
result = self.autopack()
1331
if not self.autopack():
1631
1332
# when autopack takes no steps, the names list is still
1633
return self._save_pack_names()
1637
def _suspend_write_group(self):
1638
tokens = [pack.name for pack in self._resumed_packs]
1639
self._remove_pack_indices(self._new_pack)
1640
if self._new_pack.data_inserted():
1641
# get all the data to disk and read to use
1642
self._new_pack.finish(suspend=True)
1643
tokens.append(self._new_pack.name)
1644
self._new_pack = None
1334
self._save_pack_names()
1646
1336
self._new_pack.abort()
1647
1337
self._new_pack = None
1648
self._remove_resumed_pack_indices()
1651
def _resume_write_group(self, tokens):
1652
for token in tokens:
1653
self._resume_pack(token)
1656
class PackRepository(MetaDirVersionedFileRepository):
1657
"""Repository with knit objects stored inside pack containers.
1659
The layering for a KnitPackRepository is:
1661
Graph | HPSS | Repository public layer |
1662
===================================================
1663
Tuple based apis below, string based, and key based apis above
1664
---------------------------------------------------
1666
Provides .texts, .revisions etc
1667
This adapts the N-tuple keys to physical knit records which only have a
1668
single string identifier (for historical reasons), which in older formats
1669
was always the revision_id, and in the mapped code for packs is always
1670
the last element of key tuples.
1671
---------------------------------------------------
1673
A separate GraphIndex is used for each of the
1674
texts/inventories/revisions/signatures contained within each individual
1675
pack file. The GraphIndex layer works in N-tuples and is unaware of any
1677
===================================================
1681
# These attributes are inherited from the Repository base class. Setting
1682
# them to None ensures that if the constructor is changed to not initialize
1683
# them, or a subclass fails to call the constructor, that an error will
1684
# occur rather than the system working but generating incorrect data.
1685
_commit_builder_class = None
1688
def __init__(self, _format, a_bzrdir, control_files, _commit_builder_class,
1690
MetaDirRepository.__init__(self, _format, a_bzrdir, control_files)
1691
self._commit_builder_class = _commit_builder_class
1692
self._serializer = _serializer
1693
self._reconcile_fixes_text_parents = True
1694
if self._format.supports_external_lookups:
1695
self._unstacked_provider = graph.CachingParentsProvider(
1696
self._make_parents_provider_unstacked())
1698
self._unstacked_provider = graph.CachingParentsProvider(self)
1699
self._unstacked_provider.disable_cache()
1702
def _all_revision_ids(self):
1703
"""See Repository.all_revision_ids()."""
1704
return [key[0] for key in self.revisions.keys()]
1338
self.repo._text_knit = None
1341
class KnitPackRevisionStore(KnitRevisionStore):
1342
"""An object to adapt access from RevisionStore's to use KnitPacks.
1344
This class works by replacing the original RevisionStore.
1345
We need to do this because the KnitPackRevisionStore is less
1346
isolated in its layering - it uses services from the repo.
1349
def __init__(self, repo, transport, revisionstore):
1350
"""Create a KnitPackRevisionStore on repo with revisionstore.
1352
This will store its state in the Repository, use the
1353
indices to provide a KnitGraphIndex,
1354
and at the end of transactions write new indices.
1356
KnitRevisionStore.__init__(self, revisionstore.versioned_file_store)
1358
self._serializer = revisionstore._serializer
1359
self.transport = transport
1361
def get_revision_file(self, transaction):
1362
"""Get the revision versioned file object."""
1363
if getattr(self.repo, '_revision_knit', None) is not None:
1364
return self.repo._revision_knit
1365
self.repo._pack_collection.ensure_loaded()
1366
add_callback = self.repo._pack_collection.revision_index.add_callback
1367
# setup knit specific objects
1368
knit_index = KnitGraphIndex(
1369
self.repo._pack_collection.revision_index.combined_index,
1370
add_callback=add_callback)
1371
self.repo._revision_knit = knit.KnitVersionedFile(
1372
'revisions', self.transport.clone('..'),
1373
self.repo.control_files._file_mode,
1374
create=False, access_mode=self.repo._access_mode(),
1375
index=knit_index, delta=False, factory=knit.KnitPlainFactory(),
1376
access_method=self.repo._pack_collection.revision_index.knit_access)
1377
return self.repo._revision_knit
1379
def get_signature_file(self, transaction):
1380
"""Get the signature versioned file object."""
1381
if getattr(self.repo, '_signature_knit', None) is not None:
1382
return self.repo._signature_knit
1383
self.repo._pack_collection.ensure_loaded()
1384
add_callback = self.repo._pack_collection.signature_index.add_callback
1385
# setup knit specific objects
1386
knit_index = KnitGraphIndex(
1387
self.repo._pack_collection.signature_index.combined_index,
1388
add_callback=add_callback, parents=False)
1389
self.repo._signature_knit = knit.KnitVersionedFile(
1390
'signatures', self.transport.clone('..'),
1391
self.repo.control_files._file_mode,
1392
create=False, access_mode=self.repo._access_mode(),
1393
index=knit_index, delta=False, factory=knit.KnitPlainFactory(),
1394
access_method=self.repo._pack_collection.signature_index.knit_access)
1395
return self.repo._signature_knit
1398
class KnitPackTextStore(VersionedFileStore):
1399
"""Presents a TextStore abstraction on top of packs.
1401
This class works by replacing the original VersionedFileStore.
1402
We need to do this because the KnitPackRevisionStore is less
1403
isolated in its layering - it uses services from the repo and shares them
1404
with all the data written in a single write group.
1407
def __init__(self, repo, transport, weavestore):
1408
"""Create a KnitPackTextStore on repo with weavestore.
1410
This will store its state in the Repository, use the
1411
indices FileNames to provide a KnitGraphIndex,
1412
and at the end of transactions write new indices.
1414
# don't call base class constructor - it's not suitable.
1415
# no transient data stored in the transaction
1417
self._precious = False
1419
self.transport = transport
1420
self.weavestore = weavestore
1421
# XXX for check() which isn't updated yet
1422
self._transport = weavestore._transport
1424
def get_weave_or_empty(self, file_id, transaction):
1425
"""Get a 'Knit' backed by the .tix indices.
1427
The transaction parameter is ignored.
1429
self.repo._pack_collection.ensure_loaded()
1430
add_callback = self.repo._pack_collection.text_index.add_callback
1431
# setup knit specific objects
1432
file_id_index = GraphIndexPrefixAdapter(
1433
self.repo._pack_collection.text_index.combined_index,
1434
(file_id, ), 1, add_nodes_callback=add_callback)
1435
knit_index = KnitGraphIndex(file_id_index,
1436
add_callback=file_id_index.add_nodes,
1437
deltas=True, parents=True)
1438
return knit.KnitVersionedFile('text:' + file_id,
1439
self.transport.clone('..'),
1442
access_method=self.repo._pack_collection.text_index.knit_access,
1443
factory=knit.KnitPlainFactory())
1445
get_weave = get_weave_or_empty
1448
"""Generate a list of the fileids inserted, for use by check."""
1449
self.repo._pack_collection.ensure_loaded()
1451
for index, key, value, refs in \
1452
self.repo._pack_collection.text_index.combined_index.iter_all_entries():
1457
class InventoryKnitThunk(object):
1458
"""An object to manage thunking get_inventory_weave to pack based knits."""
1460
def __init__(self, repo, transport):
1461
"""Create an InventoryKnitThunk for repo at transport.
1463
This will store its state in the Repository, use the
1464
indices FileNames to provide a KnitGraphIndex,
1465
and at the end of transactions write a new index..
1468
self.transport = transport
1470
def get_weave(self):
1471
"""Get a 'Knit' that contains inventory data."""
1472
self.repo._pack_collection.ensure_loaded()
1473
add_callback = self.repo._pack_collection.inventory_index.add_callback
1474
# setup knit specific objects
1475
knit_index = KnitGraphIndex(
1476
self.repo._pack_collection.inventory_index.combined_index,
1477
add_callback=add_callback, deltas=True, parents=True)
1478
return knit.KnitVersionedFile(
1479
'inventory', self.transport.clone('..'),
1480
self.repo.control_files._file_mode,
1481
create=False, access_mode=self.repo._access_mode(),
1482
index=knit_index, delta=True, factory=knit.KnitPlainFactory(),
1483
access_method=self.repo._pack_collection.inventory_index.knit_access)
1486
class KnitPackRepository(KnitRepository):
1487
"""Experimental graph-knit using repository."""
1489
def __init__(self, _format, a_bzrdir, control_files, _revision_store,
1490
control_store, text_store, _commit_builder_class, _serializer):
1491
KnitRepository.__init__(self, _format, a_bzrdir, control_files,
1492
_revision_store, control_store, text_store, _commit_builder_class,
1494
index_transport = control_files._transport.clone('indices')
1495
self._pack_collection = RepositoryPackCollection(self, control_files._transport,
1497
control_files._transport.clone('upload'),
1498
control_files._transport.clone('packs'))
1499
self._revision_store = KnitPackRevisionStore(self, index_transport, self._revision_store)
1500
self.weave_store = KnitPackTextStore(self, index_transport, self.weave_store)
1501
self._inv_thunk = InventoryKnitThunk(self, index_transport)
1502
# True when the repository object is 'write locked' (as opposed to the
1503
# physical lock only taken out around changes to the pack-names list.)
1504
# Another way to represent this would be a decorator around the control
1505
# files object that presents logical locks as physical ones - if this
1506
# gets ugly consider that alternative design. RBC 20071011
1507
self._write_lock_count = 0
1508
self._transaction = None
1510
self._reconcile_does_inventory_gc = True
1511
self._reconcile_fixes_text_parents = False
1512
self._reconcile_backsup_inventory = False
1706
1514
def _abort_write_group(self):
1707
self.revisions._index._key_dependencies.clear()
1708
1515
self._pack_collection._abort_write_group()
1517
def _access_mode(self):
1518
"""Return 'w' or 'r' for depending on whether a write lock is active.
1520
This method is a helper for the Knit-thunking support objects.
1522
if self.is_write_locked():
1526
def _find_inconsistent_revision_parents(self):
1527
"""Find revisions with incorrectly cached parents.
1529
:returns: an iterator yielding tuples of (revison-id, parents-in-index,
1530
parents-in-revision).
1532
assert self.is_locked()
1533
pb = ui.ui_factory.nested_progress_bar()
1536
revision_nodes = self._pack_collection.revision_index \
1537
.combined_index.iter_all_entries()
1538
index_positions = []
1539
# Get the cached index values for all revisions, and also the location
1540
# in each index of the revision text so we can perform linear IO.
1541
for index, key, value, refs in revision_nodes:
1542
pos, length = value[1:].split(' ')
1543
index_positions.append((index, int(pos), key[0],
1544
tuple(parent[0] for parent in refs[0])))
1545
pb.update("Reading revision index.", 0, 0)
1546
index_positions.sort()
1547
batch_count = len(index_positions) / 1000 + 1
1548
pb.update("Checking cached revision graph.", 0, batch_count)
1549
for offset in xrange(batch_count):
1550
pb.update("Checking cached revision graph.", offset)
1551
to_query = index_positions[offset * 1000:(offset + 1) * 1000]
1554
rev_ids = [item[2] for item in to_query]
1555
revs = self.get_revisions(rev_ids)
1556
for revision, item in zip(revs, to_query):
1557
index_parents = item[3]
1558
rev_parents = tuple(revision.parent_ids)
1559
if index_parents != rev_parents:
1560
result.append((revision.revision_id, index_parents, rev_parents))
1565
def get_parents(self, revision_ids):
1566
"""See StackedParentsProvider.get_parents.
1568
This implementation accesses the combined revision index to provide
1571
self._pack_collection.ensure_loaded()
1572
index = self._pack_collection.revision_index.combined_index
1574
for revision_id in revision_ids:
1575
if revision_id != _mod_revision.NULL_REVISION:
1576
search_keys.add((revision_id,))
1577
found_parents = {_mod_revision.NULL_REVISION:[]}
1578
for index, key, value, refs in index.iter_entries(search_keys):
1581
parents = (_mod_revision.NULL_REVISION,)
1583
parents = tuple(parent[0] for parent in parents)
1584
found_parents[key[0]] = parents
1586
for revision_id in revision_ids:
1588
result.append(found_parents[revision_id])
1710
1593
def _make_parents_provider(self):
1711
if not self._format.supports_external_lookups:
1712
return self._unstacked_provider
1713
return graph.StackedParentsProvider(_LazyListJoin(
1714
[self._unstacked_provider], self._fallback_repositories))
1716
1596
def _refresh_data(self):
1717
if not self.is_locked():
1719
self._pack_collection.reload_pack_names()
1720
self._unstacked_provider.disable_cache()
1721
self._unstacked_provider.enable_cache()
1597
if self._write_lock_count == 1 or (
1598
self.control_files._lock_count == 1 and
1599
self.control_files._lock_mode == 'r'):
1600
# forget what names there are
1601
self._pack_collection.reset()
1602
# XXX: Better to do an in-memory merge when acquiring a new lock -
1603
# factor out code from _save_pack_names.
1604
self._pack_collection.ensure_loaded()
1723
1606
def _start_write_group(self):
1724
1607
self._pack_collection._start_write_group()
1726
1609
def _commit_write_group(self):
1727
hint = self._pack_collection._commit_write_group()
1728
self.revisions._index._key_dependencies.clear()
1729
# The commit may have added keys that were previously cached as
1730
# missing, so reset the cache.
1731
self._unstacked_provider.disable_cache()
1732
self._unstacked_provider.enable_cache()
1735
def suspend_write_group(self):
1736
# XXX check self._write_group is self.get_transaction()?
1737
tokens = self._pack_collection._suspend_write_group()
1738
self.revisions._index._key_dependencies.clear()
1739
self._write_group = None
1742
def _resume_write_group(self, tokens):
1743
self._start_write_group()
1745
self._pack_collection._resume_write_group(tokens)
1746
except errors.UnresumableWriteGroup:
1747
self._abort_write_group()
1749
for pack in self._pack_collection._resumed_packs:
1750
self.revisions._index.scan_unvalidated_index(pack.revision_index)
1610
return self._pack_collection._commit_write_group()
1612
def get_inventory_weave(self):
1613
return self._inv_thunk.get_weave()
1752
1615
def get_transaction(self):
1753
1616
if self._write_lock_count:
1906
1758
mutter('creating repository in %s.', a_bzrdir.transport.base)
1907
1759
dirs = ['indices', 'obsolete_packs', 'packs', 'upload']
1908
builder = self.index_builder_class()
1760
builder = GraphIndexBuilder()
1909
1761
files = [('pack-names', builder.finish())]
1910
1762
utf8_files = [('format', self.get_format_string())]
1912
1764
self._upload_blank_content(a_bzrdir, dirs, files, utf8_files, shared)
1913
repository = self.open(a_bzrdir=a_bzrdir, _found=True)
1914
self._run_post_repo_init_hooks(repository, a_bzrdir, shared)
1765
return self.open(a_bzrdir=a_bzrdir, _found=True)
1917
1767
def open(self, a_bzrdir, _found=False, _override_transport=None):
1918
1768
"""See RepositoryFormat.open().
1920
1770
:param _override_transport: INTERNAL USE ONLY. Allows opening the
1921
1771
repository at a slightly different url
1922
1772
than normal. I.e. during 'upgrade'.
1925
format = RepositoryFormatMetaDir.find_format(a_bzrdir)
1775
format = RepositoryFormat.find_format(a_bzrdir)
1776
assert format.__class__ == self.__class__
1926
1777
if _override_transport is not None:
1927
1778
repo_transport = _override_transport
1929
1780
repo_transport = a_bzrdir.get_repository_transport(None)
1930
1781
control_files = lockable_files.LockableFiles(repo_transport,
1931
1782
'lock', lockdir.LockDir)
1783
text_store = self._get_text_store(repo_transport, control_files)
1784
control_store = self._get_control_store(repo_transport, control_files)
1785
_revision_store = self._get_revision_store(repo_transport, control_files)
1932
1786
return self.repository_class(_format=self,
1933
1787
a_bzrdir=a_bzrdir,
1934
1788
control_files=control_files,
1789
_revision_store=_revision_store,
1790
control_store=control_store,
1791
text_store=text_store,
1935
1792
_commit_builder_class=self._commit_builder_class,
1936
1793
_serializer=self._serializer)
1939
class RetryPackOperations(errors.RetryWithNewPacks):
1940
"""Raised when we are packing and we find a missing file.
1942
Meant as a signaling exception, to tell the RepositoryPackCollection.pack
1943
code it should try again.
1946
internal_error = True
1948
_fmt = ("Pack files have changed, reload and try pack again."
1949
" context: %(context)s %(orig_error)s")
1952
class _DirectPackAccess(object):
1953
"""Access to data in one or more packs with less translation."""
1955
def __init__(self, index_to_packs, reload_func=None, flush_func=None):
1956
"""Create a _DirectPackAccess object.
1958
:param index_to_packs: A dict mapping index objects to the transport
1959
and file names for obtaining data.
1960
:param reload_func: A function to call if we determine that the pack
1961
files have moved and we need to reload our caches. See
1962
bzrlib.repo_fmt.pack_repo.AggregateIndex for more details.
1964
self._container_writer = None
1965
self._write_index = None
1966
self._indices = index_to_packs
1967
self._reload_func = reload_func
1968
self._flush_func = flush_func
1970
def add_raw_records(self, key_sizes, raw_data):
1971
"""Add raw knit bytes to a storage area.
1973
The data is spooled to the container writer in one bytes-record per
1976
:param sizes: An iterable of tuples containing the key and size of each
1978
:param raw_data: A bytestring containing the data.
1979
:return: A list of memos to retrieve the record later. Each memo is an
1980
opaque index memo. For _DirectPackAccess the memo is (index, pos,
1981
length), where the index field is the write_index object supplied
1982
to the PackAccess object.
1984
if type(raw_data) is not str:
1985
raise AssertionError(
1986
'data must be plain bytes was %s' % type(raw_data))
1989
for key, size in key_sizes:
1990
p_offset, p_length = self._container_writer.add_bytes_record(
1991
raw_data[offset:offset+size], [])
1993
result.append((self._write_index, p_offset, p_length))
1997
"""Flush pending writes on this access object.
1999
This will flush any buffered writes to a NewPack.
2001
if self._flush_func is not None:
2004
def get_raw_records(self, memos_for_retrieval):
2005
"""Get the raw bytes for a records.
2007
:param memos_for_retrieval: An iterable containing the (index, pos,
2008
length) memo for retrieving the bytes. The Pack access method
2009
looks up the pack to use for a given record in its index_to_pack
2011
:return: An iterator over the bytes of the records.
2013
# first pass, group into same-index requests
2015
current_index = None
2016
for (index, offset, length) in memos_for_retrieval:
2017
if current_index == index:
2018
current_list.append((offset, length))
2020
if current_index is not None:
2021
request_lists.append((current_index, current_list))
2022
current_index = index
2023
current_list = [(offset, length)]
2024
# handle the last entry
2025
if current_index is not None:
2026
request_lists.append((current_index, current_list))
2027
for index, offsets in request_lists:
2029
transport, path = self._indices[index]
2031
# A KeyError here indicates that someone has triggered an index
2032
# reload, and this index has gone missing, we need to start
2034
if self._reload_func is None:
2035
# If we don't have a _reload_func there is nothing that can
2038
raise errors.RetryWithNewPacks(index,
2039
reload_occurred=True,
2040
exc_info=sys.exc_info())
2042
reader = pack.make_readv_reader(transport, path, offsets)
2043
for names, read_func in reader.iter_records():
2044
yield read_func(None)
2045
except errors.NoSuchFile:
2046
# A NoSuchFile error indicates that a pack file has gone
2047
# missing on disk, we need to trigger a reload, and start over.
2048
if self._reload_func is None:
2050
raise errors.RetryWithNewPacks(transport.abspath(path),
2051
reload_occurred=False,
2052
exc_info=sys.exc_info())
2054
def set_writer(self, writer, index, transport_packname):
2055
"""Set a writer to use for adding data."""
2056
if index is not None:
2057
self._indices[index] = transport_packname
2058
self._container_writer = writer
2059
self._write_index = index
2061
def reload_or_raise(self, retry_exc):
2062
"""Try calling the reload function, or re-raise the original exception.
2064
This should be called after _DirectPackAccess raises a
2065
RetryWithNewPacks exception. This function will handle the common logic
2066
of determining when the error is fatal versus being temporary.
2067
It will also make sure that the original exception is raised, rather
2068
than the RetryWithNewPacks exception.
2070
If this function returns, then the calling function should retry
2071
whatever operation was being performed. Otherwise an exception will
2074
:param retry_exc: A RetryWithNewPacks exception.
2077
if self._reload_func is None:
2079
elif not self._reload_func():
2080
# The reload claimed that nothing changed
2081
if not retry_exc.reload_occurred:
2082
# If there wasn't an earlier reload, then we really were
2083
# expecting to find changes. We didn't find them, so this is a
2087
exc_class, exc_value, exc_traceback = retry_exc.exc_info
2088
raise exc_class, exc_value, exc_traceback
1796
class RepositoryFormatKnitPack1(RepositoryFormatPack):
1797
"""A no-subtrees parameterised Pack repository.
1799
This format was introduced in 0.92.
1802
repository_class = KnitPackRepository
1803
_commit_builder_class = PackCommitBuilder
1804
_serializer = xml5.serializer_v5
1806
def _get_matching_bzrdir(self):
1807
return bzrdir.format_registry.make_bzrdir('knitpack-experimental')
1809
def _ignore_setting_bzrdir(self, format):
1812
_matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
1814
def get_format_string(self):
1815
"""See RepositoryFormat.get_format_string()."""
1816
return "Bazaar pack repository format 1 (needs bzr 0.92)\n"
1818
def get_format_description(self):
1819
"""See RepositoryFormat.get_format_description()."""
1820
return "Packs containing knits without subtree support"
1822
def check_conversion_target(self, target_format):
1826
class RepositoryFormatKnitPack3(RepositoryFormatPack):
1827
"""A subtrees parameterised Pack repository.
1829
This repository format uses the xml7 serializer to get:
1830
- support for recording full info about the tree root
1831
- support for recording tree-references
1833
This format was introduced in 0.92.
1836
repository_class = KnitPackRepository
1837
_commit_builder_class = PackRootCommitBuilder
1838
rich_root_data = True
1839
supports_tree_reference = True
1840
_serializer = xml7.serializer_v7
1842
def _get_matching_bzrdir(self):
1843
return bzrdir.format_registry.make_bzrdir(
1844
'knitpack-subtree-experimental')
1846
def _ignore_setting_bzrdir(self, format):
1849
_matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
1851
def check_conversion_target(self, target_format):
1852
if not target_format.rich_root_data:
1853
raise errors.BadConversionTarget(
1854
'Does not support rich root data.', target_format)
1855
if not getattr(target_format, 'supports_tree_reference', False):
1856
raise errors.BadConversionTarget(
1857
'Does not support nested trees', target_format)
1859
def get_format_string(self):
1860
"""See RepositoryFormat.get_format_string()."""
1861
return "Bazaar pack repository format 1 with subtree support (needs bzr 0.92)\n"
1863
def get_format_description(self):
1864
"""See RepositoryFormat.get_format_description()."""
1865
return "Packs containing knits with subtree support\n"