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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20
from bzrlib.lazy_import import lazy_import
21
lazy_import(globals(), """
22
from itertools import izip
37
from bzrlib.index import (
41
GraphIndexPrefixAdapter,
44
from bzrlib.knit import (
50
from bzrlib import tsort
57
revision as _mod_revision,
61
from bzrlib.decorators import needs_write_lock
62
from bzrlib.btree_index import (
66
from bzrlib.index import (
70
from bzrlib.repofmt.knitrepo import KnitRepository
71
from bzrlib.repository import (
73
MetaDirRepositoryFormat,
77
import bzrlib.revision as _mod_revision
78
from bzrlib.trace import (
84
class PackCommitBuilder(CommitBuilder):
85
"""A subclass of CommitBuilder to add texts with pack semantics.
87
Specifically this uses one knit object rather than one knit object per
88
added text, reducing memory and object pressure.
91
def __init__(self, repository, parents, config, timestamp=None,
92
timezone=None, committer=None, revprops=None,
94
CommitBuilder.__init__(self, repository, parents, config,
95
timestamp=timestamp, timezone=timezone, committer=committer,
96
revprops=revprops, revision_id=revision_id)
97
self._file_graph = graph.Graph(
98
repository._pack_collection.text_index.combined_index)
100
def _heads(self, file_id, revision_ids):
101
keys = [(file_id, revision_id) for revision_id in revision_ids]
102
return set([key[1] for key in self._file_graph.heads(keys)])
105
class PackRootCommitBuilder(RootCommitBuilder):
106
"""A subclass of RootCommitBuilder to add texts with pack semantics.
108
Specifically this uses one knit object rather than one knit object per
109
added text, reducing memory and object pressure.
112
def __init__(self, repository, parents, config, timestamp=None,
113
timezone=None, committer=None, revprops=None,
115
CommitBuilder.__init__(self, repository, parents, config,
116
timestamp=timestamp, timezone=timezone, committer=committer,
117
revprops=revprops, revision_id=revision_id)
118
self._file_graph = graph.Graph(
119
repository._pack_collection.text_index.combined_index)
121
def _heads(self, file_id, revision_ids):
122
keys = [(file_id, revision_id) for revision_id in revision_ids]
123
return set([key[1] for key in self._file_graph.heads(keys)])
127
"""An in memory proxy for a pack and its indices.
129
This is a base class that is not directly used, instead the classes
130
ExistingPack and NewPack are used.
133
# A map of index 'type' to the file extension and position in the
135
index_definitions = {
137
'revision': ('.rix', 0),
138
'inventory': ('.iix', 1),
140
'signature': ('.six', 3),
143
def __init__(self, revision_index, inventory_index, text_index,
144
signature_index, chk_index=None):
145
"""Create a pack instance.
147
:param revision_index: A GraphIndex for determining what revisions are
148
present in the Pack and accessing the locations of their texts.
149
:param inventory_index: A GraphIndex for determining what inventories are
150
present in the Pack and accessing the locations of their
152
:param text_index: A GraphIndex for determining what file texts
153
are present in the pack and accessing the locations of their
154
texts/deltas (via (fileid, revisionid) tuples).
155
:param signature_index: A GraphIndex for determining what signatures are
156
present in the Pack and accessing the locations of their texts.
157
:param chk_index: A GraphIndex for accessing content by CHK, if the
160
self.revision_index = revision_index
161
self.inventory_index = inventory_index
162
self.text_index = text_index
163
self.signature_index = signature_index
164
self.chk_index = chk_index
166
def access_tuple(self):
167
"""Return a tuple (transport, name) for the pack content."""
168
return self.pack_transport, self.file_name()
170
def _check_references(self):
171
"""Make sure our external references are present.
173
Packs are allowed to have deltas whose base is not in the pack, but it
174
must be present somewhere in this collection. It is not allowed to
175
have deltas based on a fallback repository.
176
(See <https://bugs.launchpad.net/bzr/+bug/288751>)
179
for (index_name, external_refs, index) in [
181
self._get_external_refs(self.text_index),
182
self._pack_collection.text_index.combined_index),
184
self._get_external_refs(self.inventory_index),
185
self._pack_collection.inventory_index.combined_index),
187
missing = external_refs.difference(
188
k for (idx, k, v, r) in
189
index.iter_entries(external_refs))
191
missing_items[index_name] = sorted(list(missing))
193
from pprint import pformat
194
raise errors.BzrCheckError(
195
"Newly created pack file %r has delta references to "
196
"items not in its repository:\n%s"
197
% (self, pformat(missing_items)))
200
"""Get the file name for the pack on disk."""
201
return self.name + '.pack'
203
def get_revision_count(self):
204
return self.revision_index.key_count()
206
def index_name(self, index_type, name):
207
"""Get the disk name of an index type for pack name 'name'."""
208
return name + Pack.index_definitions[index_type][0]
210
def index_offset(self, index_type):
211
"""Get the position in a index_size array for a given index type."""
212
return Pack.index_definitions[index_type][1]
214
def inventory_index_name(self, name):
215
"""The inv index is the name + .iix."""
216
return self.index_name('inventory', name)
218
def revision_index_name(self, name):
219
"""The revision index is the name + .rix."""
220
return self.index_name('revision', name)
222
def signature_index_name(self, name):
223
"""The signature index is the name + .six."""
224
return self.index_name('signature', name)
226
def text_index_name(self, name):
227
"""The text index is the name + .tix."""
228
return self.index_name('text', name)
230
def _replace_index_with_readonly(self, index_type):
231
setattr(self, index_type + '_index',
232
self.index_class(self.index_transport,
233
self.index_name(index_type, self.name),
234
self.index_sizes[self.index_offset(index_type)]))
237
class ExistingPack(Pack):
238
"""An in memory proxy for an existing .pack and its disk indices."""
240
def __init__(self, pack_transport, name, revision_index, inventory_index,
241
text_index, signature_index, chk_index=None):
242
"""Create an ExistingPack object.
244
:param pack_transport: The transport where the pack file resides.
245
:param name: The name of the pack on disk in the pack_transport.
247
Pack.__init__(self, revision_index, inventory_index, text_index,
248
signature_index, chk_index)
250
self.pack_transport = pack_transport
251
if None in (revision_index, inventory_index, text_index,
252
signature_index, name, pack_transport):
253
raise AssertionError()
255
def __eq__(self, other):
256
return self.__dict__ == other.__dict__
258
def __ne__(self, other):
259
return not self.__eq__(other)
262
return "<%s.%s object at 0x%x, %s, %s" % (
263
self.__class__.__module__, self.__class__.__name__, id(self),
264
self.pack_transport, self.name)
267
class ResumedPack(ExistingPack):
269
def __init__(self, name, revision_index, inventory_index, text_index,
270
signature_index, upload_transport, pack_transport, index_transport,
271
pack_collection, chk_index=None):
272
"""Create a ResumedPack object."""
273
ExistingPack.__init__(self, pack_transport, name, revision_index,
274
inventory_index, text_index, signature_index,
276
self.upload_transport = upload_transport
277
self.index_transport = index_transport
278
self.index_sizes = [None, None, None, None]
280
('revision', revision_index),
281
('inventory', inventory_index),
282
('text', text_index),
283
('signature', signature_index),
285
if chk_index is not None:
286
indices.append(('chk', chk_index))
287
self.index_sizes.append(None)
288
for index_type, index in indices:
289
offset = self.index_offset(index_type)
290
self.index_sizes[offset] = index._size
291
self.index_class = pack_collection._index_class
292
self._pack_collection = pack_collection
293
self._state = 'resumed'
294
# XXX: perhaps check that the .pack file exists?
296
def access_tuple(self):
297
if self._state == 'finished':
298
return Pack.access_tuple(self)
299
elif self._state == 'resumed':
300
return self.upload_transport, self.file_name()
302
raise AssertionError(self._state)
305
self.upload_transport.delete(self.file_name())
306
indices = [self.revision_index, self.inventory_index, self.text_index,
307
self.signature_index]
308
if self.chk_index is not None:
309
indices.append(self.chk_index)
310
for index in indices:
311
index._transport.delete(index._name)
314
self._check_references()
315
new_name = '../packs/' + self.file_name()
316
self.upload_transport.rename(self.file_name(), new_name)
317
index_types = ['revision', 'inventory', 'text', 'signature']
318
if self.chk_index is not None:
319
index_types.append('chk')
320
for index_type in index_types:
321
old_name = self.index_name(index_type, self.name)
322
new_name = '../indices/' + old_name
323
self.upload_transport.rename(old_name, new_name)
324
self._replace_index_with_readonly(index_type)
325
self._state = 'finished'
327
def _get_external_refs(self, index):
328
"""Return compression parents for this index that are not present.
330
This returns any compression parents that are referenced by this index,
331
which are not contained *in* this index. They may be present elsewhere.
333
return index.external_references(1)
337
"""An in memory proxy for a pack which is being created."""
339
def __init__(self, pack_collection, upload_suffix='', file_mode=None):
340
"""Create a NewPack instance.
342
:param pack_collection: A PackCollection into which this is being inserted.
343
:param upload_suffix: An optional suffix to be given to any temporary
344
files created during the pack creation. e.g '.autopack'
345
:param file_mode: Unix permissions for newly created file.
347
# The relative locations of the packs are constrained, but all are
348
# passed in because the caller has them, so as to avoid object churn.
349
index_builder_class = pack_collection._index_builder_class
350
if pack_collection.chk_index is not None:
351
chk_index = index_builder_class(reference_lists=0)
355
# Revisions: parents list, no text compression.
356
index_builder_class(reference_lists=1),
357
# Inventory: We want to map compression only, but currently the
358
# knit code hasn't been updated enough to understand that, so we
359
# have a regular 2-list index giving parents and compression
361
index_builder_class(reference_lists=2),
362
# Texts: compression and per file graph, for all fileids - so two
363
# reference lists and two elements in the key tuple.
364
index_builder_class(reference_lists=2, key_elements=2),
365
# Signatures: Just blobs to store, no compression, no parents
367
index_builder_class(reference_lists=0),
368
# CHK based storage - just blobs, no compression or parents.
371
self._pack_collection = pack_collection
372
# When we make readonly indices, we need this.
373
self.index_class = pack_collection._index_class
374
# where should the new pack be opened
375
self.upload_transport = pack_collection._upload_transport
376
# where are indices written out to
377
self.index_transport = pack_collection._index_transport
378
# where is the pack renamed to when it is finished?
379
self.pack_transport = pack_collection._pack_transport
380
# What file mode to upload the pack and indices with.
381
self._file_mode = file_mode
382
# tracks the content written to the .pack file.
383
self._hash = osutils.md5()
384
# a tuple with the length in bytes of the indices, once the pack
385
# is finalised. (rev, inv, text, sigs, chk_if_in_use)
386
self.index_sizes = None
387
# How much data to cache when writing packs. Note that this is not
388
# synchronised with reads, because it's not in the transport layer, so
389
# is not safe unless the client knows it won't be reading from the pack
391
self._cache_limit = 0
392
# the temporary pack file name.
393
self.random_name = osutils.rand_chars(20) + upload_suffix
394
# when was this pack started ?
395
self.start_time = time.time()
396
# open an output stream for the data added to the pack.
397
self.write_stream = self.upload_transport.open_write_stream(
398
self.random_name, mode=self._file_mode)
399
if 'pack' in debug.debug_flags:
400
mutter('%s: create_pack: pack stream open: %s%s t+%6.3fs',
401
time.ctime(), self.upload_transport.base, self.random_name,
402
time.time() - self.start_time)
403
# A list of byte sequences to be written to the new pack, and the
404
# aggregate size of them. Stored as a list rather than separate
405
# variables so that the _write_data closure below can update them.
406
self._buffer = [[], 0]
407
# create a callable for adding data
409
# robertc says- this is a closure rather than a method on the object
410
# so that the variables are locals, and faster than accessing object
412
def _write_data(bytes, flush=False, _buffer=self._buffer,
413
_write=self.write_stream.write, _update=self._hash.update):
414
_buffer[0].append(bytes)
415
_buffer[1] += len(bytes)
417
if _buffer[1] > self._cache_limit or flush:
418
bytes = ''.join(_buffer[0])
422
# expose this on self, for the occasion when clients want to add data.
423
self._write_data = _write_data
424
# a pack writer object to serialise pack records.
425
self._writer = pack.ContainerWriter(self._write_data)
427
# what state is the pack in? (open, finished, aborted)
431
"""Cancel creating this pack."""
432
self._state = 'aborted'
433
self.write_stream.close()
434
# Remove the temporary pack file.
435
self.upload_transport.delete(self.random_name)
436
# The indices have no state on disk.
438
def access_tuple(self):
439
"""Return a tuple (transport, name) for the pack content."""
440
if self._state == 'finished':
441
return Pack.access_tuple(self)
442
elif self._state == 'open':
443
return self.upload_transport, self.random_name
445
raise AssertionError(self._state)
447
def data_inserted(self):
448
"""True if data has been added to this pack."""
449
return bool(self.get_revision_count() or
450
self.inventory_index.key_count() or
451
self.text_index.key_count() or
452
self.signature_index.key_count() or
453
(self.chk_index is not None and self.chk_index.key_count()))
455
def finish(self, suspend=False):
456
"""Finish the new pack.
459
- finalises the content
460
- assigns a name (the md5 of the content, currently)
461
- writes out the associated indices
462
- renames the pack into place.
463
- stores the index size tuple for the pack in the index_sizes
468
self._write_data('', flush=True)
469
self.name = self._hash.hexdigest()
471
self._check_references()
473
# XXX: It'd be better to write them all to temporary names, then
474
# rename them all into place, so that the window when only some are
475
# visible is smaller. On the other hand none will be seen until
476
# they're in the names list.
477
self.index_sizes = [None, None, None, None]
478
self._write_index('revision', self.revision_index, 'revision', suspend)
479
self._write_index('inventory', self.inventory_index, 'inventory',
481
self._write_index('text', self.text_index, 'file texts', suspend)
482
self._write_index('signature', self.signature_index,
483
'revision signatures', suspend)
484
if self.chk_index is not None:
485
self.index_sizes.append(None)
486
self._write_index('chk', self.chk_index,
487
'content hash bytes', suspend)
488
self.write_stream.close()
489
# Note that this will clobber an existing pack with the same name,
490
# without checking for hash collisions. While this is undesirable this
491
# is something that can be rectified in a subsequent release. One way
492
# to rectify it may be to leave the pack at the original name, writing
493
# its pack-names entry as something like 'HASH: index-sizes
494
# temporary-name'. Allocate that and check for collisions, if it is
495
# collision free then rename it into place. If clients know this scheme
496
# they can handle missing-file errors by:
497
# - try for HASH.pack
498
# - try for temporary-name
499
# - refresh the pack-list to see if the pack is now absent
500
new_name = self.name + '.pack'
502
new_name = '../packs/' + new_name
503
self.upload_transport.rename(self.random_name, new_name)
504
self._state = 'finished'
505
if 'pack' in debug.debug_flags:
506
# XXX: size might be interesting?
507
mutter('%s: create_pack: pack finished: %s%s->%s t+%6.3fs',
508
time.ctime(), self.upload_transport.base, self.random_name,
509
new_name, time.time() - self.start_time)
512
"""Flush any current data."""
514
bytes = ''.join(self._buffer[0])
515
self.write_stream.write(bytes)
516
self._hash.update(bytes)
517
self._buffer[:] = [[], 0]
519
def _get_external_refs(self, index):
520
return index._external_references()
522
def set_write_cache_size(self, size):
523
self._cache_limit = size
525
def _write_index(self, index_type, index, label, suspend=False):
526
"""Write out an index.
528
:param index_type: The type of index to write - e.g. 'revision'.
529
:param index: The index object to serialise.
530
:param label: What label to give the index e.g. 'revision'.
532
index_name = self.index_name(index_type, self.name)
534
transport = self.upload_transport
536
transport = self.index_transport
537
self.index_sizes[self.index_offset(index_type)] = transport.put_file(
538
index_name, index.finish(), mode=self._file_mode)
539
if 'pack' in debug.debug_flags:
540
# XXX: size might be interesting?
541
mutter('%s: create_pack: wrote %s index: %s%s t+%6.3fs',
542
time.ctime(), label, self.upload_transport.base,
543
self.random_name, time.time() - self.start_time)
544
# Replace the writable index on this object with a readonly,
545
# presently unloaded index. We should alter
546
# the index layer to make its finish() error if add_node is
547
# subsequently used. RBC
548
self._replace_index_with_readonly(index_type)
551
class AggregateIndex(object):
552
"""An aggregated index for the RepositoryPackCollection.
554
AggregateIndex is reponsible for managing the PackAccess object,
555
Index-To-Pack mapping, and all indices list for a specific type of index
556
such as 'revision index'.
558
A CombinedIndex provides an index on a single key space built up
559
from several on-disk indices. The AggregateIndex builds on this
560
to provide a knit access layer, and allows having up to one writable
561
index within the collection.
563
# XXX: Probably 'can be written to' could/should be separated from 'acts
564
# like a knit index' -- mbp 20071024
566
def __init__(self, reload_func=None, flush_func=None):
567
"""Create an AggregateIndex.
569
:param reload_func: A function to call if we find we are missing an
570
index. Should have the form reload_func() => True if the list of
571
active pack files has changed.
573
self._reload_func = reload_func
574
self.index_to_pack = {}
575
self.combined_index = CombinedGraphIndex([], reload_func=reload_func)
576
self.data_access = _DirectPackAccess(self.index_to_pack,
577
reload_func=reload_func,
578
flush_func=flush_func)
579
self.add_callback = None
581
def replace_indices(self, index_to_pack, indices):
582
"""Replace the current mappings with fresh ones.
584
This should probably not be used eventually, rather incremental add and
585
removal of indices. It has been added during refactoring of existing
588
:param index_to_pack: A mapping from index objects to
589
(transport, name) tuples for the pack file data.
590
:param indices: A list of indices.
592
# refresh the revision pack map dict without replacing the instance.
593
self.index_to_pack.clear()
594
self.index_to_pack.update(index_to_pack)
595
# XXX: API break - clearly a 'replace' method would be good?
596
self.combined_index._indices[:] = indices
597
# the current add nodes callback for the current writable index if
599
self.add_callback = None
601
def add_index(self, index, pack):
602
"""Add index to the aggregate, which is an index for Pack pack.
604
Future searches on the aggregate index will seach this new index
605
before all previously inserted indices.
607
:param index: An Index for the pack.
608
:param pack: A Pack instance.
610
# expose it to the index map
611
self.index_to_pack[index] = pack.access_tuple()
612
# put it at the front of the linear index list
613
self.combined_index.insert_index(0, index)
615
def add_writable_index(self, index, pack):
616
"""Add an index which is able to have data added to it.
618
There can be at most one writable index at any time. Any
619
modifications made to the knit are put into this index.
621
:param index: An index from the pack parameter.
622
:param pack: A Pack instance.
624
if self.add_callback is not None:
625
raise AssertionError(
626
"%s already has a writable index through %s" % \
627
(self, self.add_callback))
628
# allow writing: queue writes to a new index
629
self.add_index(index, pack)
630
# Updates the index to packs mapping as a side effect,
631
self.data_access.set_writer(pack._writer, index, pack.access_tuple())
632
self.add_callback = index.add_nodes
635
"""Reset all the aggregate data to nothing."""
636
self.data_access.set_writer(None, None, (None, None))
637
self.index_to_pack.clear()
638
del self.combined_index._indices[:]
639
self.add_callback = None
641
def remove_index(self, index, pack):
642
"""Remove index from the indices used to answer queries.
644
:param index: An index from the pack parameter.
645
:param pack: A Pack instance.
647
del self.index_to_pack[index]
648
self.combined_index._indices.remove(index)
649
if (self.add_callback is not None and
650
getattr(index, 'add_nodes', None) == self.add_callback):
651
self.add_callback = None
652
self.data_access.set_writer(None, None, (None, None))
655
class Packer(object):
656
"""Create a pack from packs."""
658
def __init__(self, pack_collection, packs, suffix, revision_ids=None,
662
:param pack_collection: A RepositoryPackCollection object where the
663
new pack is being written to.
664
:param packs: The packs to combine.
665
:param suffix: The suffix to use on the temporary files for the pack.
666
:param revision_ids: Revision ids to limit the pack to.
667
:param reload_func: A function to call if a pack file/index goes
668
missing. The side effect of calling this function should be to
669
update self.packs. See also AggregateIndex
673
self.revision_ids = revision_ids
674
# The pack object we are creating.
676
self._pack_collection = pack_collection
677
self._reload_func = reload_func
678
# The index layer keys for the revisions being copied. None for 'all
680
self._revision_keys = None
681
# What text keys to copy. None for 'all texts'. This is set by
682
# _copy_inventory_texts
683
self._text_filter = None
686
def _extra_init(self):
687
"""A template hook to allow extending the constructor trivially."""
689
def _pack_map_and_index_list(self, index_attribute):
690
"""Convert a list of packs to an index pack map and index list.
692
:param index_attribute: The attribute that the desired index is found
694
:return: A tuple (map, list) where map contains the dict from
695
index:pack_tuple, and list contains the indices in the preferred
700
for pack_obj in self.packs:
701
index = getattr(pack_obj, index_attribute)
702
indices.append(index)
703
pack_map[index] = pack_obj
704
return pack_map, indices
706
def _index_contents(self, indices, key_filter=None):
707
"""Get an iterable of the index contents from a pack_map.
709
:param indices: The list of indices to query
710
:param key_filter: An optional filter to limit the keys returned.
712
all_index = CombinedGraphIndex(indices)
713
if key_filter is None:
714
return all_index.iter_all_entries()
716
return all_index.iter_entries(key_filter)
718
def pack(self, pb=None):
719
"""Create a new pack by reading data from other packs.
721
This does little more than a bulk copy of data. One key difference
722
is that data with the same item key across multiple packs is elided
723
from the output. The new pack is written into the current pack store
724
along with its indices, and the name added to the pack names. The
725
source packs are not altered and are not required to be in the current
728
:param pb: An optional progress bar to use. A nested bar is created if
730
:return: A Pack object, or None if nothing was copied.
732
# open a pack - using the same name as the last temporary file
733
# - which has already been flushed, so its safe.
734
# XXX: - duplicate code warning with start_write_group; fix before
735
# considering 'done'.
736
if self._pack_collection._new_pack is not None:
737
raise errors.BzrError('call to %s.pack() while another pack is'
739
% (self.__class__.__name__,))
740
if self.revision_ids is not None:
741
if len(self.revision_ids) == 0:
742
# silly fetch request.
745
self.revision_ids = frozenset(self.revision_ids)
746
self.revision_keys = frozenset((revid,) for revid in
749
self.pb = ui.ui_factory.nested_progress_bar()
753
return self._create_pack_from_packs()
759
"""Open a pack for the pack we are creating."""
760
new_pack = self._pack_collection.pack_factory(self._pack_collection,
761
upload_suffix=self.suffix,
762
file_mode=self._pack_collection.repo.bzrdir._get_file_mode())
763
# We know that we will process all nodes in order, and don't need to
764
# query, so don't combine any indices spilled to disk until we are done
765
new_pack.revision_index.set_optimize(combine_backing_indices=False)
766
new_pack.inventory_index.set_optimize(combine_backing_indices=False)
767
new_pack.text_index.set_optimize(combine_backing_indices=False)
768
new_pack.signature_index.set_optimize(combine_backing_indices=False)
771
def _update_pack_order(self, entries, index_to_pack_map):
772
"""Determine how we want our packs to be ordered.
774
This changes the sort order of the self.packs list so that packs unused
775
by 'entries' will be at the end of the list, so that future requests
776
can avoid probing them. Used packs will be at the front of the
777
self.packs list, in the order of their first use in 'entries'.
779
:param entries: A list of (index, ...) tuples
780
:param index_to_pack_map: A mapping from index objects to pack objects.
784
for entry in entries:
786
if index not in seen_indexes:
787
packs.append(index_to_pack_map[index])
788
seen_indexes.add(index)
789
if len(packs) == len(self.packs):
790
if 'pack' in debug.debug_flags:
791
mutter('Not changing pack list, all packs used.')
793
seen_packs = set(packs)
794
for pack in self.packs:
795
if pack not in seen_packs:
798
if 'pack' in debug.debug_flags:
799
old_names = [p.access_tuple()[1] for p in self.packs]
800
new_names = [p.access_tuple()[1] for p in packs]
801
mutter('Reordering packs\nfrom: %s\n to: %s',
802
old_names, new_names)
805
def _copy_revision_texts(self):
806
"""Copy revision data to the new pack."""
808
if self.revision_ids:
809
revision_keys = [(revision_id,) for revision_id in self.revision_ids]
812
# select revision keys
813
revision_index_map, revision_indices = self._pack_map_and_index_list(
815
revision_nodes = self._index_contents(revision_indices, revision_keys)
816
revision_nodes = list(revision_nodes)
817
self._update_pack_order(revision_nodes, revision_index_map)
818
# copy revision keys and adjust values
819
self.pb.update("Copying revision texts", 1)
820
total_items, readv_group_iter = self._revision_node_readv(revision_nodes)
821
list(self._copy_nodes_graph(revision_index_map, self.new_pack._writer,
822
self.new_pack.revision_index, readv_group_iter, total_items))
823
if 'pack' in debug.debug_flags:
824
mutter('%s: create_pack: revisions copied: %s%s %d items t+%6.3fs',
825
time.ctime(), self._pack_collection._upload_transport.base,
826
self.new_pack.random_name,
827
self.new_pack.revision_index.key_count(),
828
time.time() - self.new_pack.start_time)
829
self._revision_keys = revision_keys
831
def _copy_inventory_texts(self):
832
"""Copy the inventory texts to the new pack.
834
self._revision_keys is used to determine what inventories to copy.
836
Sets self._text_filter appropriately.
838
# select inventory keys
839
inv_keys = self._revision_keys # currently the same keyspace, and note that
840
# querying for keys here could introduce a bug where an inventory item
841
# is missed, so do not change it to query separately without cross
842
# checking like the text key check below.
843
inventory_index_map, inventory_indices = self._pack_map_and_index_list(
845
inv_nodes = self._index_contents(inventory_indices, inv_keys)
846
# copy inventory keys and adjust values
847
# XXX: Should be a helper function to allow different inv representation
849
self.pb.update("Copying inventory texts", 2)
850
total_items, readv_group_iter = self._least_readv_node_readv(inv_nodes)
851
# Only grab the output lines if we will be processing them
852
output_lines = bool(self.revision_ids)
853
inv_lines = self._copy_nodes_graph(inventory_index_map,
854
self.new_pack._writer, self.new_pack.inventory_index,
855
readv_group_iter, total_items, output_lines=output_lines)
856
if self.revision_ids:
857
self._process_inventory_lines(inv_lines)
859
# eat the iterator to cause it to execute.
861
self._text_filter = None
862
if 'pack' in debug.debug_flags:
863
mutter('%s: create_pack: inventories copied: %s%s %d items t+%6.3fs',
864
time.ctime(), self._pack_collection._upload_transport.base,
865
self.new_pack.random_name,
866
self.new_pack.inventory_index.key_count(),
867
time.time() - self.new_pack.start_time)
869
def _copy_text_texts(self):
871
text_index_map, text_nodes = self._get_text_nodes()
872
if self._text_filter is not None:
873
# We could return the keys copied as part of the return value from
874
# _copy_nodes_graph but this doesn't work all that well with the
875
# need to get line output too, so we check separately, and as we're
876
# going to buffer everything anyway, we check beforehand, which
877
# saves reading knit data over the wire when we know there are
879
text_nodes = set(text_nodes)
880
present_text_keys = set(_node[1] for _node in text_nodes)
881
missing_text_keys = set(self._text_filter) - present_text_keys
882
if missing_text_keys:
883
# TODO: raise a specific error that can handle many missing
885
mutter("missing keys during fetch: %r", missing_text_keys)
886
a_missing_key = missing_text_keys.pop()
887
raise errors.RevisionNotPresent(a_missing_key[1],
889
# copy text keys and adjust values
890
self.pb.update("Copying content texts", 3)
891
total_items, readv_group_iter = self._least_readv_node_readv(text_nodes)
892
list(self._copy_nodes_graph(text_index_map, self.new_pack._writer,
893
self.new_pack.text_index, readv_group_iter, total_items))
894
self._log_copied_texts()
896
def _create_pack_from_packs(self):
897
self.pb.update("Opening pack", 0, 5)
898
self.new_pack = self.open_pack()
899
new_pack = self.new_pack
900
# buffer data - we won't be reading-back during the pack creation and
901
# this makes a significant difference on sftp pushes.
902
new_pack.set_write_cache_size(1024*1024)
903
if 'pack' in debug.debug_flags:
904
plain_pack_list = ['%s%s' % (a_pack.pack_transport.base, a_pack.name)
905
for a_pack in self.packs]
906
if self.revision_ids is not None:
907
rev_count = len(self.revision_ids)
910
mutter('%s: create_pack: creating pack from source packs: '
911
'%s%s %s revisions wanted %s t=0',
912
time.ctime(), self._pack_collection._upload_transport.base, new_pack.random_name,
913
plain_pack_list, rev_count)
914
self._copy_revision_texts()
915
self._copy_inventory_texts()
916
self._copy_text_texts()
917
# select signature keys
918
signature_filter = self._revision_keys # same keyspace
919
signature_index_map, signature_indices = self._pack_map_and_index_list(
921
signature_nodes = self._index_contents(signature_indices,
923
# copy signature keys and adjust values
924
self.pb.update("Copying signature texts", 4)
925
self._copy_nodes(signature_nodes, signature_index_map, new_pack._writer,
926
new_pack.signature_index)
927
if 'pack' in debug.debug_flags:
928
mutter('%s: create_pack: revision signatures copied: %s%s %d items t+%6.3fs',
929
time.ctime(), self._pack_collection._upload_transport.base, new_pack.random_name,
930
new_pack.signature_index.key_count(),
931
time.time() - new_pack.start_time)
933
# NB XXX: how to check CHK references are present? perhaps by yielding
934
# the items? How should that interact with stacked repos?
935
if new_pack.chk_index is not None:
937
if 'pack' in debug.debug_flags:
938
mutter('%s: create_pack: chk content copied: %s%s %d items t+%6.3fs',
939
time.ctime(), self._pack_collection._upload_transport.base,
940
new_pack.random_name,
941
new_pack.chk_index.key_count(),
942
time.time() - new_pack.start_time)
943
new_pack._check_references()
944
if not self._use_pack(new_pack):
947
self.pb.update("Finishing pack", 5)
949
self._pack_collection.allocate(new_pack)
952
def _copy_chks(self, refs=None):
953
# XXX: Todo, recursive follow-pointers facility when fetching some
955
chk_index_map, chk_indices = self._pack_map_and_index_list(
957
chk_nodes = self._index_contents(chk_indices, refs)
959
# TODO: This isn't strictly tasteful as we are accessing some private
960
# variables (_serializer). Perhaps a better way would be to have
961
# Repository._deserialise_chk_node()
962
search_key_func = chk_map.search_key_registry.get(
963
self._pack_collection.repo._serializer.search_key_name)
964
def accumlate_refs(lines):
965
# XXX: move to a generic location
967
bytes = ''.join(lines)
968
node = chk_map._deserialise(bytes, ("unknown",), search_key_func)
969
new_refs.update(node.refs())
970
self._copy_nodes(chk_nodes, chk_index_map, self.new_pack._writer,
971
self.new_pack.chk_index, output_lines=accumlate_refs)
974
def _copy_nodes(self, nodes, index_map, writer, write_index,
976
"""Copy knit nodes between packs with no graph references.
978
:param output_lines: Output full texts of copied items.
980
pb = ui.ui_factory.nested_progress_bar()
982
return self._do_copy_nodes(nodes, index_map, writer,
983
write_index, pb, output_lines=output_lines)
987
def _do_copy_nodes(self, nodes, index_map, writer, write_index, pb,
989
# for record verification
990
knit = KnitVersionedFiles(None, None)
991
# plan a readv on each source pack:
993
nodes = sorted(nodes)
994
# how to map this into knit.py - or knit.py into this?
995
# we don't want the typical knit logic, we want grouping by pack
996
# at this point - perhaps a helper library for the following code
997
# duplication points?
999
for index, key, value in nodes:
1000
if index not in request_groups:
1001
request_groups[index] = []
1002
request_groups[index].append((key, value))
1004
pb.update("Copied record", record_index, len(nodes))
1005
for index, items in request_groups.iteritems():
1006
pack_readv_requests = []
1007
for key, value in items:
1008
# ---- KnitGraphIndex.get_position
1009
bits = value[1:].split(' ')
1010
offset, length = int(bits[0]), int(bits[1])
1011
pack_readv_requests.append((offset, length, (key, value[0])))
1012
# linear scan up the pack
1013
pack_readv_requests.sort()
1015
pack_obj = index_map[index]
1016
transport, path = pack_obj.access_tuple()
1018
reader = pack.make_readv_reader(transport, path,
1019
[offset[0:2] for offset in pack_readv_requests])
1020
except errors.NoSuchFile:
1021
if self._reload_func is not None:
1024
for (names, read_func), (_1, _2, (key, eol_flag)) in \
1025
izip(reader.iter_records(), pack_readv_requests):
1026
raw_data = read_func(None)
1027
# check the header only
1028
if output_lines is not None:
1029
output_lines(knit._parse_record(key[-1], raw_data)[0])
1031
df, _ = knit._parse_record_header(key, raw_data)
1033
pos, size = writer.add_bytes_record(raw_data, names)
1034
write_index.add_node(key, eol_flag + "%d %d" % (pos, size))
1035
pb.update("Copied record", record_index)
1038
def _copy_nodes_graph(self, index_map, writer, write_index,
1039
readv_group_iter, total_items, output_lines=False):
1040
"""Copy knit nodes between packs.
1042
:param output_lines: Return lines present in the copied data as
1043
an iterator of line,version_id.
1045
pb = ui.ui_factory.nested_progress_bar()
1047
for result in self._do_copy_nodes_graph(index_map, writer,
1048
write_index, output_lines, pb, readv_group_iter, total_items):
1051
# Python 2.4 does not permit try:finally: in a generator.
1057
def _do_copy_nodes_graph(self, index_map, writer, write_index,
1058
output_lines, pb, readv_group_iter, total_items):
1059
# for record verification
1060
knit = KnitVersionedFiles(None, None)
1061
# for line extraction when requested (inventories only)
1063
factory = KnitPlainFactory()
1065
pb.update("Copied record", record_index, total_items)
1066
for index, readv_vector, node_vector in readv_group_iter:
1068
pack_obj = index_map[index]
1069
transport, path = pack_obj.access_tuple()
1071
reader = pack.make_readv_reader(transport, path, readv_vector)
1072
except errors.NoSuchFile:
1073
if self._reload_func is not None:
1076
for (names, read_func), (key, eol_flag, references) in \
1077
izip(reader.iter_records(), node_vector):
1078
raw_data = read_func(None)
1080
# read the entire thing
1081
content, _ = knit._parse_record(key[-1], raw_data)
1082
if len(references[-1]) == 0:
1083
line_iterator = factory.get_fulltext_content(content)
1085
line_iterator = factory.get_linedelta_content(content)
1086
for line in line_iterator:
1089
# check the header only
1090
df, _ = knit._parse_record_header(key, raw_data)
1092
pos, size = writer.add_bytes_record(raw_data, names)
1093
write_index.add_node(key, eol_flag + "%d %d" % (pos, size), references)
1094
pb.update("Copied record", record_index)
1097
def _get_text_nodes(self):
1098
text_index_map, text_indices = self._pack_map_and_index_list(
1100
return text_index_map, self._index_contents(text_indices,
1103
def _least_readv_node_readv(self, nodes):
1104
"""Generate request groups for nodes using the least readv's.
1106
:param nodes: An iterable of graph index nodes.
1107
:return: Total node count and an iterator of the data needed to perform
1108
readvs to obtain the data for nodes. Each item yielded by the
1109
iterator is a tuple with:
1110
index, readv_vector, node_vector. readv_vector is a list ready to
1111
hand to the transport readv method, and node_vector is a list of
1112
(key, eol_flag, references) for the the node retrieved by the
1113
matching readv_vector.
1115
# group by pack so we do one readv per pack
1116
nodes = sorted(nodes)
1119
for index, key, value, references in nodes:
1120
if index not in request_groups:
1121
request_groups[index] = []
1122
request_groups[index].append((key, value, references))
1124
for index, items in request_groups.iteritems():
1125
pack_readv_requests = []
1126
for key, value, references in items:
1127
# ---- KnitGraphIndex.get_position
1128
bits = value[1:].split(' ')
1129
offset, length = int(bits[0]), int(bits[1])
1130
pack_readv_requests.append(
1131
((offset, length), (key, value[0], references)))
1132
# linear scan up the pack to maximum range combining.
1133
pack_readv_requests.sort()
1134
# split out the readv and the node data.
1135
pack_readv = [readv for readv, node in pack_readv_requests]
1136
node_vector = [node for readv, node in pack_readv_requests]
1137
result.append((index, pack_readv, node_vector))
1138
return total, result
1140
def _log_copied_texts(self):
1141
if 'pack' in debug.debug_flags:
1142
mutter('%s: create_pack: file texts copied: %s%s %d items t+%6.3fs',
1143
time.ctime(), self._pack_collection._upload_transport.base,
1144
self.new_pack.random_name,
1145
self.new_pack.text_index.key_count(),
1146
time.time() - self.new_pack.start_time)
1148
def _process_inventory_lines(self, inv_lines):
1149
"""Use up the inv_lines generator and setup a text key filter."""
1150
repo = self._pack_collection.repo
1151
fileid_revisions = repo._find_file_ids_from_xml_inventory_lines(
1152
inv_lines, self.revision_keys)
1154
for fileid, file_revids in fileid_revisions.iteritems():
1155
text_filter.extend([(fileid, file_revid) for file_revid in file_revids])
1156
self._text_filter = text_filter
1158
def _revision_node_readv(self, revision_nodes):
1159
"""Return the total revisions and the readv's to issue.
1161
:param revision_nodes: The revision index contents for the packs being
1162
incorporated into the new pack.
1163
:return: As per _least_readv_node_readv.
1165
return self._least_readv_node_readv(revision_nodes)
1167
def _use_pack(self, new_pack):
1168
"""Return True if new_pack should be used.
1170
:param new_pack: The pack that has just been created.
1171
:return: True if the pack should be used.
1173
return new_pack.data_inserted()
1176
class OptimisingPacker(Packer):
1177
"""A packer which spends more time to create better disk layouts."""
1179
def _revision_node_readv(self, revision_nodes):
1180
"""Return the total revisions and the readv's to issue.
1182
This sort places revisions in topological order with the ancestors
1185
:param revision_nodes: The revision index contents for the packs being
1186
incorporated into the new pack.
1187
:return: As per _least_readv_node_readv.
1189
# build an ancestors dict
1192
for index, key, value, references in revision_nodes:
1193
ancestors[key] = references[0]
1194
by_key[key] = (index, value, references)
1195
order = tsort.topo_sort(ancestors)
1197
# Single IO is pathological, but it will work as a starting point.
1199
for key in reversed(order):
1200
index, value, references = by_key[key]
1201
# ---- KnitGraphIndex.get_position
1202
bits = value[1:].split(' ')
1203
offset, length = int(bits[0]), int(bits[1])
1205
(index, [(offset, length)], [(key, value[0], references)]))
1206
# TODO: combine requests in the same index that are in ascending order.
1207
return total, requests
1209
def open_pack(self):
1210
"""Open a pack for the pack we are creating."""
1211
new_pack = super(OptimisingPacker, self).open_pack()
1212
# Turn on the optimization flags for all the index builders.
1213
new_pack.revision_index.set_optimize(for_size=True)
1214
new_pack.inventory_index.set_optimize(for_size=True)
1215
new_pack.text_index.set_optimize(for_size=True)
1216
new_pack.signature_index.set_optimize(for_size=True)
1220
class ReconcilePacker(Packer):
1221
"""A packer which regenerates indices etc as it copies.
1223
This is used by ``bzr reconcile`` to cause parent text pointers to be
1227
def _extra_init(self):
1228
self._data_changed = False
1230
def _process_inventory_lines(self, inv_lines):
1231
"""Generate a text key reference map rather for reconciling with."""
1232
repo = self._pack_collection.repo
1233
refs = repo._find_text_key_references_from_xml_inventory_lines(
1235
self._text_refs = refs
1236
# during reconcile we:
1237
# - convert unreferenced texts to full texts
1238
# - correct texts which reference a text not copied to be full texts
1239
# - copy all others as-is but with corrected parents.
1240
# - so at this point we don't know enough to decide what becomes a full
1242
self._text_filter = None
1244
def _copy_text_texts(self):
1245
"""generate what texts we should have and then copy."""
1246
self.pb.update("Copying content texts", 3)
1247
# we have three major tasks here:
1248
# 1) generate the ideal index
1249
repo = self._pack_collection.repo
1250
ancestors = dict([(key[0], tuple(ref[0] for ref in refs[0])) for
1251
_1, key, _2, refs in
1252
self.new_pack.revision_index.iter_all_entries()])
1253
ideal_index = repo._generate_text_key_index(self._text_refs, ancestors)
1254
# 2) generate a text_nodes list that contains all the deltas that can
1255
# be used as-is, with corrected parents.
1258
discarded_nodes = []
1259
NULL_REVISION = _mod_revision.NULL_REVISION
1260
text_index_map, text_nodes = self._get_text_nodes()
1261
for node in text_nodes:
1267
ideal_parents = tuple(ideal_index[node[1]])
1269
discarded_nodes.append(node)
1270
self._data_changed = True
1272
if ideal_parents == (NULL_REVISION,):
1274
if ideal_parents == node[3][0]:
1276
ok_nodes.append(node)
1277
elif ideal_parents[0:1] == node[3][0][0:1]:
1278
# the left most parent is the same, or there are no parents
1279
# today. Either way, we can preserve the representation as
1280
# long as we change the refs to be inserted.
1281
self._data_changed = True
1282
ok_nodes.append((node[0], node[1], node[2],
1283
(ideal_parents, node[3][1])))
1284
self._data_changed = True
1286
# Reinsert this text completely
1287
bad_texts.append((node[1], ideal_parents))
1288
self._data_changed = True
1289
# we're finished with some data.
1292
# 3) bulk copy the ok data
1293
total_items, readv_group_iter = self._least_readv_node_readv(ok_nodes)
1294
list(self._copy_nodes_graph(text_index_map, self.new_pack._writer,
1295
self.new_pack.text_index, readv_group_iter, total_items))
1296
# 4) adhoc copy all the other texts.
1297
# We have to topologically insert all texts otherwise we can fail to
1298
# reconcile when parts of a single delta chain are preserved intact,
1299
# and other parts are not. E.g. Discarded->d1->d2->d3. d1 will be
1300
# reinserted, and if d3 has incorrect parents it will also be
1301
# reinserted. If we insert d3 first, d2 is present (as it was bulk
1302
# copied), so we will try to delta, but d2 is not currently able to be
1303
# extracted because it's basis d1 is not present. Topologically sorting
1304
# addresses this. The following generates a sort for all the texts that
1305
# are being inserted without having to reference the entire text key
1306
# space (we only topo sort the revisions, which is smaller).
1307
topo_order = tsort.topo_sort(ancestors)
1308
rev_order = dict(zip(topo_order, range(len(topo_order))))
1309
bad_texts.sort(key=lambda key:rev_order.get(key[0][1], 0))
1310
transaction = repo.get_transaction()
1311
file_id_index = GraphIndexPrefixAdapter(
1312
self.new_pack.text_index,
1314
add_nodes_callback=self.new_pack.text_index.add_nodes)
1315
data_access = _DirectPackAccess(
1316
{self.new_pack.text_index:self.new_pack.access_tuple()})
1317
data_access.set_writer(self.new_pack._writer, self.new_pack.text_index,
1318
self.new_pack.access_tuple())
1319
output_texts = KnitVersionedFiles(
1320
_KnitGraphIndex(self.new_pack.text_index,
1321
add_callback=self.new_pack.text_index.add_nodes,
1322
deltas=True, parents=True, is_locked=repo.is_locked),
1323
data_access=data_access, max_delta_chain=200)
1324
for key, parent_keys in bad_texts:
1325
# We refer to the new pack to delta data being output.
1326
# A possible improvement would be to catch errors on short reads
1327
# and only flush then.
1328
self.new_pack.flush()
1330
for parent_key in parent_keys:
1331
if parent_key[0] != key[0]:
1332
# Graph parents must match the fileid
1333
raise errors.BzrError('Mismatched key parent %r:%r' %
1335
parents.append(parent_key[1])
1336
text_lines = osutils.split_lines(repo.texts.get_record_stream(
1337
[key], 'unordered', True).next().get_bytes_as('fulltext'))
1338
output_texts.add_lines(key, parent_keys, text_lines,
1339
random_id=True, check_content=False)
1340
# 5) check that nothing inserted has a reference outside the keyspace.
1341
missing_text_keys = self.new_pack.text_index._external_references()
1342
if missing_text_keys:
1343
raise errors.BzrCheckError('Reference to missing compression parents %r'
1344
% (missing_text_keys,))
1345
self._log_copied_texts()
1347
def _use_pack(self, new_pack):
1348
"""Override _use_pack to check for reconcile having changed content."""
1349
# XXX: we might be better checking this at the copy time.
1350
original_inventory_keys = set()
1351
inv_index = self._pack_collection.inventory_index.combined_index
1352
for entry in inv_index.iter_all_entries():
1353
original_inventory_keys.add(entry[1])
1354
new_inventory_keys = set()
1355
for entry in new_pack.inventory_index.iter_all_entries():
1356
new_inventory_keys.add(entry[1])
1357
if new_inventory_keys != original_inventory_keys:
1358
self._data_changed = True
1359
return new_pack.data_inserted() and self._data_changed
1362
class RepositoryPackCollection(object):
1363
"""Management of packs within a repository.
1365
:ivar _names: map of {pack_name: (index_size,)}
1368
pack_factory = NewPack
1369
resumed_pack_factory = ResumedPack
1371
def __init__(self, repo, transport, index_transport, upload_transport,
1372
pack_transport, index_builder_class, index_class,
1374
"""Create a new RepositoryPackCollection.
1376
:param transport: Addresses the repository base directory
1377
(typically .bzr/repository/).
1378
:param index_transport: Addresses the directory containing indices.
1379
:param upload_transport: Addresses the directory into which packs are written
1380
while they're being created.
1381
:param pack_transport: Addresses the directory of existing complete packs.
1382
:param index_builder_class: The index builder class to use.
1383
:param index_class: The index class to use.
1384
:param use_chk_index: Whether to setup and manage a CHK index.
1386
# XXX: This should call self.reset()
1388
self.transport = transport
1389
self._index_transport = index_transport
1390
self._upload_transport = upload_transport
1391
self._pack_transport = pack_transport
1392
self._index_builder_class = index_builder_class
1393
self._index_class = index_class
1394
self._suffix_offsets = {'.rix': 0, '.iix': 1, '.tix': 2, '.six': 3,
1399
self._packs_by_name = {}
1400
# the previous pack-names content
1401
self._packs_at_load = None
1402
# when a pack is being created by this object, the state of that pack.
1403
self._new_pack = None
1404
# aggregated revision index data
1405
flush = self._flush_new_pack
1406
self.revision_index = AggregateIndex(self.reload_pack_names, flush)
1407
self.inventory_index = AggregateIndex(self.reload_pack_names, flush)
1408
self.text_index = AggregateIndex(self.reload_pack_names, flush)
1409
self.signature_index = AggregateIndex(self.reload_pack_names, flush)
1411
self.chk_index = AggregateIndex(self.reload_pack_names, flush)
1413
# used to determine if we're using a chk_index elsewhere.
1414
self.chk_index = None
1416
self._resumed_packs = []
1418
def add_pack_to_memory(self, pack):
1419
"""Make a Pack object available to the repository to satisfy queries.
1421
:param pack: A Pack object.
1423
if pack.name in self._packs_by_name:
1424
raise AssertionError(
1425
'pack %s already in _packs_by_name' % (pack.name,))
1426
self.packs.append(pack)
1427
self._packs_by_name[pack.name] = pack
1428
self.revision_index.add_index(pack.revision_index, pack)
1429
self.inventory_index.add_index(pack.inventory_index, pack)
1430
self.text_index.add_index(pack.text_index, pack)
1431
self.signature_index.add_index(pack.signature_index, pack)
1432
if self.chk_index is not None:
1433
self.chk_index.add_index(pack.chk_index, pack)
1435
def all_packs(self):
1436
"""Return a list of all the Pack objects this repository has.
1438
Note that an in-progress pack being created is not returned.
1440
:return: A list of Pack objects for all the packs in the repository.
1443
for name in self.names():
1444
result.append(self.get_pack_by_name(name))
1448
"""Pack the pack collection incrementally.
1450
This will not attempt global reorganisation or recompression,
1451
rather it will just ensure that the total number of packs does
1452
not grow without bound. It uses the _max_pack_count method to
1453
determine if autopacking is needed, and the pack_distribution
1454
method to determine the number of revisions in each pack.
1456
If autopacking takes place then the packs name collection will have
1457
been flushed to disk - packing requires updating the name collection
1458
in synchronisation with certain steps. Otherwise the names collection
1461
:return: True if packing took place.
1465
return self._do_autopack()
1466
except errors.RetryAutopack, e:
1467
# If we get a RetryAutopack exception, we should abort the
1468
# current action, and retry.
1471
def _do_autopack(self):
1472
# XXX: Should not be needed when the management of indices is sane.
1473
total_revisions = self.revision_index.combined_index.key_count()
1474
total_packs = len(self._names)
1475
if self._max_pack_count(total_revisions) >= total_packs:
1477
# determine which packs need changing
1478
pack_distribution = self.pack_distribution(total_revisions)
1480
for pack in self.all_packs():
1481
revision_count = pack.get_revision_count()
1482
if revision_count == 0:
1483
# revision less packs are not generated by normal operation,
1484
# only by operations like sign-my-commits, and thus will not
1485
# tend to grow rapdily or without bound like commit containing
1486
# packs do - leave them alone as packing them really should
1487
# group their data with the relevant commit, and that may
1488
# involve rewriting ancient history - which autopack tries to
1489
# avoid. Alternatively we could not group the data but treat
1490
# each of these as having a single revision, and thus add
1491
# one revision for each to the total revision count, to get
1492
# a matching distribution.
1494
existing_packs.append((revision_count, pack))
1495
pack_operations = self.plan_autopack_combinations(
1496
existing_packs, pack_distribution)
1497
num_new_packs = len(pack_operations)
1498
num_old_packs = sum([len(po[1]) for po in pack_operations])
1499
num_revs_affected = sum([po[0] for po in pack_operations])
1500
mutter('Auto-packing repository %s, which has %d pack files, '
1501
'containing %d revisions. Packing %d files into %d affecting %d'
1502
' revisions', self, total_packs, total_revisions, num_old_packs,
1503
num_new_packs, num_revs_affected)
1504
self._execute_pack_operations(pack_operations,
1505
reload_func=self._restart_autopack)
1506
mutter('Auto-packing repository %s completed', self)
1509
def _execute_pack_operations(self, pack_operations, _packer_class=Packer,
1511
"""Execute a series of pack operations.
1513
:param pack_operations: A list of [revision_count, packs_to_combine].
1514
:param _packer_class: The class of packer to use (default: Packer).
1517
for revision_count, packs in pack_operations:
1518
# we may have no-ops from the setup logic
1521
packer = _packer_class(self, packs, '.autopack',
1522
reload_func=reload_func)
1525
except errors.RetryWithNewPacks:
1526
# An exception is propagating out of this context, make sure
1527
# this packer has cleaned up. Packer() doesn't set its new_pack
1528
# state into the RepositoryPackCollection object, so we only
1529
# have access to it directly here.
1530
if packer.new_pack is not None:
1531
packer.new_pack.abort()
1534
self._remove_pack_from_memory(pack)
1535
# record the newly available packs and stop advertising the old
1537
self._save_pack_names(clear_obsolete_packs=True)
1538
# Move the old packs out of the way now they are no longer referenced.
1539
for revision_count, packs in pack_operations:
1540
self._obsolete_packs(packs)
1542
def _flush_new_pack(self):
1543
if self._new_pack is not None:
1544
self._new_pack.flush()
1546
def lock_names(self):
1547
"""Acquire the mutex around the pack-names index.
1549
This cannot be used in the middle of a read-only transaction on the
1552
self.repo.control_files.lock_write()
1554
def _already_packed(self):
1555
"""Is the collection already packed?"""
1556
return len(self._names) < 2
1559
"""Pack the pack collection totally."""
1560
self.ensure_loaded()
1561
total_packs = len(self._names)
1562
if self._already_packed():
1563
# This is arguably wrong because we might not be optimal, but for
1564
# now lets leave it in. (e.g. reconcile -> one pack. But not
1567
total_revisions = self.revision_index.combined_index.key_count()
1568
# XXX: the following may want to be a class, to pack with a given
1570
mutter('Packing repository %s, which has %d pack files, '
1571
'containing %d revisions into 1 packs.', self, total_packs,
1573
# determine which packs need changing
1574
pack_distribution = [1]
1575
pack_operations = [[0, []]]
1576
for pack in self.all_packs():
1577
pack_operations[-1][0] += pack.get_revision_count()
1578
pack_operations[-1][1].append(pack)
1579
self._execute_pack_operations(pack_operations, OptimisingPacker)
1581
def plan_autopack_combinations(self, existing_packs, pack_distribution):
1582
"""Plan a pack operation.
1584
:param existing_packs: The packs to pack. (A list of (revcount, Pack)
1586
:param pack_distribution: A list with the number of revisions desired
1589
if len(existing_packs) <= len(pack_distribution):
1591
existing_packs.sort(reverse=True)
1592
pack_operations = [[0, []]]
1593
# plan out what packs to keep, and what to reorganise
1594
while len(existing_packs):
1595
# take the largest pack, and if its less than the head of the
1596
# distribution chart we will include its contents in the new pack
1597
# for that position. If its larger, we remove its size from the
1598
# distribution chart
1599
next_pack_rev_count, next_pack = existing_packs.pop(0)
1600
if next_pack_rev_count >= pack_distribution[0]:
1601
# this is already packed 'better' than this, so we can
1602
# not waste time packing it.
1603
while next_pack_rev_count > 0:
1604
next_pack_rev_count -= pack_distribution[0]
1605
if next_pack_rev_count >= 0:
1607
del pack_distribution[0]
1609
# didn't use that entire bucket up
1610
pack_distribution[0] = -next_pack_rev_count
1612
# add the revisions we're going to add to the next output pack
1613
pack_operations[-1][0] += next_pack_rev_count
1614
# allocate this pack to the next pack sub operation
1615
pack_operations[-1][1].append(next_pack)
1616
if pack_operations[-1][0] >= pack_distribution[0]:
1617
# this pack is used up, shift left.
1618
del pack_distribution[0]
1619
pack_operations.append([0, []])
1620
# Now that we know which pack files we want to move, shove them all
1621
# into a single pack file.
1623
final_pack_list = []
1624
for num_revs, pack_files in pack_operations:
1625
final_rev_count += num_revs
1626
final_pack_list.extend(pack_files)
1627
if len(final_pack_list) == 1:
1628
raise AssertionError('We somehow generated an autopack with a'
1629
' single pack file being moved.')
1631
return [[final_rev_count, final_pack_list]]
1633
def ensure_loaded(self):
1634
"""Ensure we have read names from disk.
1636
:return: True if the disk names had not been previously read.
1638
# NB: if you see an assertion error here, its probably access against
1639
# an unlocked repo. Naughty.
1640
if not self.repo.is_locked():
1641
raise errors.ObjectNotLocked(self.repo)
1642
if self._names is None:
1644
self._packs_at_load = set()
1645
for index, key, value in self._iter_disk_pack_index():
1647
self._names[name] = self._parse_index_sizes(value)
1648
self._packs_at_load.add((key, value))
1652
# populate all the metadata.
1656
def _parse_index_sizes(self, value):
1657
"""Parse a string of index sizes."""
1658
return tuple([int(digits) for digits in value.split(' ')])
1660
def get_pack_by_name(self, name):
1661
"""Get a Pack object by name.
1663
:param name: The name of the pack - e.g. '123456'
1664
:return: A Pack object.
1667
return self._packs_by_name[name]
1669
rev_index = self._make_index(name, '.rix')
1670
inv_index = self._make_index(name, '.iix')
1671
txt_index = self._make_index(name, '.tix')
1672
sig_index = self._make_index(name, '.six')
1673
if self.chk_index is not None:
1674
chk_index = self._make_index(name, '.cix')
1677
result = ExistingPack(self._pack_transport, name, rev_index,
1678
inv_index, txt_index, sig_index, chk_index)
1679
self.add_pack_to_memory(result)
1682
def _resume_pack(self, name):
1683
"""Get a suspended Pack object by name.
1685
:param name: The name of the pack - e.g. '123456'
1686
:return: A Pack object.
1688
if not re.match('[a-f0-9]{32}', name):
1689
# Tokens should be md5sums of the suspended pack file, i.e. 32 hex
1691
raise errors.UnresumableWriteGroup(
1692
self.repo, [name], 'Malformed write group token')
1694
rev_index = self._make_index(name, '.rix', resume=True)
1695
inv_index = self._make_index(name, '.iix', resume=True)
1696
txt_index = self._make_index(name, '.tix', resume=True)
1697
sig_index = self._make_index(name, '.six', resume=True)
1698
if self.chk_index is not None:
1699
chk_index = self._make_index(name, '.cix', resume=True)
1702
result = self.resumed_pack_factory(name, rev_index, inv_index,
1703
txt_index, sig_index, self._upload_transport,
1704
self._pack_transport, self._index_transport, self,
1705
chk_index=chk_index)
1706
except errors.NoSuchFile, e:
1707
raise errors.UnresumableWriteGroup(self.repo, [name], str(e))
1708
self.add_pack_to_memory(result)
1709
self._resumed_packs.append(result)
1712
def allocate(self, a_new_pack):
1713
"""Allocate name in the list of packs.
1715
:param a_new_pack: A NewPack instance to be added to the collection of
1716
packs for this repository.
1718
self.ensure_loaded()
1719
if a_new_pack.name in self._names:
1720
raise errors.BzrError(
1721
'Pack %r already exists in %s' % (a_new_pack.name, self))
1722
self._names[a_new_pack.name] = tuple(a_new_pack.index_sizes)
1723
self.add_pack_to_memory(a_new_pack)
1725
def _iter_disk_pack_index(self):
1726
"""Iterate over the contents of the pack-names index.
1728
This is used when loading the list from disk, and before writing to
1729
detect updates from others during our write operation.
1730
:return: An iterator of the index contents.
1732
return self._index_class(self.transport, 'pack-names', None
1733
).iter_all_entries()
1735
def _make_index(self, name, suffix, resume=False):
1736
size_offset = self._suffix_offsets[suffix]
1737
index_name = name + suffix
1739
transport = self._upload_transport
1740
index_size = transport.stat(index_name).st_size
1742
transport = self._index_transport
1743
index_size = self._names[name][size_offset]
1744
return self._index_class(transport, index_name, index_size)
1746
def _max_pack_count(self, total_revisions):
1747
"""Return the maximum number of packs to use for total revisions.
1749
:param total_revisions: The total number of revisions in the
1752
if not total_revisions:
1754
digits = str(total_revisions)
1756
for digit in digits:
1757
result += int(digit)
1761
"""Provide an order to the underlying names."""
1762
return sorted(self._names.keys())
1764
def _obsolete_packs(self, packs):
1765
"""Move a number of packs which have been obsoleted out of the way.
1767
Each pack and its associated indices are moved out of the way.
1769
Note: for correctness this function should only be called after a new
1770
pack names index has been written without these pack names, and with
1771
the names of packs that contain the data previously available via these
1774
:param packs: The packs to obsolete.
1775
:param return: None.
1778
pack.pack_transport.rename(pack.file_name(),
1779
'../obsolete_packs/' + pack.file_name())
1780
# TODO: Probably needs to know all possible indices for this pack
1781
# - or maybe list the directory and move all indices matching this
1782
# name whether we recognize it or not?
1783
suffixes = ['.iix', '.six', '.tix', '.rix']
1784
if self.chk_index is not None:
1785
suffixes.append('.cix')
1786
for suffix in suffixes:
1787
self._index_transport.rename(pack.name + suffix,
1788
'../obsolete_packs/' + pack.name + suffix)
1790
def pack_distribution(self, total_revisions):
1791
"""Generate a list of the number of revisions to put in each pack.
1793
:param total_revisions: The total number of revisions in the
1796
if total_revisions == 0:
1798
digits = reversed(str(total_revisions))
1800
for exponent, count in enumerate(digits):
1801
size = 10 ** exponent
1802
for pos in range(int(count)):
1804
return list(reversed(result))
1806
def _pack_tuple(self, name):
1807
"""Return a tuple with the transport and file name for a pack name."""
1808
return self._pack_transport, name + '.pack'
1810
def _remove_pack_from_memory(self, pack):
1811
"""Remove pack from the packs accessed by this repository.
1813
Only affects memory state, until self._save_pack_names() is invoked.
1815
self._names.pop(pack.name)
1816
self._packs_by_name.pop(pack.name)
1817
self._remove_pack_indices(pack)
1818
self.packs.remove(pack)
1820
def _remove_pack_indices(self, pack):
1821
"""Remove the indices for pack from the aggregated indices."""
1822
self.revision_index.remove_index(pack.revision_index, pack)
1823
self.inventory_index.remove_index(pack.inventory_index, pack)
1824
self.text_index.remove_index(pack.text_index, pack)
1825
self.signature_index.remove_index(pack.signature_index, pack)
1826
if self.chk_index is not None:
1827
self.chk_index.remove_index(pack.chk_index, pack)
1830
"""Clear all cached data."""
1831
# cached revision data
1832
self.revision_index.clear()
1833
# cached signature data
1834
self.signature_index.clear()
1835
# cached file text data
1836
self.text_index.clear()
1837
# cached inventory data
1838
self.inventory_index.clear()
1840
if self.chk_index is not None:
1841
self.chk_index.clear()
1842
# remove the open pack
1843
self._new_pack = None
1844
# information about packs.
1847
self._packs_by_name = {}
1848
self._packs_at_load = None
1850
def _unlock_names(self):
1851
"""Release the mutex around the pack-names index."""
1852
self.repo.control_files.unlock()
1854
def _diff_pack_names(self):
1855
"""Read the pack names from disk, and compare it to the one in memory.
1857
:return: (disk_nodes, deleted_nodes, new_nodes)
1858
disk_nodes The final set of nodes that should be referenced
1859
deleted_nodes Nodes which have been removed from when we started
1860
new_nodes Nodes that are newly introduced
1862
# load the disk nodes across
1864
for index, key, value in self._iter_disk_pack_index():
1865
disk_nodes.add((key, value))
1867
# do a two-way diff against our original content
1868
current_nodes = set()
1869
for name, sizes in self._names.iteritems():
1871
((name, ), ' '.join(str(size) for size in sizes)))
1873
# Packs no longer present in the repository, which were present when we
1874
# locked the repository
1875
deleted_nodes = self._packs_at_load - current_nodes
1876
# Packs which this process is adding
1877
new_nodes = current_nodes - self._packs_at_load
1879
# Update the disk_nodes set to include the ones we are adding, and
1880
# remove the ones which were removed by someone else
1881
disk_nodes.difference_update(deleted_nodes)
1882
disk_nodes.update(new_nodes)
1884
return disk_nodes, deleted_nodes, new_nodes
1886
def _syncronize_pack_names_from_disk_nodes(self, disk_nodes):
1887
"""Given the correct set of pack files, update our saved info.
1889
:return: (removed, added, modified)
1890
removed pack names removed from self._names
1891
added pack names added to self._names
1892
modified pack names that had changed value
1897
## self._packs_at_load = disk_nodes
1898
new_names = dict(disk_nodes)
1899
# drop no longer present nodes
1900
for pack in self.all_packs():
1901
if (pack.name,) not in new_names:
1902
removed.append(pack.name)
1903
self._remove_pack_from_memory(pack)
1904
# add new nodes/refresh existing ones
1905
for key, value in disk_nodes:
1907
sizes = self._parse_index_sizes(value)
1908
if name in self._names:
1910
if sizes != self._names[name]:
1911
# the pack for name has had its indices replaced - rare but
1912
# important to handle. XXX: probably can never happen today
1913
# because the three-way merge code above does not handle it
1914
# - you may end up adding the same key twice to the new
1915
# disk index because the set values are the same, unless
1916
# the only index shows up as deleted by the set difference
1917
# - which it may. Until there is a specific test for this,
1918
# assume its broken. RBC 20071017.
1919
self._remove_pack_from_memory(self.get_pack_by_name(name))
1920
self._names[name] = sizes
1921
self.get_pack_by_name(name)
1922
modified.append(name)
1925
self._names[name] = sizes
1926
self.get_pack_by_name(name)
1928
return removed, added, modified
1930
def _save_pack_names(self, clear_obsolete_packs=False):
1931
"""Save the list of packs.
1933
This will take out the mutex around the pack names list for the
1934
duration of the method call. If concurrent updates have been made, a
1935
three-way merge between the current list and the current in memory list
1938
:param clear_obsolete_packs: If True, clear out the contents of the
1939
obsolete_packs directory.
1943
builder = self._index_builder_class()
1944
disk_nodes, deleted_nodes, new_nodes = self._diff_pack_names()
1945
# TODO: handle same-name, index-size-changes here -
1946
# e.g. use the value from disk, not ours, *unless* we're the one
1948
for key, value in disk_nodes:
1949
builder.add_node(key, value)
1950
self.transport.put_file('pack-names', builder.finish(),
1951
mode=self.repo.bzrdir._get_file_mode())
1952
# move the baseline forward
1953
self._packs_at_load = disk_nodes
1954
if clear_obsolete_packs:
1955
self._clear_obsolete_packs()
1957
self._unlock_names()
1958
# synchronise the memory packs list with what we just wrote:
1959
self._syncronize_pack_names_from_disk_nodes(disk_nodes)
1961
def reload_pack_names(self):
1962
"""Sync our pack listing with what is present in the repository.
1964
This should be called when we find out that something we thought was
1965
present is now missing. This happens when another process re-packs the
1968
:return: True if the in-memory list of packs has been altered at all.
1970
# The ensure_loaded call is to handle the case where the first call
1971
# made involving the collection was to reload_pack_names, where we
1972
# don't have a view of disk contents. Its a bit of a bandaid, and
1973
# causes two reads of pack-names, but its a rare corner case not struck
1974
# with regular push/pull etc.
1975
first_read = self.ensure_loaded()
1978
# out the new value.
1979
disk_nodes, _, _ = self._diff_pack_names()
1980
self._packs_at_load = disk_nodes
1982
modified) = self._syncronize_pack_names_from_disk_nodes(disk_nodes)
1983
if removed or added or modified:
1987
def _restart_autopack(self):
1988
"""Reload the pack names list, and restart the autopack code."""
1989
if not self.reload_pack_names():
1990
# Re-raise the original exception, because something went missing
1991
# and a restart didn't find it
1993
raise errors.RetryAutopack(self.repo, False, sys.exc_info())
1995
def _clear_obsolete_packs(self):
1996
"""Delete everything from the obsolete-packs directory.
1998
obsolete_pack_transport = self.transport.clone('obsolete_packs')
1999
for filename in obsolete_pack_transport.list_dir('.'):
2001
obsolete_pack_transport.delete(filename)
2002
except (errors.PathError, errors.TransportError), e:
2003
warning("couldn't delete obsolete pack, skipping it:\n%s" % (e,))
2005
def _start_write_group(self):
2006
# Do not permit preparation for writing if we're not in a 'write lock'.
2007
if not self.repo.is_write_locked():
2008
raise errors.NotWriteLocked(self)
2009
self._new_pack = self.pack_factory(self, upload_suffix='.pack',
2010
file_mode=self.repo.bzrdir._get_file_mode())
2011
# allow writing: queue writes to a new index
2012
self.revision_index.add_writable_index(self._new_pack.revision_index,
2014
self.inventory_index.add_writable_index(self._new_pack.inventory_index,
2016
self.text_index.add_writable_index(self._new_pack.text_index,
2018
self._new_pack.text_index.set_optimize(combine_backing_indices=False)
2019
self.signature_index.add_writable_index(self._new_pack.signature_index,
2021
if self.chk_index is not None:
2022
self.chk_index.add_writable_index(self._new_pack.chk_index,
2024
self.repo.chk_bytes._index._add_callback = self.chk_index.add_callback
2025
self._new_pack.chk_index.set_optimize(combine_backing_indices=False)
2027
self.repo.inventories._index._add_callback = self.inventory_index.add_callback
2028
self.repo.revisions._index._add_callback = self.revision_index.add_callback
2029
self.repo.signatures._index._add_callback = self.signature_index.add_callback
2030
self.repo.texts._index._add_callback = self.text_index.add_callback
2032
def _abort_write_group(self):
2033
# FIXME: just drop the transient index.
2034
# forget what names there are
2035
if self._new_pack is not None:
2037
self._new_pack.abort()
2039
# XXX: If we aborted while in the middle of finishing the write
2040
# group, _remove_pack_indices can fail because the indexes are
2041
# already gone. If they're not there we shouldn't fail in this
2042
# case. -- mbp 20081113
2043
self._remove_pack_indices(self._new_pack)
2044
self._new_pack = None
2045
for resumed_pack in self._resumed_packs:
2047
resumed_pack.abort()
2049
# See comment in previous finally block.
2051
self._remove_pack_indices(resumed_pack)
2054
del self._resumed_packs[:]
2056
def _remove_resumed_pack_indices(self):
2057
for resumed_pack in self._resumed_packs:
2058
self._remove_pack_indices(resumed_pack)
2059
del self._resumed_packs[:]
2061
def _commit_write_group(self):
2063
for prefix, versioned_file in (
2064
('revisions', self.repo.revisions),
2065
('inventories', self.repo.inventories),
2066
('texts', self.repo.texts),
2067
('signatures', self.repo.signatures),
2069
missing = versioned_file.get_missing_compression_parent_keys()
2070
all_missing.update([(prefix,) + key for key in missing])
2072
raise errors.BzrCheckError(
2073
"Repository %s has missing compression parent(s) %r "
2074
% (self.repo, sorted(all_missing)))
2075
self._remove_pack_indices(self._new_pack)
2076
should_autopack = False
2077
if self._new_pack.data_inserted():
2078
# get all the data to disk and read to use
2079
self._new_pack.finish()
2080
self.allocate(self._new_pack)
2081
self._new_pack = None
2082
should_autopack = True
2084
self._new_pack.abort()
2085
self._new_pack = None
2086
for resumed_pack in self._resumed_packs:
2087
# XXX: this is a pretty ugly way to turn the resumed pack into a
2088
# properly committed pack.
2089
self._names[resumed_pack.name] = None
2090
self._remove_pack_from_memory(resumed_pack)
2091
resumed_pack.finish()
2092
self.allocate(resumed_pack)
2093
should_autopack = True
2094
del self._resumed_packs[:]
2096
if not self.autopack():
2097
# when autopack takes no steps, the names list is still
2099
self._save_pack_names()
2101
def _suspend_write_group(self):
2102
tokens = [pack.name for pack in self._resumed_packs]
2103
self._remove_pack_indices(self._new_pack)
2104
if self._new_pack.data_inserted():
2105
# get all the data to disk and read to use
2106
self._new_pack.finish(suspend=True)
2107
tokens.append(self._new_pack.name)
2108
self._new_pack = None
2110
self._new_pack.abort()
2111
self._new_pack = None
2112
self._remove_resumed_pack_indices()
2115
def _resume_write_group(self, tokens):
2116
for token in tokens:
2117
self._resume_pack(token)
2120
class KnitPackRepository(KnitRepository):
2121
"""Repository with knit objects stored inside pack containers.
2123
The layering for a KnitPackRepository is:
2125
Graph | HPSS | Repository public layer |
2126
===================================================
2127
Tuple based apis below, string based, and key based apis above
2128
---------------------------------------------------
2130
Provides .texts, .revisions etc
2131
This adapts the N-tuple keys to physical knit records which only have a
2132
single string identifier (for historical reasons), which in older formats
2133
was always the revision_id, and in the mapped code for packs is always
2134
the last element of key tuples.
2135
---------------------------------------------------
2137
A separate GraphIndex is used for each of the
2138
texts/inventories/revisions/signatures contained within each individual
2139
pack file. The GraphIndex layer works in N-tuples and is unaware of any
2141
===================================================
2145
def __init__(self, _format, a_bzrdir, control_files, _commit_builder_class,
2147
KnitRepository.__init__(self, _format, a_bzrdir, control_files,
2148
_commit_builder_class, _serializer)
2149
index_transport = self._transport.clone('indices')
2150
self._pack_collection = RepositoryPackCollection(self, self._transport,
2152
self._transport.clone('upload'),
2153
self._transport.clone('packs'),
2154
_format.index_builder_class,
2155
_format.index_class,
2156
use_chk_index=self._format.supports_chks,
2158
self.inventories = KnitVersionedFiles(
2159
_KnitGraphIndex(self._pack_collection.inventory_index.combined_index,
2160
add_callback=self._pack_collection.inventory_index.add_callback,
2161
deltas=True, parents=True, is_locked=self.is_locked),
2162
data_access=self._pack_collection.inventory_index.data_access,
2163
max_delta_chain=200)
2164
self.revisions = KnitVersionedFiles(
2165
_KnitGraphIndex(self._pack_collection.revision_index.combined_index,
2166
add_callback=self._pack_collection.revision_index.add_callback,
2167
deltas=False, parents=True, is_locked=self.is_locked,
2168
track_external_parent_refs=True),
2169
data_access=self._pack_collection.revision_index.data_access,
2171
self.signatures = KnitVersionedFiles(
2172
_KnitGraphIndex(self._pack_collection.signature_index.combined_index,
2173
add_callback=self._pack_collection.signature_index.add_callback,
2174
deltas=False, parents=False, is_locked=self.is_locked),
2175
data_access=self._pack_collection.signature_index.data_access,
2177
self.texts = KnitVersionedFiles(
2178
_KnitGraphIndex(self._pack_collection.text_index.combined_index,
2179
add_callback=self._pack_collection.text_index.add_callback,
2180
deltas=True, parents=True, is_locked=self.is_locked),
2181
data_access=self._pack_collection.text_index.data_access,
2182
max_delta_chain=200)
2183
if _format.supports_chks:
2184
# No graph, no compression:- references from chks are between
2185
# different objects not temporal versions of the same; and without
2186
# some sort of temporal structure knit compression will just fail.
2187
self.chk_bytes = KnitVersionedFiles(
2188
_KnitGraphIndex(self._pack_collection.chk_index.combined_index,
2189
add_callback=self._pack_collection.chk_index.add_callback,
2190
deltas=False, parents=False, is_locked=self.is_locked),
2191
data_access=self._pack_collection.chk_index.data_access,
2194
self.chk_bytes = None
2195
# True when the repository object is 'write locked' (as opposed to the
2196
# physical lock only taken out around changes to the pack-names list.)
2197
# Another way to represent this would be a decorator around the control
2198
# files object that presents logical locks as physical ones - if this
2199
# gets ugly consider that alternative design. RBC 20071011
2200
self._write_lock_count = 0
2201
self._transaction = None
2203
self._reconcile_does_inventory_gc = True
2204
self._reconcile_fixes_text_parents = True
2205
self._reconcile_backsup_inventory = False
2207
def _warn_if_deprecated(self):
2208
# This class isn't deprecated, but one sub-format is
2209
if isinstance(self._format, RepositoryFormatKnitPack5RichRootBroken):
2210
from bzrlib import repository
2211
if repository._deprecation_warning_done:
2213
repository._deprecation_warning_done = True
2214
warning("Format %s for %s is deprecated - please use"
2215
" 'bzr upgrade --1.6.1-rich-root'"
2216
% (self._format, self.bzrdir.transport.base))
2218
def _abort_write_group(self):
2219
self.revisions._index._key_dependencies.refs.clear()
2220
self._pack_collection._abort_write_group()
2222
def _find_inconsistent_revision_parents(self):
2223
"""Find revisions with incorrectly cached parents.
2225
:returns: an iterator yielding tuples of (revison-id, parents-in-index,
2226
parents-in-revision).
2228
if not self.is_locked():
2229
raise errors.ObjectNotLocked(self)
2230
pb = ui.ui_factory.nested_progress_bar()
2233
revision_nodes = self._pack_collection.revision_index \
2234
.combined_index.iter_all_entries()
2235
index_positions = []
2236
# Get the cached index values for all revisions, and also the
2237
# location in each index of the revision text so we can perform
2239
for index, key, value, refs in revision_nodes:
2240
node = (index, key, value, refs)
2241
index_memo = self.revisions._index._node_to_position(node)
2242
if index_memo[0] != index:
2243
raise AssertionError('%r != %r' % (index_memo[0], index))
2244
index_positions.append((index_memo, key[0],
2245
tuple(parent[0] for parent in refs[0])))
2246
pb.update("Reading revision index", 0, 0)
2247
index_positions.sort()
2249
pb.update("Checking cached revision graph", 0,
2250
len(index_positions))
2251
for offset in xrange(0, len(index_positions), 1000):
2252
pb.update("Checking cached revision graph", offset)
2253
to_query = index_positions[offset:offset + batch_size]
2256
rev_ids = [item[1] for item in to_query]
2257
revs = self.get_revisions(rev_ids)
2258
for revision, item in zip(revs, to_query):
2259
index_parents = item[2]
2260
rev_parents = tuple(revision.parent_ids)
2261
if index_parents != rev_parents:
2262
result.append((revision.revision_id, index_parents,
2268
def _make_parents_provider(self):
2269
return graph.CachingParentsProvider(self)
2271
def _refresh_data(self):
2272
if not self.is_locked():
2274
self._pack_collection.reload_pack_names()
2276
def _start_write_group(self):
2277
self._pack_collection._start_write_group()
2279
def _commit_write_group(self):
2280
self.revisions._index._key_dependencies.refs.clear()
2281
return self._pack_collection._commit_write_group()
2283
def suspend_write_group(self):
2284
# XXX check self._write_group is self.get_transaction()?
2285
tokens = self._pack_collection._suspend_write_group()
2286
self.revisions._index._key_dependencies.refs.clear()
2287
self._write_group = None
2290
def _resume_write_group(self, tokens):
2291
self._start_write_group()
2293
self._pack_collection._resume_write_group(tokens)
2294
except errors.UnresumableWriteGroup:
2295
self._abort_write_group()
2297
for pack in self._pack_collection._resumed_packs:
2298
self.revisions._index.scan_unvalidated_index(pack.revision_index)
2300
def get_transaction(self):
2301
if self._write_lock_count:
2302
return self._transaction
2304
return self.control_files.get_transaction()
2306
def is_locked(self):
2307
return self._write_lock_count or self.control_files.is_locked()
2309
def is_write_locked(self):
2310
return self._write_lock_count
2312
def lock_write(self, token=None):
2313
locked = self.is_locked()
2314
if not self._write_lock_count and locked:
2315
raise errors.ReadOnlyError(self)
2316
self._write_lock_count += 1
2317
if self._write_lock_count == 1:
2318
self._transaction = transactions.WriteTransaction()
2320
for repo in self._fallback_repositories:
2321
# Writes don't affect fallback repos
2323
self._refresh_data()
2325
def lock_read(self):
2326
locked = self.is_locked()
2327
if self._write_lock_count:
2328
self._write_lock_count += 1
2330
self.control_files.lock_read()
2332
for repo in self._fallback_repositories:
2334
self._refresh_data()
2336
def leave_lock_in_place(self):
2337
# not supported - raise an error
2338
raise NotImplementedError(self.leave_lock_in_place)
2340
def dont_leave_lock_in_place(self):
2341
# not supported - raise an error
2342
raise NotImplementedError(self.dont_leave_lock_in_place)
2346
"""Compress the data within the repository.
2348
This will pack all the data to a single pack. In future it may
2349
recompress deltas or do other such expensive operations.
2351
self._pack_collection.pack()
2354
def reconcile(self, other=None, thorough=False):
2355
"""Reconcile this repository."""
2356
from bzrlib.reconcile import PackReconciler
2357
reconciler = PackReconciler(self, thorough=thorough)
2358
reconciler.reconcile()
2361
def _reconcile_pack(self, collection, packs, extension, revs, pb):
2362
packer = ReconcilePacker(collection, packs, extension, revs)
2363
return packer.pack(pb)
2366
if self._write_lock_count == 1 and self._write_group is not None:
2367
self.abort_write_group()
2368
self._transaction = None
2369
self._write_lock_count = 0
2370
raise errors.BzrError(
2371
'Must end write group before releasing write lock on %s'
2373
if self._write_lock_count:
2374
self._write_lock_count -= 1
2375
if not self._write_lock_count:
2376
transaction = self._transaction
2377
self._transaction = None
2378
transaction.finish()
2380
self.control_files.unlock()
2382
if not self.is_locked():
2383
for repo in self._fallback_repositories:
2387
class RepositoryFormatPack(MetaDirRepositoryFormat):
2388
"""Format logic for pack structured repositories.
2390
This repository format has:
2391
- a list of packs in pack-names
2392
- packs in packs/NAME.pack
2393
- indices in indices/NAME.{iix,six,tix,rix}
2394
- knit deltas in the packs, knit indices mapped to the indices.
2395
- thunk objects to support the knits programming API.
2396
- a format marker of its own
2397
- an optional 'shared-storage' flag
2398
- an optional 'no-working-trees' flag
2402
# Set this attribute in derived classes to control the repository class
2403
# created by open and initialize.
2404
repository_class = None
2405
# Set this attribute in derived classes to control the
2406
# _commit_builder_class that the repository objects will have passed to
2407
# their constructor.
2408
_commit_builder_class = None
2409
# Set this attribute in derived clases to control the _serializer that the
2410
# repository objects will have passed to their constructor.
2412
# Packs are not confused by ghosts.
2413
supports_ghosts = True
2414
# External references are not supported in pack repositories yet.
2415
supports_external_lookups = False
2416
# Most pack formats do not use chk lookups.
2417
supports_chks = False
2418
# What index classes to use
2419
index_builder_class = None
2421
_fetch_uses_deltas = True
2424
def initialize(self, a_bzrdir, shared=False):
2425
"""Create a pack based repository.
2427
:param a_bzrdir: bzrdir to contain the new repository; must already
2429
:param shared: If true the repository will be initialized as a shared
2432
mutter('creating repository in %s.', a_bzrdir.transport.base)
2433
dirs = ['indices', 'obsolete_packs', 'packs', 'upload']
2434
builder = self.index_builder_class()
2435
files = [('pack-names', builder.finish())]
2436
utf8_files = [('format', self.get_format_string())]
2438
self._upload_blank_content(a_bzrdir, dirs, files, utf8_files, shared)
2439
return self.open(a_bzrdir=a_bzrdir, _found=True)
2441
def open(self, a_bzrdir, _found=False, _override_transport=None):
2442
"""See RepositoryFormat.open().
2444
:param _override_transport: INTERNAL USE ONLY. Allows opening the
2445
repository at a slightly different url
2446
than normal. I.e. during 'upgrade'.
2449
format = RepositoryFormat.find_format(a_bzrdir)
2450
if _override_transport is not None:
2451
repo_transport = _override_transport
2453
repo_transport = a_bzrdir.get_repository_transport(None)
2454
control_files = lockable_files.LockableFiles(repo_transport,
2455
'lock', lockdir.LockDir)
2456
return self.repository_class(_format=self,
2458
control_files=control_files,
2459
_commit_builder_class=self._commit_builder_class,
2460
_serializer=self._serializer)
2463
class RepositoryFormatKnitPack1(RepositoryFormatPack):
2464
"""A no-subtrees parameterized Pack repository.
2466
This format was introduced in 0.92.
2469
repository_class = KnitPackRepository
2470
_commit_builder_class = PackCommitBuilder
2472
def _serializer(self):
2473
return xml5.serializer_v5
2474
# What index classes to use
2475
index_builder_class = InMemoryGraphIndex
2476
index_class = GraphIndex
2478
def _get_matching_bzrdir(self):
2479
return bzrdir.format_registry.make_bzrdir('pack-0.92')
2481
def _ignore_setting_bzrdir(self, format):
2484
_matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
2486
def get_format_string(self):
2487
"""See RepositoryFormat.get_format_string()."""
2488
return "Bazaar pack repository format 1 (needs bzr 0.92)\n"
2490
def get_format_description(self):
2491
"""See RepositoryFormat.get_format_description()."""
2492
return "Packs containing knits without subtree support"
2494
def check_conversion_target(self, target_format):
2498
class RepositoryFormatKnitPack3(RepositoryFormatPack):
2499
"""A subtrees parameterized Pack repository.
2501
This repository format uses the xml7 serializer to get:
2502
- support for recording full info about the tree root
2503
- support for recording tree-references
2505
This format was introduced in 0.92.
2508
repository_class = KnitPackRepository
2509
_commit_builder_class = PackRootCommitBuilder
2510
rich_root_data = True
2511
supports_tree_reference = True
2513
def _serializer(self):
2514
return xml7.serializer_v7
2515
# What index classes to use
2516
index_builder_class = InMemoryGraphIndex
2517
index_class = GraphIndex
2519
def _get_matching_bzrdir(self):
2520
return bzrdir.format_registry.make_bzrdir(
2521
'pack-0.92-subtree')
2523
def _ignore_setting_bzrdir(self, format):
2526
_matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
2528
def check_conversion_target(self, target_format):
2529
if not target_format.rich_root_data:
2530
raise errors.BadConversionTarget(
2531
'Does not support rich root data.', target_format)
2532
if not getattr(target_format, 'supports_tree_reference', False):
2533
raise errors.BadConversionTarget(
2534
'Does not support nested trees', target_format)
2536
def get_format_string(self):
2537
"""See RepositoryFormat.get_format_string()."""
2538
return "Bazaar pack repository format 1 with subtree support (needs bzr 0.92)\n"
2540
def get_format_description(self):
2541
"""See RepositoryFormat.get_format_description()."""
2542
return "Packs containing knits with subtree support\n"
2545
class RepositoryFormatKnitPack4(RepositoryFormatPack):
2546
"""A rich-root, no subtrees parameterized Pack repository.
2548
This repository format uses the xml6 serializer to get:
2549
- support for recording full info about the tree root
2551
This format was introduced in 1.0.
2554
repository_class = KnitPackRepository
2555
_commit_builder_class = PackRootCommitBuilder
2556
rich_root_data = True
2557
supports_tree_reference = False
2559
def _serializer(self):
2560
return xml6.serializer_v6
2561
# What index classes to use
2562
index_builder_class = InMemoryGraphIndex
2563
index_class = GraphIndex
2565
def _get_matching_bzrdir(self):
2566
return bzrdir.format_registry.make_bzrdir(
2569
def _ignore_setting_bzrdir(self, format):
2572
_matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
2574
def check_conversion_target(self, target_format):
2575
if not target_format.rich_root_data:
2576
raise errors.BadConversionTarget(
2577
'Does not support rich root data.', target_format)
2579
def get_format_string(self):
2580
"""See RepositoryFormat.get_format_string()."""
2581
return ("Bazaar pack repository format 1 with rich root"
2582
" (needs bzr 1.0)\n")
2584
def get_format_description(self):
2585
"""See RepositoryFormat.get_format_description()."""
2586
return "Packs containing knits with rich root support\n"
2589
class RepositoryFormatKnitPack5(RepositoryFormatPack):
2590
"""Repository that supports external references to allow stacking.
2594
Supports external lookups, which results in non-truncated ghosts after
2595
reconcile compared to pack-0.92 formats.
2598
repository_class = KnitPackRepository
2599
_commit_builder_class = PackCommitBuilder
2600
supports_external_lookups = True
2601
# What index classes to use
2602
index_builder_class = InMemoryGraphIndex
2603
index_class = GraphIndex
2606
def _serializer(self):
2607
return xml5.serializer_v5
2609
def _get_matching_bzrdir(self):
2610
return bzrdir.format_registry.make_bzrdir('1.6')
2612
def _ignore_setting_bzrdir(self, format):
2615
_matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
2617
def get_format_string(self):
2618
"""See RepositoryFormat.get_format_string()."""
2619
return "Bazaar RepositoryFormatKnitPack5 (bzr 1.6)\n"
2621
def get_format_description(self):
2622
"""See RepositoryFormat.get_format_description()."""
2623
return "Packs 5 (adds stacking support, requires bzr 1.6)"
2625
def check_conversion_target(self, target_format):
2629
class RepositoryFormatKnitPack5RichRoot(RepositoryFormatPack):
2630
"""A repository with rich roots and stacking.
2632
New in release 1.6.1.
2634
Supports stacking on other repositories, allowing data to be accessed
2635
without being stored locally.
2638
repository_class = KnitPackRepository
2639
_commit_builder_class = PackRootCommitBuilder
2640
rich_root_data = True
2641
supports_tree_reference = False # no subtrees
2642
supports_external_lookups = True
2643
# What index classes to use
2644
index_builder_class = InMemoryGraphIndex
2645
index_class = GraphIndex
2648
def _serializer(self):
2649
return xml6.serializer_v6
2651
def _get_matching_bzrdir(self):
2652
return bzrdir.format_registry.make_bzrdir(
2655
def _ignore_setting_bzrdir(self, format):
2658
_matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
2660
def check_conversion_target(self, target_format):
2661
if not target_format.rich_root_data:
2662
raise errors.BadConversionTarget(
2663
'Does not support rich root data.', target_format)
2665
def get_format_string(self):
2666
"""See RepositoryFormat.get_format_string()."""
2667
return "Bazaar RepositoryFormatKnitPack5RichRoot (bzr 1.6.1)\n"
2669
def get_format_description(self):
2670
return "Packs 5 rich-root (adds stacking support, requires bzr 1.6.1)"
2673
class RepositoryFormatKnitPack5RichRootBroken(RepositoryFormatPack):
2674
"""A repository with rich roots and external references.
2678
Supports external lookups, which results in non-truncated ghosts after
2679
reconcile compared to pack-0.92 formats.
2681
This format was deprecated because the serializer it uses accidentally
2682
supported subtrees, when the format was not intended to. This meant that
2683
someone could accidentally fetch from an incorrect repository.
2686
repository_class = KnitPackRepository
2687
_commit_builder_class = PackRootCommitBuilder
2688
rich_root_data = True
2689
supports_tree_reference = False # no subtrees
2691
supports_external_lookups = True
2692
# What index classes to use
2693
index_builder_class = InMemoryGraphIndex
2694
index_class = GraphIndex
2697
def _serializer(self):
2698
return xml7.serializer_v7
2700
def _get_matching_bzrdir(self):
2701
matching = bzrdir.format_registry.make_bzrdir(
2703
matching.repository_format = self
2706
def _ignore_setting_bzrdir(self, format):
2709
_matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
2711
def check_conversion_target(self, target_format):
2712
if not target_format.rich_root_data:
2713
raise errors.BadConversionTarget(
2714
'Does not support rich root data.', target_format)
2716
def get_format_string(self):
2717
"""See RepositoryFormat.get_format_string()."""
2718
return "Bazaar RepositoryFormatKnitPack5RichRoot (bzr 1.6)\n"
2720
def get_format_description(self):
2721
return ("Packs 5 rich-root (adds stacking support, requires bzr 1.6)"
2725
class RepositoryFormatKnitPack6(RepositoryFormatPack):
2726
"""A repository with stacking and btree indexes,
2727
without rich roots or subtrees.
2729
This is equivalent to pack-1.6 with B+Tree indices.
2732
repository_class = KnitPackRepository
2733
_commit_builder_class = PackCommitBuilder
2734
supports_external_lookups = True
2735
# What index classes to use
2736
index_builder_class = BTreeBuilder
2737
index_class = BTreeGraphIndex
2740
def _serializer(self):
2741
return xml5.serializer_v5
2743
def _get_matching_bzrdir(self):
2744
return bzrdir.format_registry.make_bzrdir('1.9')
2746
def _ignore_setting_bzrdir(self, format):
2749
_matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
2751
def get_format_string(self):
2752
"""See RepositoryFormat.get_format_string()."""
2753
return "Bazaar RepositoryFormatKnitPack6 (bzr 1.9)\n"
2755
def get_format_description(self):
2756
"""See RepositoryFormat.get_format_description()."""
2757
return "Packs 6 (uses btree indexes, requires bzr 1.9)"
2759
def check_conversion_target(self, target_format):
2763
class RepositoryFormatKnitPack6RichRoot(RepositoryFormatPack):
2764
"""A repository with rich roots, no subtrees, stacking and btree indexes.
2766
1.6-rich-root with B+Tree indices.
2769
repository_class = KnitPackRepository
2770
_commit_builder_class = PackRootCommitBuilder
2771
rich_root_data = True
2772
supports_tree_reference = False # no subtrees
2773
supports_external_lookups = True
2774
# What index classes to use
2775
index_builder_class = BTreeBuilder
2776
index_class = BTreeGraphIndex
2779
def _serializer(self):
2780
return xml6.serializer_v6
2782
def _get_matching_bzrdir(self):
2783
return bzrdir.format_registry.make_bzrdir(
2786
def _ignore_setting_bzrdir(self, format):
2789
_matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
2791
def check_conversion_target(self, target_format):
2792
if not target_format.rich_root_data:
2793
raise errors.BadConversionTarget(
2794
'Does not support rich root data.', target_format)
2796
def get_format_string(self):
2797
"""See RepositoryFormat.get_format_string()."""
2798
return "Bazaar RepositoryFormatKnitPack6RichRoot (bzr 1.9)\n"
2800
def get_format_description(self):
2801
return "Packs 6 rich-root (uses btree indexes, requires bzr 1.9)"
2804
class RepositoryFormatPackDevelopment2Subtree(RepositoryFormatPack):
2805
"""A subtrees development repository.
2807
This format should be retained until the second release after bzr 1.7.
2809
1.6.1-subtree[as it might have been] with B+Tree indices.
2811
This is [now] retained until we have a CHK based subtree format in
2815
repository_class = KnitPackRepository
2816
_commit_builder_class = PackRootCommitBuilder
2817
rich_root_data = True
2818
supports_tree_reference = True
2819
supports_external_lookups = True
2820
# What index classes to use
2821
index_builder_class = BTreeBuilder
2822
index_class = BTreeGraphIndex
2825
def _serializer(self):
2826
return xml7.serializer_v7
2828
def _get_matching_bzrdir(self):
2829
return bzrdir.format_registry.make_bzrdir(
2830
'development-subtree')
2832
def _ignore_setting_bzrdir(self, format):
2835
_matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
2837
def check_conversion_target(self, target_format):
2838
if not target_format.rich_root_data:
2839
raise errors.BadConversionTarget(
2840
'Does not support rich root data.', target_format)
2841
if not getattr(target_format, 'supports_tree_reference', False):
2842
raise errors.BadConversionTarget(
2843
'Does not support nested trees', target_format)
2845
def get_format_string(self):
2846
"""See RepositoryFormat.get_format_string()."""
2847
return ("Bazaar development format 2 with subtree support "
2848
"(needs bzr.dev from before 1.8)\n")
2850
def get_format_description(self):
2851
"""See RepositoryFormat.get_format_description()."""
2852
return ("Development repository format, currently the same as "
2853
"1.6.1-subtree with B+Tree indices.\n")