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,
272
"""Create a ResumedPack object."""
273
ExistingPack.__init__(self, pack_transport, name, revision_index,
274
inventory_index, text_index, signature_index)
275
self.upload_transport = upload_transport
276
self.index_transport = index_transport
277
self.index_sizes = [None, None, None, None]
279
('revision', revision_index),
280
('inventory', inventory_index),
281
('text', text_index),
282
('signature', signature_index),
284
for index_type, index in indices:
285
offset = self.index_offset(index_type)
286
self.index_sizes[offset] = index._size
287
self.index_class = pack_collection._index_class
288
self._pack_collection = pack_collection
289
self._state = 'resumed'
290
# XXX: perhaps check that the .pack file exists?
292
def access_tuple(self):
293
if self._state == 'finished':
294
return Pack.access_tuple(self)
295
elif self._state == 'resumed':
296
return self.upload_transport, self.file_name()
298
raise AssertionError(self._state)
301
self.upload_transport.delete(self.file_name())
302
indices = [self.revision_index, self.inventory_index, self.text_index,
303
self.signature_index]
304
for index in indices:
305
index._transport.delete(index._name)
308
self._check_references()
309
new_name = '../packs/' + self.file_name()
310
self.upload_transport.rename(self.file_name(), new_name)
311
for index_type in ['revision', 'inventory', 'text', 'signature']:
312
old_name = self.index_name(index_type, self.name)
313
new_name = '../indices/' + old_name
314
self.upload_transport.rename(old_name, new_name)
315
self._replace_index_with_readonly(index_type)
316
self._state = 'finished'
318
def _get_external_refs(self, index):
319
return index.external_references(1)
323
"""An in memory proxy for a pack which is being created."""
325
def __init__(self, pack_collection, upload_suffix='', file_mode=None):
326
"""Create a NewPack instance.
328
:param pack_collection: A PackCollection into which this is being inserted.
329
:param upload_suffix: An optional suffix to be given to any temporary
330
files created during the pack creation. e.g '.autopack'
331
:param file_mode: Unix permissions for newly created file.
333
# The relative locations of the packs are constrained, but all are
334
# passed in because the caller has them, so as to avoid object churn.
335
index_builder_class = pack_collection._index_builder_class
336
if pack_collection.chk_index is not None:
337
chk_index = index_builder_class(reference_lists=0)
341
# Revisions: parents list, no text compression.
342
index_builder_class(reference_lists=1),
343
# Inventory: We want to map compression only, but currently the
344
# knit code hasn't been updated enough to understand that, so we
345
# have a regular 2-list index giving parents and compression
347
index_builder_class(reference_lists=2),
348
# Texts: compression and per file graph, for all fileids - so two
349
# reference lists and two elements in the key tuple.
350
index_builder_class(reference_lists=2, key_elements=2),
351
# Signatures: Just blobs to store, no compression, no parents
353
index_builder_class(reference_lists=0),
354
# CHK based storage - just blobs, no compression or parents.
357
self._pack_collection = pack_collection
358
# When we make readonly indices, we need this.
359
self.index_class = pack_collection._index_class
360
# where should the new pack be opened
361
self.upload_transport = pack_collection._upload_transport
362
# where are indices written out to
363
self.index_transport = pack_collection._index_transport
364
# where is the pack renamed to when it is finished?
365
self.pack_transport = pack_collection._pack_transport
366
# What file mode to upload the pack and indices with.
367
self._file_mode = file_mode
368
# tracks the content written to the .pack file.
369
self._hash = osutils.md5()
370
# a tuple with the length in bytes of the indices, once the pack
371
# is finalised. (rev, inv, text, sigs, chk_if_in_use)
372
self.index_sizes = None
373
# How much data to cache when writing packs. Note that this is not
374
# synchronised with reads, because it's not in the transport layer, so
375
# is not safe unless the client knows it won't be reading from the pack
377
self._cache_limit = 0
378
# the temporary pack file name.
379
self.random_name = osutils.rand_chars(20) + upload_suffix
380
# when was this pack started ?
381
self.start_time = time.time()
382
# open an output stream for the data added to the pack.
383
self.write_stream = self.upload_transport.open_write_stream(
384
self.random_name, mode=self._file_mode)
385
if 'pack' in debug.debug_flags:
386
mutter('%s: create_pack: pack stream open: %s%s t+%6.3fs',
387
time.ctime(), self.upload_transport.base, self.random_name,
388
time.time() - self.start_time)
389
# A list of byte sequences to be written to the new pack, and the
390
# aggregate size of them. Stored as a list rather than separate
391
# variables so that the _write_data closure below can update them.
392
self._buffer = [[], 0]
393
# create a callable for adding data
395
# robertc says- this is a closure rather than a method on the object
396
# so that the variables are locals, and faster than accessing object
398
def _write_data(bytes, flush=False, _buffer=self._buffer,
399
_write=self.write_stream.write, _update=self._hash.update):
400
_buffer[0].append(bytes)
401
_buffer[1] += len(bytes)
403
if _buffer[1] > self._cache_limit or flush:
404
bytes = ''.join(_buffer[0])
408
# expose this on self, for the occasion when clients want to add data.
409
self._write_data = _write_data
410
# a pack writer object to serialise pack records.
411
self._writer = pack.ContainerWriter(self._write_data)
413
# what state is the pack in? (open, finished, aborted)
417
"""Cancel creating this pack."""
418
self._state = 'aborted'
419
self.write_stream.close()
420
# Remove the temporary pack file.
421
self.upload_transport.delete(self.random_name)
422
# The indices have no state on disk.
424
def access_tuple(self):
425
"""Return a tuple (transport, name) for the pack content."""
426
if self._state == 'finished':
427
return Pack.access_tuple(self)
428
elif self._state == 'open':
429
return self.upload_transport, self.random_name
431
raise AssertionError(self._state)
433
def data_inserted(self):
434
"""True if data has been added to this pack."""
435
return bool(self.get_revision_count() or
436
self.inventory_index.key_count() or
437
self.text_index.key_count() or
438
self.signature_index.key_count() or
439
(self.chk_index is not None and self.chk_index.key_count()))
441
def finish(self, suspend=False):
442
"""Finish the new pack.
445
- finalises the content
446
- assigns a name (the md5 of the content, currently)
447
- writes out the associated indices
448
- renames the pack into place.
449
- stores the index size tuple for the pack in the index_sizes
454
self._write_data('', flush=True)
455
self.name = self._hash.hexdigest()
457
self._check_references()
459
# XXX: It'd be better to write them all to temporary names, then
460
# rename them all into place, so that the window when only some are
461
# visible is smaller. On the other hand none will be seen until
462
# they're in the names list.
463
self.index_sizes = [None, None, None, None]
464
self._write_index('revision', self.revision_index, 'revision', suspend)
465
self._write_index('inventory', self.inventory_index, 'inventory',
467
self._write_index('text', self.text_index, 'file texts', suspend)
468
self._write_index('signature', self.signature_index,
469
'revision signatures', suspend)
470
if self.chk_index is not None:
471
self.index_sizes.append(None)
472
self._write_index('chk', self.chk_index,
473
'content hash bytes', suspend)
474
self.write_stream.close()
475
# Note that this will clobber an existing pack with the same name,
476
# without checking for hash collisions. While this is undesirable this
477
# is something that can be rectified in a subsequent release. One way
478
# to rectify it may be to leave the pack at the original name, writing
479
# its pack-names entry as something like 'HASH: index-sizes
480
# temporary-name'. Allocate that and check for collisions, if it is
481
# collision free then rename it into place. If clients know this scheme
482
# they can handle missing-file errors by:
483
# - try for HASH.pack
484
# - try for temporary-name
485
# - refresh the pack-list to see if the pack is now absent
486
new_name = self.name + '.pack'
488
new_name = '../packs/' + new_name
489
self.upload_transport.rename(self.random_name, new_name)
490
self._state = 'finished'
491
if 'pack' in debug.debug_flags:
492
# XXX: size might be interesting?
493
mutter('%s: create_pack: pack finished: %s%s->%s t+%6.3fs',
494
time.ctime(), self.upload_transport.base, self.random_name,
495
new_name, time.time() - self.start_time)
498
"""Flush any current data."""
500
bytes = ''.join(self._buffer[0])
501
self.write_stream.write(bytes)
502
self._hash.update(bytes)
503
self._buffer[:] = [[], 0]
505
def _get_external_refs(self, index):
506
return index._external_references()
508
def set_write_cache_size(self, size):
509
self._cache_limit = size
511
def _write_index(self, index_type, index, label, suspend=False):
512
"""Write out an index.
514
:param index_type: The type of index to write - e.g. 'revision'.
515
:param index: The index object to serialise.
516
:param label: What label to give the index e.g. 'revision'.
518
index_name = self.index_name(index_type, self.name)
520
transport = self.upload_transport
522
transport = self.index_transport
523
self.index_sizes[self.index_offset(index_type)] = transport.put_file(
524
index_name, index.finish(), mode=self._file_mode)
525
if 'pack' in debug.debug_flags:
526
# XXX: size might be interesting?
527
mutter('%s: create_pack: wrote %s index: %s%s t+%6.3fs',
528
time.ctime(), label, self.upload_transport.base,
529
self.random_name, time.time() - self.start_time)
530
# Replace the writable index on this object with a readonly,
531
# presently unloaded index. We should alter
532
# the index layer to make its finish() error if add_node is
533
# subsequently used. RBC
534
self._replace_index_with_readonly(index_type)
537
class AggregateIndex(object):
538
"""An aggregated index for the RepositoryPackCollection.
540
AggregateIndex is reponsible for managing the PackAccess object,
541
Index-To-Pack mapping, and all indices list for a specific type of index
542
such as 'revision index'.
544
A CombinedIndex provides an index on a single key space built up
545
from several on-disk indices. The AggregateIndex builds on this
546
to provide a knit access layer, and allows having up to one writable
547
index within the collection.
549
# XXX: Probably 'can be written to' could/should be separated from 'acts
550
# like a knit index' -- mbp 20071024
552
def __init__(self, reload_func=None, flush_func=None):
553
"""Create an AggregateIndex.
555
:param reload_func: A function to call if we find we are missing an
556
index. Should have the form reload_func() => True if the list of
557
active pack files has changed.
559
self._reload_func = reload_func
560
self.index_to_pack = {}
561
self.combined_index = CombinedGraphIndex([], reload_func=reload_func)
562
self.data_access = _DirectPackAccess(self.index_to_pack,
563
reload_func=reload_func,
564
flush_func=flush_func)
565
self.add_callback = None
567
def replace_indices(self, index_to_pack, indices):
568
"""Replace the current mappings with fresh ones.
570
This should probably not be used eventually, rather incremental add and
571
removal of indices. It has been added during refactoring of existing
574
:param index_to_pack: A mapping from index objects to
575
(transport, name) tuples for the pack file data.
576
:param indices: A list of indices.
578
# refresh the revision pack map dict without replacing the instance.
579
self.index_to_pack.clear()
580
self.index_to_pack.update(index_to_pack)
581
# XXX: API break - clearly a 'replace' method would be good?
582
self.combined_index._indices[:] = indices
583
# the current add nodes callback for the current writable index if
585
self.add_callback = None
587
def add_index(self, index, pack):
588
"""Add index to the aggregate, which is an index for Pack pack.
590
Future searches on the aggregate index will seach this new index
591
before all previously inserted indices.
593
:param index: An Index for the pack.
594
:param pack: A Pack instance.
596
# expose it to the index map
597
self.index_to_pack[index] = pack.access_tuple()
598
# put it at the front of the linear index list
599
self.combined_index.insert_index(0, index)
601
def add_writable_index(self, index, pack):
602
"""Add an index which is able to have data added to it.
604
There can be at most one writable index at any time. Any
605
modifications made to the knit are put into this index.
607
:param index: An index from the pack parameter.
608
:param pack: A Pack instance.
610
if self.add_callback is not None:
611
raise AssertionError(
612
"%s already has a writable index through %s" % \
613
(self, self.add_callback))
614
# allow writing: queue writes to a new index
615
self.add_index(index, pack)
616
# Updates the index to packs mapping as a side effect,
617
self.data_access.set_writer(pack._writer, index, pack.access_tuple())
618
self.add_callback = index.add_nodes
621
"""Reset all the aggregate data to nothing."""
622
self.data_access.set_writer(None, None, (None, None))
623
self.index_to_pack.clear()
624
del self.combined_index._indices[:]
625
self.add_callback = None
627
def remove_index(self, index, pack):
628
"""Remove index from the indices used to answer queries.
630
:param index: An index from the pack parameter.
631
:param pack: A Pack instance.
633
del self.index_to_pack[index]
634
self.combined_index._indices.remove(index)
635
if (self.add_callback is not None and
636
getattr(index, 'add_nodes', None) == self.add_callback):
637
self.add_callback = None
638
self.data_access.set_writer(None, None, (None, None))
641
class Packer(object):
642
"""Create a pack from packs."""
644
def __init__(self, pack_collection, packs, suffix, revision_ids=None,
648
:param pack_collection: A RepositoryPackCollection object where the
649
new pack is being written to.
650
:param packs: The packs to combine.
651
:param suffix: The suffix to use on the temporary files for the pack.
652
:param revision_ids: Revision ids to limit the pack to.
653
:param reload_func: A function to call if a pack file/index goes
654
missing. The side effect of calling this function should be to
655
update self.packs. See also AggregateIndex
659
self.revision_ids = revision_ids
660
# The pack object we are creating.
662
self._pack_collection = pack_collection
663
self._reload_func = reload_func
664
# The index layer keys for the revisions being copied. None for 'all
666
self._revision_keys = None
667
# What text keys to copy. None for 'all texts'. This is set by
668
# _copy_inventory_texts
669
self._text_filter = None
672
def _extra_init(self):
673
"""A template hook to allow extending the constructor trivially."""
675
def _pack_map_and_index_list(self, index_attribute):
676
"""Convert a list of packs to an index pack map and index list.
678
:param index_attribute: The attribute that the desired index is found
680
:return: A tuple (map, list) where map contains the dict from
681
index:pack_tuple, and list contains the indices in the preferred
686
for pack_obj in self.packs:
687
index = getattr(pack_obj, index_attribute)
688
indices.append(index)
689
pack_map[index] = pack_obj
690
return pack_map, indices
692
def _index_contents(self, indices, key_filter=None):
693
"""Get an iterable of the index contents from a pack_map.
695
:param indices: The list of indices to query
696
:param key_filter: An optional filter to limit the keys returned.
698
all_index = CombinedGraphIndex(indices)
699
if key_filter is None:
700
return all_index.iter_all_entries()
702
return all_index.iter_entries(key_filter)
704
def pack(self, pb=None):
705
"""Create a new pack by reading data from other packs.
707
This does little more than a bulk copy of data. One key difference
708
is that data with the same item key across multiple packs is elided
709
from the output. The new pack is written into the current pack store
710
along with its indices, and the name added to the pack names. The
711
source packs are not altered and are not required to be in the current
714
:param pb: An optional progress bar to use. A nested bar is created if
716
:return: A Pack object, or None if nothing was copied.
718
# open a pack - using the same name as the last temporary file
719
# - which has already been flushed, so its safe.
720
# XXX: - duplicate code warning with start_write_group; fix before
721
# considering 'done'.
722
if self._pack_collection._new_pack is not None:
723
raise errors.BzrError('call to %s.pack() while another pack is'
725
% (self.__class__.__name__,))
726
if self.revision_ids is not None:
727
if len(self.revision_ids) == 0:
728
# silly fetch request.
731
self.revision_ids = frozenset(self.revision_ids)
732
self.revision_keys = frozenset((revid,) for revid in
735
self.pb = ui.ui_factory.nested_progress_bar()
739
return self._create_pack_from_packs()
745
"""Open a pack for the pack we are creating."""
746
new_pack = self._pack_collection.pack_factory(self._pack_collection,
747
upload_suffix=self.suffix,
748
file_mode=self._pack_collection.repo.bzrdir._get_file_mode())
749
# We know that we will process all nodes in order, and don't need to
750
# query, so don't combine any indices spilled to disk until we are done
751
new_pack.revision_index.set_optimize(combine_backing_indices=False)
752
new_pack.inventory_index.set_optimize(combine_backing_indices=False)
753
new_pack.text_index.set_optimize(combine_backing_indices=False)
754
new_pack.signature_index.set_optimize(combine_backing_indices=False)
757
def _update_pack_order(self, entries, index_to_pack_map):
758
"""Determine how we want our packs to be ordered.
760
This changes the sort order of the self.packs list so that packs unused
761
by 'entries' will be at the end of the list, so that future requests
762
can avoid probing them. Used packs will be at the front of the
763
self.packs list, in the order of their first use in 'entries'.
765
:param entries: A list of (index, ...) tuples
766
:param index_to_pack_map: A mapping from index objects to pack objects.
770
for entry in entries:
772
if index not in seen_indexes:
773
packs.append(index_to_pack_map[index])
774
seen_indexes.add(index)
775
if len(packs) == len(self.packs):
776
if 'pack' in debug.debug_flags:
777
mutter('Not changing pack list, all packs used.')
779
seen_packs = set(packs)
780
for pack in self.packs:
781
if pack not in seen_packs:
784
if 'pack' in debug.debug_flags:
785
old_names = [p.access_tuple()[1] for p in self.packs]
786
new_names = [p.access_tuple()[1] for p in packs]
787
mutter('Reordering packs\nfrom: %s\n to: %s',
788
old_names, new_names)
791
def _copy_revision_texts(self):
792
"""Copy revision data to the new pack."""
794
if self.revision_ids:
795
revision_keys = [(revision_id,) for revision_id in self.revision_ids]
798
# select revision keys
799
revision_index_map, revision_indices = self._pack_map_and_index_list(
801
revision_nodes = self._index_contents(revision_indices, revision_keys)
802
revision_nodes = list(revision_nodes)
803
self._update_pack_order(revision_nodes, revision_index_map)
804
# copy revision keys and adjust values
805
self.pb.update("Copying revision texts", 1)
806
total_items, readv_group_iter = self._revision_node_readv(revision_nodes)
807
list(self._copy_nodes_graph(revision_index_map, self.new_pack._writer,
808
self.new_pack.revision_index, readv_group_iter, total_items))
809
if 'pack' in debug.debug_flags:
810
mutter('%s: create_pack: revisions copied: %s%s %d items t+%6.3fs',
811
time.ctime(), self._pack_collection._upload_transport.base,
812
self.new_pack.random_name,
813
self.new_pack.revision_index.key_count(),
814
time.time() - self.new_pack.start_time)
815
self._revision_keys = revision_keys
817
def _copy_inventory_texts(self):
818
"""Copy the inventory texts to the new pack.
820
self._revision_keys is used to determine what inventories to copy.
822
Sets self._text_filter appropriately.
824
# select inventory keys
825
inv_keys = self._revision_keys # currently the same keyspace, and note that
826
# querying for keys here could introduce a bug where an inventory item
827
# is missed, so do not change it to query separately without cross
828
# checking like the text key check below.
829
inventory_index_map, inventory_indices = self._pack_map_and_index_list(
831
inv_nodes = self._index_contents(inventory_indices, inv_keys)
832
# copy inventory keys and adjust values
833
# XXX: Should be a helper function to allow different inv representation
835
self.pb.update("Copying inventory texts", 2)
836
total_items, readv_group_iter = self._least_readv_node_readv(inv_nodes)
837
# Only grab the output lines if we will be processing them
838
output_lines = bool(self.revision_ids)
839
inv_lines = self._copy_nodes_graph(inventory_index_map,
840
self.new_pack._writer, self.new_pack.inventory_index,
841
readv_group_iter, total_items, output_lines=output_lines)
842
if self.revision_ids:
843
self._process_inventory_lines(inv_lines)
845
# eat the iterator to cause it to execute.
847
self._text_filter = None
848
if 'pack' in debug.debug_flags:
849
mutter('%s: create_pack: inventories copied: %s%s %d items t+%6.3fs',
850
time.ctime(), self._pack_collection._upload_transport.base,
851
self.new_pack.random_name,
852
self.new_pack.inventory_index.key_count(),
853
time.time() - self.new_pack.start_time)
855
def _copy_text_texts(self):
857
text_index_map, text_nodes = self._get_text_nodes()
858
if self._text_filter is not None:
859
# We could return the keys copied as part of the return value from
860
# _copy_nodes_graph but this doesn't work all that well with the
861
# need to get line output too, so we check separately, and as we're
862
# going to buffer everything anyway, we check beforehand, which
863
# saves reading knit data over the wire when we know there are
865
text_nodes = set(text_nodes)
866
present_text_keys = set(_node[1] for _node in text_nodes)
867
missing_text_keys = set(self._text_filter) - present_text_keys
868
if missing_text_keys:
869
# TODO: raise a specific error that can handle many missing
871
mutter("missing keys during fetch: %r", missing_text_keys)
872
a_missing_key = missing_text_keys.pop()
873
raise errors.RevisionNotPresent(a_missing_key[1],
875
# copy text keys and adjust values
876
self.pb.update("Copying content texts", 3)
877
total_items, readv_group_iter = self._least_readv_node_readv(text_nodes)
878
list(self._copy_nodes_graph(text_index_map, self.new_pack._writer,
879
self.new_pack.text_index, readv_group_iter, total_items))
880
self._log_copied_texts()
882
def _create_pack_from_packs(self):
883
self.pb.update("Opening pack", 0, 5)
884
self.new_pack = self.open_pack()
885
new_pack = self.new_pack
886
# buffer data - we won't be reading-back during the pack creation and
887
# this makes a significant difference on sftp pushes.
888
new_pack.set_write_cache_size(1024*1024)
889
if 'pack' in debug.debug_flags:
890
plain_pack_list = ['%s%s' % (a_pack.pack_transport.base, a_pack.name)
891
for a_pack in self.packs]
892
if self.revision_ids is not None:
893
rev_count = len(self.revision_ids)
896
mutter('%s: create_pack: creating pack from source packs: '
897
'%s%s %s revisions wanted %s t=0',
898
time.ctime(), self._pack_collection._upload_transport.base, new_pack.random_name,
899
plain_pack_list, rev_count)
900
self._copy_revision_texts()
901
self._copy_inventory_texts()
902
self._copy_text_texts()
903
# select signature keys
904
signature_filter = self._revision_keys # same keyspace
905
signature_index_map, signature_indices = self._pack_map_and_index_list(
907
signature_nodes = self._index_contents(signature_indices,
909
# copy signature keys and adjust values
910
self.pb.update("Copying signature texts", 4)
911
self._copy_nodes(signature_nodes, signature_index_map, new_pack._writer,
912
new_pack.signature_index)
913
if 'pack' in debug.debug_flags:
914
mutter('%s: create_pack: revision signatures copied: %s%s %d items t+%6.3fs',
915
time.ctime(), self._pack_collection._upload_transport.base, new_pack.random_name,
916
new_pack.signature_index.key_count(),
917
time.time() - new_pack.start_time)
919
# NB XXX: how to check CHK references are present? perhaps by yielding
920
# the items? How should that interact with stacked repos?
921
if new_pack.chk_index is not None:
923
if 'pack' in debug.debug_flags:
924
mutter('%s: create_pack: chk content copied: %s%s %d items t+%6.3fs',
925
time.ctime(), self._pack_collection._upload_transport.base,
926
new_pack.random_name,
927
new_pack.chk_index.key_count(),
928
time.time() - new_pack.start_time)
929
new_pack._check_references()
930
if not self._use_pack(new_pack):
933
self.pb.update("Finishing pack", 5)
935
self._pack_collection.allocate(new_pack)
938
def _copy_chks(self, refs=None):
939
# XXX: Todo, recursive follow-pointers facility when fetching some
941
chk_index_map, chk_indices = self._pack_map_and_index_list(
943
chk_nodes = self._index_contents(chk_indices, refs)
945
# TODO: This isn't strictly tasteful as we are accessing some private
946
# variables (_serializer). Perhaps a better way would be to have
947
# Repository._deserialise_chk_node()
948
search_key_func = chk_map.search_key_registry.get(
949
self._pack_collection.repo._serializer.search_key_name)
950
def accumlate_refs(lines):
951
# XXX: move to a generic location
953
bytes = ''.join(lines)
954
node = chk_map._deserialise(bytes, ("unknown",), search_key_func)
955
new_refs.update(node.refs())
956
self._copy_nodes(chk_nodes, chk_index_map, self.new_pack._writer,
957
self.new_pack.chk_index, output_lines=accumlate_refs)
960
def _copy_nodes(self, nodes, index_map, writer, write_index,
962
"""Copy knit nodes between packs with no graph references.
964
:param output_lines: Output full texts of copied items.
966
pb = ui.ui_factory.nested_progress_bar()
968
return self._do_copy_nodes(nodes, index_map, writer,
969
write_index, pb, output_lines=output_lines)
973
def _do_copy_nodes(self, nodes, index_map, writer, write_index, pb,
975
# for record verification
976
knit = KnitVersionedFiles(None, None)
977
# plan a readv on each source pack:
979
nodes = sorted(nodes)
980
# how to map this into knit.py - or knit.py into this?
981
# we don't want the typical knit logic, we want grouping by pack
982
# at this point - perhaps a helper library for the following code
983
# duplication points?
985
for index, key, value in nodes:
986
if index not in request_groups:
987
request_groups[index] = []
988
request_groups[index].append((key, value))
990
pb.update("Copied record", record_index, len(nodes))
991
for index, items in request_groups.iteritems():
992
pack_readv_requests = []
993
for key, value in items:
994
# ---- KnitGraphIndex.get_position
995
bits = value[1:].split(' ')
996
offset, length = int(bits[0]), int(bits[1])
997
pack_readv_requests.append((offset, length, (key, value[0])))
998
# linear scan up the pack
999
pack_readv_requests.sort()
1001
pack_obj = index_map[index]
1002
transport, path = pack_obj.access_tuple()
1004
reader = pack.make_readv_reader(transport, path,
1005
[offset[0:2] for offset in pack_readv_requests])
1006
except errors.NoSuchFile:
1007
if self._reload_func is not None:
1010
for (names, read_func), (_1, _2, (key, eol_flag)) in \
1011
izip(reader.iter_records(), pack_readv_requests):
1012
raw_data = read_func(None)
1013
# check the header only
1014
if output_lines is not None:
1015
output_lines(knit._parse_record(key[-1], raw_data)[0])
1017
df, _ = knit._parse_record_header(key, raw_data)
1019
pos, size = writer.add_bytes_record(raw_data, names)
1020
write_index.add_node(key, eol_flag + "%d %d" % (pos, size))
1021
pb.update("Copied record", record_index)
1024
def _copy_nodes_graph(self, index_map, writer, write_index,
1025
readv_group_iter, total_items, output_lines=False):
1026
"""Copy knit nodes between packs.
1028
:param output_lines: Return lines present in the copied data as
1029
an iterator of line,version_id.
1031
pb = ui.ui_factory.nested_progress_bar()
1033
for result in self._do_copy_nodes_graph(index_map, writer,
1034
write_index, output_lines, pb, readv_group_iter, total_items):
1037
# Python 2.4 does not permit try:finally: in a generator.
1043
def _do_copy_nodes_graph(self, index_map, writer, write_index,
1044
output_lines, pb, readv_group_iter, total_items):
1045
# for record verification
1046
knit = KnitVersionedFiles(None, None)
1047
# for line extraction when requested (inventories only)
1049
factory = KnitPlainFactory()
1051
pb.update("Copied record", record_index, total_items)
1052
for index, readv_vector, node_vector in readv_group_iter:
1054
pack_obj = index_map[index]
1055
transport, path = pack_obj.access_tuple()
1057
reader = pack.make_readv_reader(transport, path, readv_vector)
1058
except errors.NoSuchFile:
1059
if self._reload_func is not None:
1062
for (names, read_func), (key, eol_flag, references) in \
1063
izip(reader.iter_records(), node_vector):
1064
raw_data = read_func(None)
1066
# read the entire thing
1067
content, _ = knit._parse_record(key[-1], raw_data)
1068
if len(references[-1]) == 0:
1069
line_iterator = factory.get_fulltext_content(content)
1071
line_iterator = factory.get_linedelta_content(content)
1072
for line in line_iterator:
1075
# check the header only
1076
df, _ = knit._parse_record_header(key, raw_data)
1078
pos, size = writer.add_bytes_record(raw_data, names)
1079
write_index.add_node(key, eol_flag + "%d %d" % (pos, size), references)
1080
pb.update("Copied record", record_index)
1083
def _get_text_nodes(self):
1084
text_index_map, text_indices = self._pack_map_and_index_list(
1086
return text_index_map, self._index_contents(text_indices,
1089
def _least_readv_node_readv(self, nodes):
1090
"""Generate request groups for nodes using the least readv's.
1092
:param nodes: An iterable of graph index nodes.
1093
:return: Total node count and an iterator of the data needed to perform
1094
readvs to obtain the data for nodes. Each item yielded by the
1095
iterator is a tuple with:
1096
index, readv_vector, node_vector. readv_vector is a list ready to
1097
hand to the transport readv method, and node_vector is a list of
1098
(key, eol_flag, references) for the the node retrieved by the
1099
matching readv_vector.
1101
# group by pack so we do one readv per pack
1102
nodes = sorted(nodes)
1105
for index, key, value, references in nodes:
1106
if index not in request_groups:
1107
request_groups[index] = []
1108
request_groups[index].append((key, value, references))
1110
for index, items in request_groups.iteritems():
1111
pack_readv_requests = []
1112
for key, value, references in items:
1113
# ---- KnitGraphIndex.get_position
1114
bits = value[1:].split(' ')
1115
offset, length = int(bits[0]), int(bits[1])
1116
pack_readv_requests.append(
1117
((offset, length), (key, value[0], references)))
1118
# linear scan up the pack to maximum range combining.
1119
pack_readv_requests.sort()
1120
# split out the readv and the node data.
1121
pack_readv = [readv for readv, node in pack_readv_requests]
1122
node_vector = [node for readv, node in pack_readv_requests]
1123
result.append((index, pack_readv, node_vector))
1124
return total, result
1126
def _log_copied_texts(self):
1127
if 'pack' in debug.debug_flags:
1128
mutter('%s: create_pack: file texts copied: %s%s %d items t+%6.3fs',
1129
time.ctime(), self._pack_collection._upload_transport.base,
1130
self.new_pack.random_name,
1131
self.new_pack.text_index.key_count(),
1132
time.time() - self.new_pack.start_time)
1134
def _process_inventory_lines(self, inv_lines):
1135
"""Use up the inv_lines generator and setup a text key filter."""
1136
repo = self._pack_collection.repo
1137
fileid_revisions = repo._find_file_ids_from_xml_inventory_lines(
1138
inv_lines, self.revision_keys)
1140
for fileid, file_revids in fileid_revisions.iteritems():
1141
text_filter.extend([(fileid, file_revid) for file_revid in file_revids])
1142
self._text_filter = text_filter
1144
def _revision_node_readv(self, revision_nodes):
1145
"""Return the total revisions and the readv's to issue.
1147
:param revision_nodes: The revision index contents for the packs being
1148
incorporated into the new pack.
1149
:return: As per _least_readv_node_readv.
1151
return self._least_readv_node_readv(revision_nodes)
1153
def _use_pack(self, new_pack):
1154
"""Return True if new_pack should be used.
1156
:param new_pack: The pack that has just been created.
1157
:return: True if the pack should be used.
1159
return new_pack.data_inserted()
1162
class OptimisingPacker(Packer):
1163
"""A packer which spends more time to create better disk layouts."""
1165
def _revision_node_readv(self, revision_nodes):
1166
"""Return the total revisions and the readv's to issue.
1168
This sort places revisions in topological order with the ancestors
1171
:param revision_nodes: The revision index contents for the packs being
1172
incorporated into the new pack.
1173
:return: As per _least_readv_node_readv.
1175
# build an ancestors dict
1178
for index, key, value, references in revision_nodes:
1179
ancestors[key] = references[0]
1180
by_key[key] = (index, value, references)
1181
order = tsort.topo_sort(ancestors)
1183
# Single IO is pathological, but it will work as a starting point.
1185
for key in reversed(order):
1186
index, value, references = by_key[key]
1187
# ---- KnitGraphIndex.get_position
1188
bits = value[1:].split(' ')
1189
offset, length = int(bits[0]), int(bits[1])
1191
(index, [(offset, length)], [(key, value[0], references)]))
1192
# TODO: combine requests in the same index that are in ascending order.
1193
return total, requests
1195
def open_pack(self):
1196
"""Open a pack for the pack we are creating."""
1197
new_pack = super(OptimisingPacker, self).open_pack()
1198
# Turn on the optimization flags for all the index builders.
1199
new_pack.revision_index.set_optimize(for_size=True)
1200
new_pack.inventory_index.set_optimize(for_size=True)
1201
new_pack.text_index.set_optimize(for_size=True)
1202
new_pack.signature_index.set_optimize(for_size=True)
1206
class ReconcilePacker(Packer):
1207
"""A packer which regenerates indices etc as it copies.
1209
This is used by ``bzr reconcile`` to cause parent text pointers to be
1213
def _extra_init(self):
1214
self._data_changed = False
1216
def _process_inventory_lines(self, inv_lines):
1217
"""Generate a text key reference map rather for reconciling with."""
1218
repo = self._pack_collection.repo
1219
refs = repo._find_text_key_references_from_xml_inventory_lines(
1221
self._text_refs = refs
1222
# during reconcile we:
1223
# - convert unreferenced texts to full texts
1224
# - correct texts which reference a text not copied to be full texts
1225
# - copy all others as-is but with corrected parents.
1226
# - so at this point we don't know enough to decide what becomes a full
1228
self._text_filter = None
1230
def _copy_text_texts(self):
1231
"""generate what texts we should have and then copy."""
1232
self.pb.update("Copying content texts", 3)
1233
# we have three major tasks here:
1234
# 1) generate the ideal index
1235
repo = self._pack_collection.repo
1236
ancestors = dict([(key[0], tuple(ref[0] for ref in refs[0])) for
1237
_1, key, _2, refs in
1238
self.new_pack.revision_index.iter_all_entries()])
1239
ideal_index = repo._generate_text_key_index(self._text_refs, ancestors)
1240
# 2) generate a text_nodes list that contains all the deltas that can
1241
# be used as-is, with corrected parents.
1244
discarded_nodes = []
1245
NULL_REVISION = _mod_revision.NULL_REVISION
1246
text_index_map, text_nodes = self._get_text_nodes()
1247
for node in text_nodes:
1253
ideal_parents = tuple(ideal_index[node[1]])
1255
discarded_nodes.append(node)
1256
self._data_changed = True
1258
if ideal_parents == (NULL_REVISION,):
1260
if ideal_parents == node[3][0]:
1262
ok_nodes.append(node)
1263
elif ideal_parents[0:1] == node[3][0][0:1]:
1264
# the left most parent is the same, or there are no parents
1265
# today. Either way, we can preserve the representation as
1266
# long as we change the refs to be inserted.
1267
self._data_changed = True
1268
ok_nodes.append((node[0], node[1], node[2],
1269
(ideal_parents, node[3][1])))
1270
self._data_changed = True
1272
# Reinsert this text completely
1273
bad_texts.append((node[1], ideal_parents))
1274
self._data_changed = True
1275
# we're finished with some data.
1278
# 3) bulk copy the ok data
1279
total_items, readv_group_iter = self._least_readv_node_readv(ok_nodes)
1280
list(self._copy_nodes_graph(text_index_map, self.new_pack._writer,
1281
self.new_pack.text_index, readv_group_iter, total_items))
1282
# 4) adhoc copy all the other texts.
1283
# We have to topologically insert all texts otherwise we can fail to
1284
# reconcile when parts of a single delta chain are preserved intact,
1285
# and other parts are not. E.g. Discarded->d1->d2->d3. d1 will be
1286
# reinserted, and if d3 has incorrect parents it will also be
1287
# reinserted. If we insert d3 first, d2 is present (as it was bulk
1288
# copied), so we will try to delta, but d2 is not currently able to be
1289
# extracted because it's basis d1 is not present. Topologically sorting
1290
# addresses this. The following generates a sort for all the texts that
1291
# are being inserted without having to reference the entire text key
1292
# space (we only topo sort the revisions, which is smaller).
1293
topo_order = tsort.topo_sort(ancestors)
1294
rev_order = dict(zip(topo_order, range(len(topo_order))))
1295
bad_texts.sort(key=lambda key:rev_order[key[0][1]])
1296
transaction = repo.get_transaction()
1297
file_id_index = GraphIndexPrefixAdapter(
1298
self.new_pack.text_index,
1300
add_nodes_callback=self.new_pack.text_index.add_nodes)
1301
data_access = _DirectPackAccess(
1302
{self.new_pack.text_index:self.new_pack.access_tuple()})
1303
data_access.set_writer(self.new_pack._writer, self.new_pack.text_index,
1304
self.new_pack.access_tuple())
1305
output_texts = KnitVersionedFiles(
1306
_KnitGraphIndex(self.new_pack.text_index,
1307
add_callback=self.new_pack.text_index.add_nodes,
1308
deltas=True, parents=True, is_locked=repo.is_locked),
1309
data_access=data_access, max_delta_chain=200)
1310
for key, parent_keys in bad_texts:
1311
# We refer to the new pack to delta data being output.
1312
# A possible improvement would be to catch errors on short reads
1313
# and only flush then.
1314
self.new_pack.flush()
1316
for parent_key in parent_keys:
1317
if parent_key[0] != key[0]:
1318
# Graph parents must match the fileid
1319
raise errors.BzrError('Mismatched key parent %r:%r' %
1321
parents.append(parent_key[1])
1322
text_lines = osutils.split_lines(repo.texts.get_record_stream(
1323
[key], 'unordered', True).next().get_bytes_as('fulltext'))
1324
output_texts.add_lines(key, parent_keys, text_lines,
1325
random_id=True, check_content=False)
1326
# 5) check that nothing inserted has a reference outside the keyspace.
1327
missing_text_keys = self.new_pack.text_index._external_references()
1328
if missing_text_keys:
1329
raise errors.BzrCheckError('Reference to missing compression parents %r'
1330
% (missing_text_keys,))
1331
self._log_copied_texts()
1333
def _use_pack(self, new_pack):
1334
"""Override _use_pack to check for reconcile having changed content."""
1335
# XXX: we might be better checking this at the copy time.
1336
original_inventory_keys = set()
1337
inv_index = self._pack_collection.inventory_index.combined_index
1338
for entry in inv_index.iter_all_entries():
1339
original_inventory_keys.add(entry[1])
1340
new_inventory_keys = set()
1341
for entry in new_pack.inventory_index.iter_all_entries():
1342
new_inventory_keys.add(entry[1])
1343
if new_inventory_keys != original_inventory_keys:
1344
self._data_changed = True
1345
return new_pack.data_inserted() and self._data_changed
1348
class RepositoryPackCollection(object):
1349
"""Management of packs within a repository.
1351
:ivar _names: map of {pack_name: (index_size,)}
1354
pack_factory = NewPack
1356
def __init__(self, repo, transport, index_transport, upload_transport,
1357
pack_transport, index_builder_class, index_class,
1359
"""Create a new RepositoryPackCollection.
1361
:param transport: Addresses the repository base directory
1362
(typically .bzr/repository/).
1363
:param index_transport: Addresses the directory containing indices.
1364
:param upload_transport: Addresses the directory into which packs are written
1365
while they're being created.
1366
:param pack_transport: Addresses the directory of existing complete packs.
1367
:param index_builder_class: The index builder class to use.
1368
:param index_class: The index class to use.
1369
:param use_chk_index: Whether to setup and manage a CHK index.
1371
# XXX: This should call self.reset()
1373
self.transport = transport
1374
self._index_transport = index_transport
1375
self._upload_transport = upload_transport
1376
self._pack_transport = pack_transport
1377
self._index_builder_class = index_builder_class
1378
self._index_class = index_class
1379
self._suffix_offsets = {'.rix': 0, '.iix': 1, '.tix': 2, '.six': 3,
1384
self._packs_by_name = {}
1385
# the previous pack-names content
1386
self._packs_at_load = None
1387
# when a pack is being created by this object, the state of that pack.
1388
self._new_pack = None
1389
# aggregated revision index data
1390
flush = self._flush_new_pack
1391
self.revision_index = AggregateIndex(self.reload_pack_names, flush)
1392
self.inventory_index = AggregateIndex(self.reload_pack_names, flush)
1393
self.text_index = AggregateIndex(self.reload_pack_names, flush)
1394
self.signature_index = AggregateIndex(self.reload_pack_names, flush)
1396
self.chk_index = AggregateIndex(self.reload_pack_names, flush)
1398
# used to determine if we're using a chk_index elsewhere.
1399
self.chk_index = None
1401
self._resumed_packs = []
1403
def add_pack_to_memory(self, pack):
1404
"""Make a Pack object available to the repository to satisfy queries.
1406
:param pack: A Pack object.
1408
if pack.name in self._packs_by_name:
1409
raise AssertionError(
1410
'pack %s already in _packs_by_name' % (pack.name,))
1411
self.packs.append(pack)
1412
self._packs_by_name[pack.name] = pack
1413
self.revision_index.add_index(pack.revision_index, pack)
1414
self.inventory_index.add_index(pack.inventory_index, pack)
1415
self.text_index.add_index(pack.text_index, pack)
1416
self.signature_index.add_index(pack.signature_index, pack)
1417
if self.chk_index is not None:
1418
self.chk_index.add_index(pack.chk_index, pack)
1420
def all_packs(self):
1421
"""Return a list of all the Pack objects this repository has.
1423
Note that an in-progress pack being created is not returned.
1425
:return: A list of Pack objects for all the packs in the repository.
1428
for name in self.names():
1429
result.append(self.get_pack_by_name(name))
1433
"""Pack the pack collection incrementally.
1435
This will not attempt global reorganisation or recompression,
1436
rather it will just ensure that the total number of packs does
1437
not grow without bound. It uses the _max_pack_count method to
1438
determine if autopacking is needed, and the pack_distribution
1439
method to determine the number of revisions in each pack.
1441
If autopacking takes place then the packs name collection will have
1442
been flushed to disk - packing requires updating the name collection
1443
in synchronisation with certain steps. Otherwise the names collection
1446
:return: True if packing took place.
1450
return self._do_autopack()
1451
except errors.RetryAutopack, e:
1452
# If we get a RetryAutopack exception, we should abort the
1453
# current action, and retry.
1456
def _do_autopack(self):
1457
# XXX: Should not be needed when the management of indices is sane.
1458
total_revisions = self.revision_index.combined_index.key_count()
1459
total_packs = len(self._names)
1460
if self._max_pack_count(total_revisions) >= total_packs:
1462
# determine which packs need changing
1463
pack_distribution = self.pack_distribution(total_revisions)
1465
for pack in self.all_packs():
1466
revision_count = pack.get_revision_count()
1467
if revision_count == 0:
1468
# revision less packs are not generated by normal operation,
1469
# only by operations like sign-my-commits, and thus will not
1470
# tend to grow rapdily or without bound like commit containing
1471
# packs do - leave them alone as packing them really should
1472
# group their data with the relevant commit, and that may
1473
# involve rewriting ancient history - which autopack tries to
1474
# avoid. Alternatively we could not group the data but treat
1475
# each of these as having a single revision, and thus add
1476
# one revision for each to the total revision count, to get
1477
# a matching distribution.
1479
existing_packs.append((revision_count, pack))
1480
pack_operations = self.plan_autopack_combinations(
1481
existing_packs, pack_distribution)
1482
num_new_packs = len(pack_operations)
1483
num_old_packs = sum([len(po[1]) for po in pack_operations])
1484
num_revs_affected = sum([po[0] for po in pack_operations])
1485
mutter('Auto-packing repository %s, which has %d pack files, '
1486
'containing %d revisions. Packing %d files into %d affecting %d'
1487
' revisions', self, total_packs, total_revisions, num_old_packs,
1488
num_new_packs, num_revs_affected)
1489
self._execute_pack_operations(pack_operations,
1490
reload_func=self._restart_autopack)
1491
mutter('Auto-packing repository %s completed', self)
1494
def _execute_pack_operations(self, pack_operations, _packer_class=Packer,
1496
"""Execute a series of pack operations.
1498
:param pack_operations: A list of [revision_count, packs_to_combine].
1499
:param _packer_class: The class of packer to use (default: Packer).
1502
for revision_count, packs in pack_operations:
1503
# we may have no-ops from the setup logic
1506
packer = _packer_class(self, packs, '.autopack',
1507
reload_func=reload_func)
1510
except errors.RetryWithNewPacks:
1511
# An exception is propagating out of this context, make sure
1512
# this packer has cleaned up. Packer() doesn't set its new_pack
1513
# state into the RepositoryPackCollection object, so we only
1514
# have access to it directly here.
1515
if packer.new_pack is not None:
1516
packer.new_pack.abort()
1519
self._remove_pack_from_memory(pack)
1520
# record the newly available packs and stop advertising the old
1522
self._save_pack_names(clear_obsolete_packs=True)
1523
# Move the old packs out of the way now they are no longer referenced.
1524
for revision_count, packs in pack_operations:
1525
self._obsolete_packs(packs)
1527
def _flush_new_pack(self):
1528
if self._new_pack is not None:
1529
self._new_pack.flush()
1531
def lock_names(self):
1532
"""Acquire the mutex around the pack-names index.
1534
This cannot be used in the middle of a read-only transaction on the
1537
self.repo.control_files.lock_write()
1539
def _already_packed(self):
1540
"""Is the collection already packed?"""
1541
return len(self._names) < 2
1544
"""Pack the pack collection totally."""
1545
self.ensure_loaded()
1546
total_packs = len(self._names)
1547
if self._already_packed():
1548
# This is arguably wrong because we might not be optimal, but for
1549
# now lets leave it in. (e.g. reconcile -> one pack. But not
1552
total_revisions = self.revision_index.combined_index.key_count()
1553
# XXX: the following may want to be a class, to pack with a given
1555
mutter('Packing repository %s, which has %d pack files, '
1556
'containing %d revisions into 1 packs.', self, total_packs,
1558
# determine which packs need changing
1559
pack_distribution = [1]
1560
pack_operations = [[0, []]]
1561
for pack in self.all_packs():
1562
pack_operations[-1][0] += pack.get_revision_count()
1563
pack_operations[-1][1].append(pack)
1564
self._execute_pack_operations(pack_operations, OptimisingPacker)
1566
def plan_autopack_combinations(self, existing_packs, pack_distribution):
1567
"""Plan a pack operation.
1569
:param existing_packs: The packs to pack. (A list of (revcount, Pack)
1571
:param pack_distribution: A list with the number of revisions desired
1574
if len(existing_packs) <= len(pack_distribution):
1576
existing_packs.sort(reverse=True)
1577
pack_operations = [[0, []]]
1578
# plan out what packs to keep, and what to reorganise
1579
while len(existing_packs):
1580
# take the largest pack, and if its less than the head of the
1581
# distribution chart we will include its contents in the new pack
1582
# for that position. If its larger, we remove its size from the
1583
# distribution chart
1584
next_pack_rev_count, next_pack = existing_packs.pop(0)
1585
if next_pack_rev_count >= pack_distribution[0]:
1586
# this is already packed 'better' than this, so we can
1587
# not waste time packing it.
1588
while next_pack_rev_count > 0:
1589
next_pack_rev_count -= pack_distribution[0]
1590
if next_pack_rev_count >= 0:
1592
del pack_distribution[0]
1594
# didn't use that entire bucket up
1595
pack_distribution[0] = -next_pack_rev_count
1597
# add the revisions we're going to add to the next output pack
1598
pack_operations[-1][0] += next_pack_rev_count
1599
# allocate this pack to the next pack sub operation
1600
pack_operations[-1][1].append(next_pack)
1601
if pack_operations[-1][0] >= pack_distribution[0]:
1602
# this pack is used up, shift left.
1603
del pack_distribution[0]
1604
pack_operations.append([0, []])
1605
# Now that we know which pack files we want to move, shove them all
1606
# into a single pack file.
1608
final_pack_list = []
1609
for num_revs, pack_files in pack_operations:
1610
final_rev_count += num_revs
1611
final_pack_list.extend(pack_files)
1612
if len(final_pack_list) == 1:
1613
raise AssertionError('We somehow generated an autopack with a'
1614
' single pack file being moved.')
1616
return [[final_rev_count, final_pack_list]]
1618
def ensure_loaded(self):
1619
"""Ensure we have read names from disk.
1621
:return: True if the disk names had not been previously read.
1623
# NB: if you see an assertion error here, its probably access against
1624
# an unlocked repo. Naughty.
1625
if not self.repo.is_locked():
1626
raise errors.ObjectNotLocked(self.repo)
1627
if self._names is None:
1629
self._packs_at_load = set()
1630
for index, key, value in self._iter_disk_pack_index():
1632
self._names[name] = self._parse_index_sizes(value)
1633
self._packs_at_load.add((key, value))
1637
# populate all the metadata.
1641
def _parse_index_sizes(self, value):
1642
"""Parse a string of index sizes."""
1643
return tuple([int(digits) for digits in value.split(' ')])
1645
def get_pack_by_name(self, name):
1646
"""Get a Pack object by name.
1648
:param name: The name of the pack - e.g. '123456'
1649
:return: A Pack object.
1652
return self._packs_by_name[name]
1654
rev_index = self._make_index(name, '.rix')
1655
inv_index = self._make_index(name, '.iix')
1656
txt_index = self._make_index(name, '.tix')
1657
sig_index = self._make_index(name, '.six')
1658
if self.chk_index is not None:
1659
chk_index = self._make_index(name, '.cix')
1662
result = ExistingPack(self._pack_transport, name, rev_index,
1663
inv_index, txt_index, sig_index, chk_index)
1664
self.add_pack_to_memory(result)
1667
def _resume_pack(self, name):
1668
"""Get a suspended Pack object by name.
1670
:param name: The name of the pack - e.g. '123456'
1671
:return: A Pack object.
1673
if not re.match('[a-f0-9]{32}', name):
1674
# Tokens should be md5sums of the suspended pack file, i.e. 32 hex
1676
raise errors.UnresumableWriteGroup(
1677
self.repo, [name], 'Malformed write group token')
1679
rev_index = self._make_index(name, '.rix', resume=True)
1680
inv_index = self._make_index(name, '.iix', resume=True)
1681
txt_index = self._make_index(name, '.tix', resume=True)
1682
sig_index = self._make_index(name, '.six', resume=True)
1683
result = ResumedPack(name, rev_index, inv_index, txt_index,
1684
sig_index, self._upload_transport, self._pack_transport,
1685
self._index_transport, self)
1686
except errors.NoSuchFile, e:
1687
raise errors.UnresumableWriteGroup(self.repo, [name], str(e))
1688
self.add_pack_to_memory(result)
1689
self._resumed_packs.append(result)
1692
def allocate(self, a_new_pack):
1693
"""Allocate name in the list of packs.
1695
:param a_new_pack: A NewPack instance to be added to the collection of
1696
packs for this repository.
1698
self.ensure_loaded()
1699
if a_new_pack.name in self._names:
1700
raise errors.BzrError(
1701
'Pack %r already exists in %s' % (a_new_pack.name, self))
1702
self._names[a_new_pack.name] = tuple(a_new_pack.index_sizes)
1703
self.add_pack_to_memory(a_new_pack)
1705
def _iter_disk_pack_index(self):
1706
"""Iterate over the contents of the pack-names index.
1708
This is used when loading the list from disk, and before writing to
1709
detect updates from others during our write operation.
1710
:return: An iterator of the index contents.
1712
return self._index_class(self.transport, 'pack-names', None
1713
).iter_all_entries()
1715
def _make_index(self, name, suffix, resume=False):
1716
size_offset = self._suffix_offsets[suffix]
1717
index_name = name + suffix
1719
transport = self._upload_transport
1720
index_size = transport.stat(index_name).st_size
1722
transport = self._index_transport
1723
index_size = self._names[name][size_offset]
1724
return self._index_class(transport, index_name, index_size)
1726
def _max_pack_count(self, total_revisions):
1727
"""Return the maximum number of packs to use for total revisions.
1729
:param total_revisions: The total number of revisions in the
1732
if not total_revisions:
1734
digits = str(total_revisions)
1736
for digit in digits:
1737
result += int(digit)
1741
"""Provide an order to the underlying names."""
1742
return sorted(self._names.keys())
1744
def _obsolete_packs(self, packs):
1745
"""Move a number of packs which have been obsoleted out of the way.
1747
Each pack and its associated indices are moved out of the way.
1749
Note: for correctness this function should only be called after a new
1750
pack names index has been written without these pack names, and with
1751
the names of packs that contain the data previously available via these
1754
:param packs: The packs to obsolete.
1755
:param return: None.
1758
pack.pack_transport.rename(pack.file_name(),
1759
'../obsolete_packs/' + pack.file_name())
1760
# TODO: Probably needs to know all possible indices for this pack
1761
# - or maybe list the directory and move all indices matching this
1762
# name whether we recognize it or not?
1763
suffixes = ['.iix', '.six', '.tix', '.rix']
1764
if self.chk_index is not None:
1765
suffixes.append('.cix')
1766
for suffix in suffixes:
1767
self._index_transport.rename(pack.name + suffix,
1768
'../obsolete_packs/' + pack.name + suffix)
1770
def pack_distribution(self, total_revisions):
1771
"""Generate a list of the number of revisions to put in each pack.
1773
:param total_revisions: The total number of revisions in the
1776
if total_revisions == 0:
1778
digits = reversed(str(total_revisions))
1780
for exponent, count in enumerate(digits):
1781
size = 10 ** exponent
1782
for pos in range(int(count)):
1784
return list(reversed(result))
1786
def _pack_tuple(self, name):
1787
"""Return a tuple with the transport and file name for a pack name."""
1788
return self._pack_transport, name + '.pack'
1790
def _remove_pack_from_memory(self, pack):
1791
"""Remove pack from the packs accessed by this repository.
1793
Only affects memory state, until self._save_pack_names() is invoked.
1795
self._names.pop(pack.name)
1796
self._packs_by_name.pop(pack.name)
1797
self._remove_pack_indices(pack)
1798
self.packs.remove(pack)
1800
def _remove_pack_indices(self, pack):
1801
"""Remove the indices for pack from the aggregated indices."""
1802
self.revision_index.remove_index(pack.revision_index, pack)
1803
self.inventory_index.remove_index(pack.inventory_index, pack)
1804
self.text_index.remove_index(pack.text_index, pack)
1805
self.signature_index.remove_index(pack.signature_index, pack)
1806
if self.chk_index is not None:
1807
self.chk_index.remove_index(pack.chk_index, pack)
1810
"""Clear all cached data."""
1811
# cached revision data
1812
self.repo._revision_knit = None
1813
self.revision_index.clear()
1814
# cached signature data
1815
self.repo._signature_knit = None
1816
self.signature_index.clear()
1817
# cached file text data
1818
self.text_index.clear()
1819
self.repo._text_knit = None
1820
# cached inventory data
1821
self.inventory_index.clear()
1823
if self.chk_index is not None:
1824
self.chk_index.clear()
1825
# remove the open pack
1826
self._new_pack = None
1827
# information about packs.
1830
self._packs_by_name = {}
1831
self._packs_at_load = None
1833
def _unlock_names(self):
1834
"""Release the mutex around the pack-names index."""
1835
self.repo.control_files.unlock()
1837
def _diff_pack_names(self):
1838
"""Read the pack names from disk, and compare it to the one in memory.
1840
:return: (disk_nodes, deleted_nodes, new_nodes)
1841
disk_nodes The final set of nodes that should be referenced
1842
deleted_nodes Nodes which have been removed from when we started
1843
new_nodes Nodes that are newly introduced
1845
# load the disk nodes across
1847
for index, key, value in self._iter_disk_pack_index():
1848
disk_nodes.add((key, value))
1850
# do a two-way diff against our original content
1851
current_nodes = set()
1852
for name, sizes in self._names.iteritems():
1854
((name, ), ' '.join(str(size) for size in sizes)))
1856
# Packs no longer present in the repository, which were present when we
1857
# locked the repository
1858
deleted_nodes = self._packs_at_load - current_nodes
1859
# Packs which this process is adding
1860
new_nodes = current_nodes - self._packs_at_load
1862
# Update the disk_nodes set to include the ones we are adding, and
1863
# remove the ones which were removed by someone else
1864
disk_nodes.difference_update(deleted_nodes)
1865
disk_nodes.update(new_nodes)
1867
return disk_nodes, deleted_nodes, new_nodes
1869
def _syncronize_pack_names_from_disk_nodes(self, disk_nodes):
1870
"""Given the correct set of pack files, update our saved info.
1872
:return: (removed, added, modified)
1873
removed pack names removed from self._names
1874
added pack names added to self._names
1875
modified pack names that had changed value
1880
## self._packs_at_load = disk_nodes
1881
new_names = dict(disk_nodes)
1882
# drop no longer present nodes
1883
for pack in self.all_packs():
1884
if (pack.name,) not in new_names:
1885
removed.append(pack.name)
1886
self._remove_pack_from_memory(pack)
1887
# add new nodes/refresh existing ones
1888
for key, value in disk_nodes:
1890
sizes = self._parse_index_sizes(value)
1891
if name in self._names:
1893
if sizes != self._names[name]:
1894
# the pack for name has had its indices replaced - rare but
1895
# important to handle. XXX: probably can never happen today
1896
# because the three-way merge code above does not handle it
1897
# - you may end up adding the same key twice to the new
1898
# disk index because the set values are the same, unless
1899
# the only index shows up as deleted by the set difference
1900
# - which it may. Until there is a specific test for this,
1901
# assume its broken. RBC 20071017.
1902
self._remove_pack_from_memory(self.get_pack_by_name(name))
1903
self._names[name] = sizes
1904
self.get_pack_by_name(name)
1905
modified.append(name)
1908
self._names[name] = sizes
1909
self.get_pack_by_name(name)
1911
return removed, added, modified
1913
def _save_pack_names(self, clear_obsolete_packs=False):
1914
"""Save the list of packs.
1916
This will take out the mutex around the pack names list for the
1917
duration of the method call. If concurrent updates have been made, a
1918
three-way merge between the current list and the current in memory list
1921
:param clear_obsolete_packs: If True, clear out the contents of the
1922
obsolete_packs directory.
1926
builder = self._index_builder_class()
1927
disk_nodes, deleted_nodes, new_nodes = self._diff_pack_names()
1928
# TODO: handle same-name, index-size-changes here -
1929
# e.g. use the value from disk, not ours, *unless* we're the one
1931
for key, value in disk_nodes:
1932
builder.add_node(key, value)
1933
self.transport.put_file('pack-names', builder.finish(),
1934
mode=self.repo.bzrdir._get_file_mode())
1935
# move the baseline forward
1936
self._packs_at_load = disk_nodes
1937
if clear_obsolete_packs:
1938
self._clear_obsolete_packs()
1940
self._unlock_names()
1941
# synchronise the memory packs list with what we just wrote:
1942
self._syncronize_pack_names_from_disk_nodes(disk_nodes)
1944
def reload_pack_names(self):
1945
"""Sync our pack listing with what is present in the repository.
1947
This should be called when we find out that something we thought was
1948
present is now missing. This happens when another process re-packs the
1951
:return: True if the in-memory list of packs has been altered at all.
1953
# The ensure_loaded call is to handle the case where the first call
1954
# made involving the collection was to reload_pack_names, where we
1955
# don't have a view of disk contents. Its a bit of a bandaid, and
1956
# causes two reads of pack-names, but its a rare corner case not struck
1957
# with regular push/pull etc.
1958
first_read = self.ensure_loaded()
1961
# out the new value.
1962
disk_nodes, _, _ = self._diff_pack_names()
1963
self._packs_at_load = disk_nodes
1965
modified) = self._syncronize_pack_names_from_disk_nodes(disk_nodes)
1966
if removed or added or modified:
1970
def _restart_autopack(self):
1971
"""Reload the pack names list, and restart the autopack code."""
1972
if not self.reload_pack_names():
1973
# Re-raise the original exception, because something went missing
1974
# and a restart didn't find it
1976
raise errors.RetryAutopack(self.repo, False, sys.exc_info())
1978
def _clear_obsolete_packs(self):
1979
"""Delete everything from the obsolete-packs directory.
1981
obsolete_pack_transport = self.transport.clone('obsolete_packs')
1982
for filename in obsolete_pack_transport.list_dir('.'):
1984
obsolete_pack_transport.delete(filename)
1985
except (errors.PathError, errors.TransportError), e:
1986
warning("couldn't delete obsolete pack, skipping it:\n%s" % (e,))
1988
def _start_write_group(self):
1989
# Do not permit preparation for writing if we're not in a 'write lock'.
1990
if not self.repo.is_write_locked():
1991
raise errors.NotWriteLocked(self)
1992
self._new_pack = self.pack_factory(self, upload_suffix='.pack',
1993
file_mode=self.repo.bzrdir._get_file_mode())
1994
# allow writing: queue writes to a new index
1995
self.revision_index.add_writable_index(self._new_pack.revision_index,
1997
self.inventory_index.add_writable_index(self._new_pack.inventory_index,
1999
self.text_index.add_writable_index(self._new_pack.text_index,
2001
self._new_pack.text_index.set_optimize(combine_backing_indices=False)
2002
self.signature_index.add_writable_index(self._new_pack.signature_index,
2004
if self.chk_index is not None:
2005
self.chk_index.add_writable_index(self._new_pack.chk_index,
2007
self.repo.chk_bytes._index._add_callback = self.chk_index.add_callback
2008
self._new_pack.chk_index.set_optimize(combine_backing_indices=False)
2010
self.repo.inventories._index._add_callback = self.inventory_index.add_callback
2011
self.repo.revisions._index._add_callback = self.revision_index.add_callback
2012
self.repo.signatures._index._add_callback = self.signature_index.add_callback
2013
self.repo.texts._index._add_callback = self.text_index.add_callback
2015
def _abort_write_group(self):
2016
# FIXME: just drop the transient index.
2017
# forget what names there are
2018
if self._new_pack is not None:
2020
self._new_pack.abort()
2022
# XXX: If we aborted while in the middle of finishing the write
2023
# group, _remove_pack_indices can fail because the indexes are
2024
# already gone. If they're not there we shouldn't fail in this
2025
# case. -- mbp 20081113
2026
self._remove_pack_indices(self._new_pack)
2027
self._new_pack = None
2028
for resumed_pack in self._resumed_packs:
2030
resumed_pack.abort()
2032
# See comment in previous finally block.
2034
self._remove_pack_indices(resumed_pack)
2037
del self._resumed_packs[:]
2038
self.repo._text_knit = None
2040
def _remove_resumed_pack_indices(self):
2041
for resumed_pack in self._resumed_packs:
2042
self._remove_pack_indices(resumed_pack)
2043
del self._resumed_packs[:]
2045
def _commit_write_group(self):
2047
for prefix, versioned_file in (
2048
('revisions', self.repo.revisions),
2049
('inventories', self.repo.inventories),
2050
('texts', self.repo.texts),
2051
('signatures', self.repo.signatures),
2053
missing = versioned_file.get_missing_compression_parent_keys()
2054
all_missing.update([(prefix,) + key for key in missing])
2056
raise errors.BzrCheckError(
2057
"Repository %s has missing compression parent(s) %r "
2058
% (self.repo, sorted(all_missing)))
2059
self._remove_pack_indices(self._new_pack)
2060
should_autopack = False
2061
if self._new_pack.data_inserted():
2062
# get all the data to disk and read to use
2063
self._new_pack.finish()
2064
self.allocate(self._new_pack)
2065
self._new_pack = None
2066
should_autopack = True
2068
self._new_pack.abort()
2069
self._new_pack = None
2070
for resumed_pack in self._resumed_packs:
2071
# XXX: this is a pretty ugly way to turn the resumed pack into a
2072
# properly committed pack.
2073
self._names[resumed_pack.name] = None
2074
self._remove_pack_from_memory(resumed_pack)
2075
resumed_pack.finish()
2076
self.allocate(resumed_pack)
2077
should_autopack = True
2078
del self._resumed_packs[:]
2080
if not self.autopack():
2081
# when autopack takes no steps, the names list is still
2083
self._save_pack_names()
2084
self.repo._text_knit = None
2086
def _suspend_write_group(self):
2087
tokens = [pack.name for pack in self._resumed_packs]
2088
self._remove_pack_indices(self._new_pack)
2089
if self._new_pack.data_inserted():
2090
# get all the data to disk and read to use
2091
self._new_pack.finish(suspend=True)
2092
tokens.append(self._new_pack.name)
2093
self._new_pack = None
2095
self._new_pack.abort()
2096
self._new_pack = None
2097
self._remove_resumed_pack_indices()
2098
self.repo._text_knit = None
2101
def _resume_write_group(self, tokens):
2102
for token in tokens:
2103
self._resume_pack(token)
2106
class KnitPackRepository(KnitRepository):
2107
"""Repository with knit objects stored inside pack containers.
2109
The layering for a KnitPackRepository is:
2111
Graph | HPSS | Repository public layer |
2112
===================================================
2113
Tuple based apis below, string based, and key based apis above
2114
---------------------------------------------------
2116
Provides .texts, .revisions etc
2117
This adapts the N-tuple keys to physical knit records which only have a
2118
single string identifier (for historical reasons), which in older formats
2119
was always the revision_id, and in the mapped code for packs is always
2120
the last element of key tuples.
2121
---------------------------------------------------
2123
A separate GraphIndex is used for each of the
2124
texts/inventories/revisions/signatures contained within each individual
2125
pack file. The GraphIndex layer works in N-tuples and is unaware of any
2127
===================================================
2131
def __init__(self, _format, a_bzrdir, control_files, _commit_builder_class,
2133
KnitRepository.__init__(self, _format, a_bzrdir, control_files,
2134
_commit_builder_class, _serializer)
2135
index_transport = self._transport.clone('indices')
2136
self._pack_collection = RepositoryPackCollection(self, self._transport,
2138
self._transport.clone('upload'),
2139
self._transport.clone('packs'),
2140
_format.index_builder_class,
2141
_format.index_class,
2142
use_chk_index=self._format.supports_chks,
2144
self.inventories = KnitVersionedFiles(
2145
_KnitGraphIndex(self._pack_collection.inventory_index.combined_index,
2146
add_callback=self._pack_collection.inventory_index.add_callback,
2147
deltas=True, parents=True, is_locked=self.is_locked),
2148
data_access=self._pack_collection.inventory_index.data_access,
2149
max_delta_chain=200)
2150
self.revisions = KnitVersionedFiles(
2151
_KnitGraphIndex(self._pack_collection.revision_index.combined_index,
2152
add_callback=self._pack_collection.revision_index.add_callback,
2153
deltas=False, parents=True, is_locked=self.is_locked,
2154
track_external_parent_refs=True),
2155
data_access=self._pack_collection.revision_index.data_access,
2157
self.signatures = KnitVersionedFiles(
2158
_KnitGraphIndex(self._pack_collection.signature_index.combined_index,
2159
add_callback=self._pack_collection.signature_index.add_callback,
2160
deltas=False, parents=False, is_locked=self.is_locked),
2161
data_access=self._pack_collection.signature_index.data_access,
2163
self.texts = KnitVersionedFiles(
2164
_KnitGraphIndex(self._pack_collection.text_index.combined_index,
2165
add_callback=self._pack_collection.text_index.add_callback,
2166
deltas=True, parents=True, is_locked=self.is_locked),
2167
data_access=self._pack_collection.text_index.data_access,
2168
max_delta_chain=200)
2169
if _format.supports_chks:
2170
# No graph, no compression:- references from chks are between
2171
# different objects not temporal versions of the same; and without
2172
# some sort of temporal structure knit compression will just fail.
2173
self.chk_bytes = KnitVersionedFiles(
2174
_KnitGraphIndex(self._pack_collection.chk_index.combined_index,
2175
add_callback=self._pack_collection.chk_index.add_callback,
2176
deltas=False, parents=False, is_locked=self.is_locked),
2177
data_access=self._pack_collection.chk_index.data_access,
2180
self.chk_bytes = None
2181
# True when the repository object is 'write locked' (as opposed to the
2182
# physical lock only taken out around changes to the pack-names list.)
2183
# Another way to represent this would be a decorator around the control
2184
# files object that presents logical locks as physical ones - if this
2185
# gets ugly consider that alternative design. RBC 20071011
2186
self._write_lock_count = 0
2187
self._transaction = None
2189
self._reconcile_does_inventory_gc = True
2190
self._reconcile_fixes_text_parents = True
2191
self._reconcile_backsup_inventory = False
2193
def _warn_if_deprecated(self):
2194
# This class isn't deprecated, but one sub-format is
2195
if isinstance(self._format, RepositoryFormatKnitPack5RichRootBroken):
2196
from bzrlib import repository
2197
if repository._deprecation_warning_done:
2199
repository._deprecation_warning_done = True
2200
warning("Format %s for %s is deprecated - please use"
2201
" 'bzr upgrade --1.6.1-rich-root'"
2202
% (self._format, self.bzrdir.transport.base))
2204
def _abort_write_group(self):
2205
self._pack_collection._abort_write_group()
2207
def _find_inconsistent_revision_parents(self):
2208
"""Find revisions with incorrectly cached parents.
2210
:returns: an iterator yielding tuples of (revison-id, parents-in-index,
2211
parents-in-revision).
2213
if not self.is_locked():
2214
raise errors.ObjectNotLocked(self)
2215
pb = ui.ui_factory.nested_progress_bar()
2218
revision_nodes = self._pack_collection.revision_index \
2219
.combined_index.iter_all_entries()
2220
index_positions = []
2221
# Get the cached index values for all revisions, and also the
2222
# location in each index of the revision text so we can perform
2224
for index, key, value, refs in revision_nodes:
2225
node = (index, key, value, refs)
2226
index_memo = self.revisions._index._node_to_position(node)
2227
if index_memo[0] != index:
2228
raise AssertionError('%r != %r' % (index_memo[0], index))
2229
index_positions.append((index_memo, key[0],
2230
tuple(parent[0] for parent in refs[0])))
2231
pb.update("Reading revision index", 0, 0)
2232
index_positions.sort()
2234
pb.update("Checking cached revision graph", 0,
2235
len(index_positions))
2236
for offset in xrange(0, len(index_positions), 1000):
2237
pb.update("Checking cached revision graph", offset)
2238
to_query = index_positions[offset:offset + batch_size]
2241
rev_ids = [item[1] for item in to_query]
2242
revs = self.get_revisions(rev_ids)
2243
for revision, item in zip(revs, to_query):
2244
index_parents = item[2]
2245
rev_parents = tuple(revision.parent_ids)
2246
if index_parents != rev_parents:
2247
result.append((revision.revision_id, index_parents,
2253
def _make_parents_provider(self):
2254
return graph.CachingParentsProvider(self)
2256
def _refresh_data(self):
2257
if not self.is_locked():
2259
self._pack_collection.reload_pack_names()
2261
def _start_write_group(self):
2262
self._pack_collection._start_write_group()
2264
def _commit_write_group(self):
2265
return self._pack_collection._commit_write_group()
2267
def suspend_write_group(self):
2268
# XXX check self._write_group is self.get_transaction()?
2269
tokens = self._pack_collection._suspend_write_group()
2270
self._write_group = None
2273
def _resume_write_group(self, tokens):
2274
self._start_write_group()
2275
self._pack_collection._resume_write_group(tokens)
2276
for pack in self._pack_collection._resumed_packs:
2277
self.revisions._index.scan_unvalidated_index(pack.revision_index)
2279
def get_transaction(self):
2280
if self._write_lock_count:
2281
return self._transaction
2283
return self.control_files.get_transaction()
2285
def is_locked(self):
2286
return self._write_lock_count or self.control_files.is_locked()
2288
def is_write_locked(self):
2289
return self._write_lock_count
2291
def lock_write(self, token=None):
2292
locked = self.is_locked()
2293
if not self._write_lock_count and locked:
2294
raise errors.ReadOnlyError(self)
2295
self._write_lock_count += 1
2296
if self._write_lock_count == 1:
2297
self._transaction = transactions.WriteTransaction()
2298
for repo in self._fallback_repositories:
2299
# Writes don't affect fallback repos
2302
self._refresh_data()
2304
def lock_read(self):
2305
locked = self.is_locked()
2306
if self._write_lock_count:
2307
self._write_lock_count += 1
2309
self.control_files.lock_read()
2310
for repo in self._fallback_repositories:
2311
# Writes don't affect fallback repos
2314
self._refresh_data()
2316
def leave_lock_in_place(self):
2317
# not supported - raise an error
2318
raise NotImplementedError(self.leave_lock_in_place)
2320
def dont_leave_lock_in_place(self):
2321
# not supported - raise an error
2322
raise NotImplementedError(self.dont_leave_lock_in_place)
2326
"""Compress the data within the repository.
2328
This will pack all the data to a single pack. In future it may
2329
recompress deltas or do other such expensive operations.
2331
self._pack_collection.pack()
2334
def reconcile(self, other=None, thorough=False):
2335
"""Reconcile this repository."""
2336
from bzrlib.reconcile import PackReconciler
2337
reconciler = PackReconciler(self, thorough=thorough)
2338
reconciler.reconcile()
2341
def _reconcile_pack(self, collection, packs, extension, revs, pb):
2342
packer = ReconcilePacker(collection, packs, extension, revs)
2343
return packer.pack(pb)
2346
if self._write_lock_count == 1 and self._write_group is not None:
2347
self.abort_write_group()
2348
self._transaction = None
2349
self._write_lock_count = 0
2350
raise errors.BzrError(
2351
'Must end write group before releasing write lock on %s'
2353
if self._write_lock_count:
2354
self._write_lock_count -= 1
2355
if not self._write_lock_count:
2356
transaction = self._transaction
2357
self._transaction = None
2358
transaction.finish()
2359
for repo in self._fallback_repositories:
2362
self.control_files.unlock()
2363
for repo in self._fallback_repositories:
2367
class RepositoryFormatPack(MetaDirRepositoryFormat):
2368
"""Format logic for pack structured repositories.
2370
This repository format has:
2371
- a list of packs in pack-names
2372
- packs in packs/NAME.pack
2373
- indices in indices/NAME.{iix,six,tix,rix}
2374
- knit deltas in the packs, knit indices mapped to the indices.
2375
- thunk objects to support the knits programming API.
2376
- a format marker of its own
2377
- an optional 'shared-storage' flag
2378
- an optional 'no-working-trees' flag
2382
# Set this attribute in derived classes to control the repository class
2383
# created by open and initialize.
2384
repository_class = None
2385
# Set this attribute in derived classes to control the
2386
# _commit_builder_class that the repository objects will have passed to
2387
# their constructor.
2388
_commit_builder_class = None
2389
# Set this attribute in derived clases to control the _serializer that the
2390
# repository objects will have passed to their constructor.
2392
# Packs are not confused by ghosts.
2393
supports_ghosts = True
2394
# External references are not supported in pack repositories yet.
2395
supports_external_lookups = False
2396
# Most pack formats do not use chk lookups.
2397
supports_chks = False
2398
# What index classes to use
2399
index_builder_class = None
2401
_fetch_uses_deltas = True
2404
def initialize(self, a_bzrdir, shared=False):
2405
"""Create a pack based repository.
2407
:param a_bzrdir: bzrdir to contain the new repository; must already
2409
:param shared: If true the repository will be initialized as a shared
2412
mutter('creating repository in %s.', a_bzrdir.transport.base)
2413
dirs = ['indices', 'obsolete_packs', 'packs', 'upload']
2414
builder = self.index_builder_class()
2415
files = [('pack-names', builder.finish())]
2416
utf8_files = [('format', self.get_format_string())]
2418
self._upload_blank_content(a_bzrdir, dirs, files, utf8_files, shared)
2419
return self.open(a_bzrdir=a_bzrdir, _found=True)
2421
def open(self, a_bzrdir, _found=False, _override_transport=None):
2422
"""See RepositoryFormat.open().
2424
:param _override_transport: INTERNAL USE ONLY. Allows opening the
2425
repository at a slightly different url
2426
than normal. I.e. during 'upgrade'.
2429
format = RepositoryFormat.find_format(a_bzrdir)
2430
if _override_transport is not None:
2431
repo_transport = _override_transport
2433
repo_transport = a_bzrdir.get_repository_transport(None)
2434
control_files = lockable_files.LockableFiles(repo_transport,
2435
'lock', lockdir.LockDir)
2436
return self.repository_class(_format=self,
2438
control_files=control_files,
2439
_commit_builder_class=self._commit_builder_class,
2440
_serializer=self._serializer)
2443
class RepositoryFormatKnitPack1(RepositoryFormatPack):
2444
"""A no-subtrees parameterized Pack repository.
2446
This format was introduced in 0.92.
2449
repository_class = KnitPackRepository
2450
_commit_builder_class = PackCommitBuilder
2452
def _serializer(self):
2453
return xml5.serializer_v5
2454
# What index classes to use
2455
index_builder_class = InMemoryGraphIndex
2456
index_class = GraphIndex
2458
def _get_matching_bzrdir(self):
2459
return bzrdir.format_registry.make_bzrdir('pack-0.92')
2461
def _ignore_setting_bzrdir(self, format):
2464
_matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
2466
def get_format_string(self):
2467
"""See RepositoryFormat.get_format_string()."""
2468
return "Bazaar pack repository format 1 (needs bzr 0.92)\n"
2470
def get_format_description(self):
2471
"""See RepositoryFormat.get_format_description()."""
2472
return "Packs containing knits without subtree support"
2474
def check_conversion_target(self, target_format):
2478
class RepositoryFormatKnitPack3(RepositoryFormatPack):
2479
"""A subtrees parameterized Pack repository.
2481
This repository format uses the xml7 serializer to get:
2482
- support for recording full info about the tree root
2483
- support for recording tree-references
2485
This format was introduced in 0.92.
2488
repository_class = KnitPackRepository
2489
_commit_builder_class = PackRootCommitBuilder
2490
rich_root_data = True
2491
supports_tree_reference = True
2493
def _serializer(self):
2494
return xml7.serializer_v7
2495
# What index classes to use
2496
index_builder_class = InMemoryGraphIndex
2497
index_class = GraphIndex
2499
def _get_matching_bzrdir(self):
2500
return bzrdir.format_registry.make_bzrdir(
2501
'pack-0.92-subtree')
2503
def _ignore_setting_bzrdir(self, format):
2506
_matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
2508
def check_conversion_target(self, target_format):
2509
if not target_format.rich_root_data:
2510
raise errors.BadConversionTarget(
2511
'Does not support rich root data.', target_format)
2512
if not getattr(target_format, 'supports_tree_reference', False):
2513
raise errors.BadConversionTarget(
2514
'Does not support nested trees', target_format)
2516
def get_format_string(self):
2517
"""See RepositoryFormat.get_format_string()."""
2518
return "Bazaar pack repository format 1 with subtree support (needs bzr 0.92)\n"
2520
def get_format_description(self):
2521
"""See RepositoryFormat.get_format_description()."""
2522
return "Packs containing knits with subtree support\n"
2525
class RepositoryFormatKnitPack4(RepositoryFormatPack):
2526
"""A rich-root, no subtrees parameterized Pack repository.
2528
This repository format uses the xml6 serializer to get:
2529
- support for recording full info about the tree root
2531
This format was introduced in 1.0.
2534
repository_class = KnitPackRepository
2535
_commit_builder_class = PackRootCommitBuilder
2536
rich_root_data = True
2537
supports_tree_reference = False
2539
def _serializer(self):
2540
return xml6.serializer_v6
2541
# What index classes to use
2542
index_builder_class = InMemoryGraphIndex
2543
index_class = GraphIndex
2545
def _get_matching_bzrdir(self):
2546
return bzrdir.format_registry.make_bzrdir(
2549
def _ignore_setting_bzrdir(self, format):
2552
_matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
2554
def check_conversion_target(self, target_format):
2555
if not target_format.rich_root_data:
2556
raise errors.BadConversionTarget(
2557
'Does not support rich root data.', target_format)
2559
def get_format_string(self):
2560
"""See RepositoryFormat.get_format_string()."""
2561
return ("Bazaar pack repository format 1 with rich root"
2562
" (needs bzr 1.0)\n")
2564
def get_format_description(self):
2565
"""See RepositoryFormat.get_format_description()."""
2566
return "Packs containing knits with rich root support\n"
2569
class RepositoryFormatKnitPack5(RepositoryFormatPack):
2570
"""Repository that supports external references to allow stacking.
2574
Supports external lookups, which results in non-truncated ghosts after
2575
reconcile compared to pack-0.92 formats.
2578
repository_class = KnitPackRepository
2579
_commit_builder_class = PackCommitBuilder
2580
supports_external_lookups = True
2581
# What index classes to use
2582
index_builder_class = InMemoryGraphIndex
2583
index_class = GraphIndex
2586
def _serializer(self):
2587
return xml5.serializer_v5
2589
def _get_matching_bzrdir(self):
2590
return bzrdir.format_registry.make_bzrdir('1.6')
2592
def _ignore_setting_bzrdir(self, format):
2595
_matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
2597
def get_format_string(self):
2598
"""See RepositoryFormat.get_format_string()."""
2599
return "Bazaar RepositoryFormatKnitPack5 (bzr 1.6)\n"
2601
def get_format_description(self):
2602
"""See RepositoryFormat.get_format_description()."""
2603
return "Packs 5 (adds stacking support, requires bzr 1.6)"
2605
def check_conversion_target(self, target_format):
2609
class RepositoryFormatKnitPack5RichRoot(RepositoryFormatPack):
2610
"""A repository with rich roots and stacking.
2612
New in release 1.6.1.
2614
Supports stacking on other repositories, allowing data to be accessed
2615
without being stored locally.
2618
repository_class = KnitPackRepository
2619
_commit_builder_class = PackRootCommitBuilder
2620
rich_root_data = True
2621
supports_tree_reference = False # no subtrees
2622
supports_external_lookups = True
2623
# What index classes to use
2624
index_builder_class = InMemoryGraphIndex
2625
index_class = GraphIndex
2628
def _serializer(self):
2629
return xml6.serializer_v6
2631
def _get_matching_bzrdir(self):
2632
return bzrdir.format_registry.make_bzrdir(
2635
def _ignore_setting_bzrdir(self, format):
2638
_matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
2640
def check_conversion_target(self, target_format):
2641
if not target_format.rich_root_data:
2642
raise errors.BadConversionTarget(
2643
'Does not support rich root data.', target_format)
2645
def get_format_string(self):
2646
"""See RepositoryFormat.get_format_string()."""
2647
return "Bazaar RepositoryFormatKnitPack5RichRoot (bzr 1.6.1)\n"
2649
def get_format_description(self):
2650
return "Packs 5 rich-root (adds stacking support, requires bzr 1.6.1)"
2653
class RepositoryFormatKnitPack5RichRootBroken(RepositoryFormatPack):
2654
"""A repository with rich roots and external references.
2658
Supports external lookups, which results in non-truncated ghosts after
2659
reconcile compared to pack-0.92 formats.
2661
This format was deprecated because the serializer it uses accidentally
2662
supported subtrees, when the format was not intended to. This meant that
2663
someone could accidentally fetch from an incorrect repository.
2666
repository_class = KnitPackRepository
2667
_commit_builder_class = PackRootCommitBuilder
2668
rich_root_data = True
2669
supports_tree_reference = False # no subtrees
2671
supports_external_lookups = True
2672
# What index classes to use
2673
index_builder_class = InMemoryGraphIndex
2674
index_class = GraphIndex
2677
def _serializer(self):
2678
return xml7.serializer_v7
2680
def _get_matching_bzrdir(self):
2681
matching = bzrdir.format_registry.make_bzrdir(
2683
matching.repository_format = self
2686
def _ignore_setting_bzrdir(self, format):
2689
_matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
2691
def check_conversion_target(self, target_format):
2692
if not target_format.rich_root_data:
2693
raise errors.BadConversionTarget(
2694
'Does not support rich root data.', target_format)
2696
def get_format_string(self):
2697
"""See RepositoryFormat.get_format_string()."""
2698
return "Bazaar RepositoryFormatKnitPack5RichRoot (bzr 1.6)\n"
2700
def get_format_description(self):
2701
return ("Packs 5 rich-root (adds stacking support, requires bzr 1.6)"
2705
class RepositoryFormatKnitPack6(RepositoryFormatPack):
2706
"""A repository with stacking and btree indexes,
2707
without rich roots or subtrees.
2709
This is equivalent to pack-1.6 with B+Tree indices.
2712
repository_class = KnitPackRepository
2713
_commit_builder_class = PackCommitBuilder
2714
supports_external_lookups = True
2715
# What index classes to use
2716
index_builder_class = BTreeBuilder
2717
index_class = BTreeGraphIndex
2720
def _serializer(self):
2721
return xml5.serializer_v5
2723
def _get_matching_bzrdir(self):
2724
return bzrdir.format_registry.make_bzrdir('1.9')
2726
def _ignore_setting_bzrdir(self, format):
2729
_matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
2731
def get_format_string(self):
2732
"""See RepositoryFormat.get_format_string()."""
2733
return "Bazaar RepositoryFormatKnitPack6 (bzr 1.9)\n"
2735
def get_format_description(self):
2736
"""See RepositoryFormat.get_format_description()."""
2737
return "Packs 6 (uses btree indexes, requires bzr 1.9)"
2739
def check_conversion_target(self, target_format):
2743
class RepositoryFormatKnitPack6RichRoot(RepositoryFormatPack):
2744
"""A repository with rich roots, no subtrees, stacking and btree indexes.
2746
1.6-rich-root with B+Tree indices.
2749
repository_class = KnitPackRepository
2750
_commit_builder_class = PackRootCommitBuilder
2751
rich_root_data = True
2752
supports_tree_reference = False # no subtrees
2753
supports_external_lookups = True
2754
# What index classes to use
2755
index_builder_class = BTreeBuilder
2756
index_class = BTreeGraphIndex
2759
def _serializer(self):
2760
return xml6.serializer_v6
2762
def _get_matching_bzrdir(self):
2763
return bzrdir.format_registry.make_bzrdir(
2766
def _ignore_setting_bzrdir(self, format):
2769
_matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
2771
def check_conversion_target(self, target_format):
2772
if not target_format.rich_root_data:
2773
raise errors.BadConversionTarget(
2774
'Does not support rich root data.', target_format)
2776
def get_format_string(self):
2777
"""See RepositoryFormat.get_format_string()."""
2778
return "Bazaar RepositoryFormatKnitPack6RichRoot (bzr 1.9)\n"
2780
def get_format_description(self):
2781
return "Packs 6 rich-root (uses btree indexes, requires bzr 1.9)"
2784
class RepositoryFormatPackDevelopment2Subtree(RepositoryFormatPack):
2785
"""A subtrees development repository.
2787
This format should be retained until the second release after bzr 1.7.
2789
1.6.1-subtree[as it might have been] with B+Tree indices.
2791
This is [now] retained until we have a CHK based subtree format in
2795
repository_class = KnitPackRepository
2796
_commit_builder_class = PackRootCommitBuilder
2797
rich_root_data = True
2798
supports_tree_reference = True
2799
supports_external_lookups = True
2800
# What index classes to use
2801
index_builder_class = BTreeBuilder
2802
index_class = BTreeGraphIndex
2805
def _serializer(self):
2806
return xml7.serializer_v7
2808
def _get_matching_bzrdir(self):
2809
return bzrdir.format_registry.make_bzrdir(
2810
'development-subtree')
2812
def _ignore_setting_bzrdir(self, format):
2815
_matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
2817
def check_conversion_target(self, target_format):
2818
if not target_format.rich_root_data:
2819
raise errors.BadConversionTarget(
2820
'Does not support rich root data.', target_format)
2821
if not getattr(target_format, 'supports_tree_reference', False):
2822
raise errors.BadConversionTarget(
2823
'Does not support nested trees', target_format)
2825
def get_format_string(self):
2826
"""See RepositoryFormat.get_format_string()."""
2827
return ("Bazaar development format 2 with subtree support "
2828
"(needs bzr.dev from before 1.8)\n")
2830
def get_format_description(self):
2831
"""See RepositoryFormat.get_format_description()."""
2832
return ("Development repository format, currently the same as "
2833
"1.6.1-subtree with B+Tree indices.\n")