1
# Copyright (C) 2007-2011 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
17
from __future__ import absolute_import
22
from ..lazy_import import lazy_import
23
lazy_import(globals(), """
35
from breezy.bzr import (
38
from breezy.bzr.index import (
51
from ..decorators import (
54
from ..lock import LogicalLockResult
55
from ..repository import (
57
RepositoryWriteLockResult,
59
from ..bzr.repository import (
61
RepositoryFormatMetaDir,
63
from ..sixish import (
67
from ..bzr.vf_repository import (
68
MetaDirVersionedFileRepository,
69
MetaDirVersionedFileRepositoryFormat,
70
VersionedFileCommitBuilder,
79
class PackCommitBuilder(VersionedFileCommitBuilder):
80
"""Subclass of VersionedFileCommitBuilder to add texts with pack semantics.
82
Specifically this uses one knit object rather than one knit object per
83
added text, reducing memory and object pressure.
86
def __init__(self, repository, parents, config, timestamp=None,
87
timezone=None, committer=None, revprops=None,
88
revision_id=None, lossy=False):
89
VersionedFileCommitBuilder.__init__(self, repository, parents, config,
90
timestamp=timestamp, timezone=timezone, committer=committer,
91
revprops=revprops, revision_id=revision_id, lossy=lossy)
92
self._file_graph = graph.Graph(
93
repository._pack_collection.text_index.combined_index)
95
def _heads(self, file_id, revision_ids):
96
keys = [(file_id, revision_id) for revision_id in revision_ids]
97
return {key[1] for key in self._file_graph.heads(keys)}
101
"""An in memory proxy for a pack and its indices.
103
This is a base class that is not directly used, instead the classes
104
ExistingPack and NewPack are used.
107
# A map of index 'type' to the file extension and position in the
109
index_definitions = {
111
'revision': ('.rix', 0),
112
'inventory': ('.iix', 1),
114
'signature': ('.six', 3),
117
def __init__(self, revision_index, inventory_index, text_index,
118
signature_index, chk_index=None):
119
"""Create a pack instance.
121
:param revision_index: A GraphIndex for determining what revisions are
122
present in the Pack and accessing the locations of their texts.
123
:param inventory_index: A GraphIndex for determining what inventories are
124
present in the Pack and accessing the locations of their
126
:param text_index: A GraphIndex for determining what file texts
127
are present in the pack and accessing the locations of their
128
texts/deltas (via (fileid, revisionid) tuples).
129
:param signature_index: A GraphIndex for determining what signatures are
130
present in the Pack and accessing the locations of their texts.
131
:param chk_index: A GraphIndex for accessing content by CHK, if the
134
self.revision_index = revision_index
135
self.inventory_index = inventory_index
136
self.text_index = text_index
137
self.signature_index = signature_index
138
self.chk_index = chk_index
140
def access_tuple(self):
141
"""Return a tuple (transport, name) for the pack content."""
142
return self.pack_transport, self.file_name()
144
def _check_references(self):
145
"""Make sure our external references are present.
147
Packs are allowed to have deltas whose base is not in the pack, but it
148
must be present somewhere in this collection. It is not allowed to
149
have deltas based on a fallback repository.
150
(See <https://bugs.launchpad.net/bzr/+bug/288751>)
153
for (index_name, external_refs, index) in [
155
self._get_external_refs(self.text_index),
156
self._pack_collection.text_index.combined_index),
158
self._get_external_refs(self.inventory_index),
159
self._pack_collection.inventory_index.combined_index),
161
missing = external_refs.difference(
162
k for (idx, k, v, r) in
163
index.iter_entries(external_refs))
165
missing_items[index_name] = sorted(list(missing))
167
from pprint import pformat
168
raise errors.BzrCheckError(
169
"Newly created pack file %r has delta references to "
170
"items not in its repository:\n%s"
171
% (self, pformat(missing_items)))
174
"""Get the file name for the pack on disk."""
175
return self.name + '.pack'
177
def get_revision_count(self):
178
return self.revision_index.key_count()
180
def index_name(self, index_type, name):
181
"""Get the disk name of an index type for pack name 'name'."""
182
return name + Pack.index_definitions[index_type][0]
184
def index_offset(self, index_type):
185
"""Get the position in a index_size array for a given index type."""
186
return Pack.index_definitions[index_type][1]
188
def inventory_index_name(self, name):
189
"""The inv index is the name + .iix."""
190
return self.index_name('inventory', name)
192
def revision_index_name(self, name):
193
"""The revision index is the name + .rix."""
194
return self.index_name('revision', name)
196
def signature_index_name(self, name):
197
"""The signature index is the name + .six."""
198
return self.index_name('signature', name)
200
def text_index_name(self, name):
201
"""The text index is the name + .tix."""
202
return self.index_name('text', name)
204
def _replace_index_with_readonly(self, index_type):
205
unlimited_cache = False
206
if index_type == 'chk':
207
unlimited_cache = True
208
index = self.index_class(self.index_transport,
209
self.index_name(index_type, self.name),
210
self.index_sizes[self.index_offset(
212
unlimited_cache=unlimited_cache)
213
if index_type == 'chk':
214
index._leaf_factory = btree_index._gcchk_factory
215
setattr(self, index_type + '_index', index)
217
def __lt__(self, other):
218
if not isinstance(other, Pack):
219
raise TypeError(other)
220
return (id(self) < id(other))
223
return hash((type(self), self.revision_index, self.inventory_index,
224
self.text_index, self.signature_index, self.chk_index))
227
class ExistingPack(Pack):
228
"""An in memory proxy for an existing .pack and its disk indices."""
230
def __init__(self, pack_transport, name, revision_index, inventory_index,
231
text_index, signature_index, chk_index=None):
232
"""Create an ExistingPack object.
234
:param pack_transport: The transport where the pack file resides.
235
:param name: The name of the pack on disk in the pack_transport.
237
Pack.__init__(self, revision_index, inventory_index, text_index,
238
signature_index, chk_index)
240
self.pack_transport = pack_transport
241
if None in (revision_index, inventory_index, text_index,
242
signature_index, name, pack_transport):
243
raise AssertionError()
245
def __eq__(self, other):
246
return self.__dict__ == other.__dict__
248
def __ne__(self, other):
249
return not self.__eq__(other)
252
return "<%s.%s object at 0x%x, %s, %s" % (
253
self.__class__.__module__, self.__class__.__name__, id(self),
254
self.pack_transport, self.name)
257
return hash((type(self), self.name))
260
class ResumedPack(ExistingPack):
262
def __init__(self, name, revision_index, inventory_index, text_index,
263
signature_index, upload_transport, pack_transport, index_transport,
264
pack_collection, chk_index=None):
265
"""Create a ResumedPack object."""
266
ExistingPack.__init__(self, pack_transport, name, revision_index,
267
inventory_index, text_index, signature_index,
269
self.upload_transport = upload_transport
270
self.index_transport = index_transport
271
self.index_sizes = [None, None, None, None]
273
('revision', revision_index),
274
('inventory', inventory_index),
275
('text', text_index),
276
('signature', signature_index),
278
if chk_index is not None:
279
indices.append(('chk', chk_index))
280
self.index_sizes.append(None)
281
for index_type, index in indices:
282
offset = self.index_offset(index_type)
283
self.index_sizes[offset] = index._size
284
self.index_class = pack_collection._index_class
285
self._pack_collection = pack_collection
286
self._state = 'resumed'
287
# XXX: perhaps check that the .pack file exists?
289
def access_tuple(self):
290
if self._state == 'finished':
291
return Pack.access_tuple(self)
292
elif self._state == 'resumed':
293
return self.upload_transport, self.file_name()
295
raise AssertionError(self._state)
298
self.upload_transport.delete(self.file_name())
299
indices = [self.revision_index, self.inventory_index, self.text_index,
300
self.signature_index]
301
if self.chk_index is not None:
302
indices.append(self.chk_index)
303
for index in indices:
304
index._transport.delete(index._name)
307
self._check_references()
308
index_types = ['revision', 'inventory', 'text', 'signature']
309
if self.chk_index is not None:
310
index_types.append('chk')
311
for index_type in index_types:
312
old_name = self.index_name(index_type, self.name)
313
new_name = '../indices/' + old_name
314
self.upload_transport.move(old_name, new_name)
315
self._replace_index_with_readonly(index_type)
316
new_name = '../packs/' + self.file_name()
317
self.upload_transport.move(self.file_name(), new_name)
318
self._state = 'finished'
320
def _get_external_refs(self, index):
321
"""Return compression parents for this index that are not present.
323
This returns any compression parents that are referenced by this index,
324
which are not contained *in* this index. They may be present elsewhere.
326
return index.external_references(1)
330
"""An in memory proxy for a pack which is being created."""
332
def __init__(self, pack_collection, upload_suffix='', file_mode=None):
333
"""Create a NewPack instance.
335
:param pack_collection: A PackCollection into which this is being inserted.
336
:param upload_suffix: An optional suffix to be given to any temporary
337
files created during the pack creation. e.g '.autopack'
338
:param file_mode: Unix permissions for newly created file.
340
# The relative locations of the packs are constrained, but all are
341
# passed in because the caller has them, so as to avoid object churn.
342
index_builder_class = pack_collection._index_builder_class
343
if pack_collection.chk_index is not None:
344
chk_index = index_builder_class(reference_lists=0)
348
# Revisions: parents list, no text compression.
349
index_builder_class(reference_lists=1),
350
# Inventory: We want to map compression only, but currently the
351
# knit code hasn't been updated enough to understand that, so we
352
# have a regular 2-list index giving parents and compression
354
index_builder_class(reference_lists=2),
355
# Texts: compression and per file graph, for all fileids - so two
356
# reference lists and two elements in the key tuple.
357
index_builder_class(reference_lists=2, key_elements=2),
358
# Signatures: Just blobs to store, no compression, no parents
360
index_builder_class(reference_lists=0),
361
# CHK based storage - just blobs, no compression or parents.
364
self._pack_collection = pack_collection
365
# When we make readonly indices, we need this.
366
self.index_class = pack_collection._index_class
367
# where should the new pack be opened
368
self.upload_transport = pack_collection._upload_transport
369
# where are indices written out to
370
self.index_transport = pack_collection._index_transport
371
# where is the pack renamed to when it is finished?
372
self.pack_transport = pack_collection._pack_transport
373
# What file mode to upload the pack and indices with.
374
self._file_mode = file_mode
375
# tracks the content written to the .pack file.
376
self._hash = osutils.md5()
377
# a tuple with the length in bytes of the indices, once the pack
378
# is finalised. (rev, inv, text, sigs, chk_if_in_use)
379
self.index_sizes = None
380
# How much data to cache when writing packs. Note that this is not
381
# synchronised with reads, because it's not in the transport layer, so
382
# is not safe unless the client knows it won't be reading from the pack
384
self._cache_limit = 0
385
# the temporary pack file name.
386
self.random_name = osutils.rand_chars(20) + upload_suffix
387
# when was this pack started ?
388
self.start_time = time.time()
389
# open an output stream for the data added to the pack.
390
self.write_stream = self.upload_transport.open_write_stream(
391
self.random_name, mode=self._file_mode)
392
if 'pack' in debug.debug_flags:
393
mutter('%s: create_pack: pack stream open: %s%s t+%6.3fs',
394
time.ctime(), self.upload_transport.base, self.random_name,
395
time.time() - self.start_time)
396
# A list of byte sequences to be written to the new pack, and the
397
# aggregate size of them. Stored as a list rather than separate
398
# variables so that the _write_data closure below can update them.
399
self._buffer = [[], 0]
400
# create a callable for adding data
402
# robertc says- this is a closure rather than a method on the object
403
# so that the variables are locals, and faster than accessing object
406
def _write_data(bytes, flush=False, _buffer=self._buffer,
407
_write=self.write_stream.write, _update=self._hash.update):
408
_buffer[0].append(bytes)
409
_buffer[1] += len(bytes)
411
if _buffer[1] > self._cache_limit or flush:
412
bytes = b''.join(_buffer[0])
416
# expose this on self, for the occasion when clients want to add data.
417
self._write_data = _write_data
418
# a pack writer object to serialise pack records.
419
self._writer = pack.ContainerWriter(self._write_data)
421
# what state is the pack in? (open, finished, aborted)
423
# no name until we finish writing the content
427
"""Cancel creating this pack."""
428
self._state = 'aborted'
429
self.write_stream.close()
430
# Remove the temporary pack file.
431
self.upload_transport.delete(self.random_name)
432
# The indices have no state on disk.
434
def access_tuple(self):
435
"""Return a tuple (transport, name) for the pack content."""
436
if self._state == 'finished':
437
return Pack.access_tuple(self)
438
elif self._state == 'open':
439
return self.upload_transport, self.random_name
441
raise AssertionError(self._state)
443
def data_inserted(self):
444
"""True if data has been added to this pack."""
445
return bool(self.get_revision_count() or
446
self.inventory_index.key_count() or
447
self.text_index.key_count() or
448
self.signature_index.key_count() or
449
(self.chk_index is not None and self.chk_index.key_count()))
451
def finish_content(self):
452
if self.name is not None:
456
self._write_data(b'', flush=True)
457
self.name = self._hash.hexdigest()
459
def finish(self, suspend=False):
460
"""Finish the new pack.
463
- finalises the content
464
- assigns a name (the md5 of the content, currently)
465
- writes out the associated indices
466
- renames the pack into place.
467
- stores the index size tuple for the pack in the index_sizes
470
self.finish_content()
472
self._check_references()
474
# XXX: It'd be better to write them all to temporary names, then
475
# rename them all into place, so that the window when only some are
476
# visible is smaller. On the other hand none will be seen until
477
# they're in the names list.
478
self.index_sizes = [None, None, None, None]
479
self._write_index('revision', self.revision_index, 'revision',
481
self._write_index('inventory', self.inventory_index, 'inventory',
483
self._write_index('text', self.text_index, 'file texts', suspend)
484
self._write_index('signature', self.signature_index,
485
'revision signatures', suspend)
486
if self.chk_index is not None:
487
self.index_sizes.append(None)
488
self._write_index('chk', self.chk_index,
489
'content hash bytes', suspend)
490
self.write_stream.close(
491
want_fdatasync=self._pack_collection.config_stack.get('repository.fdatasync'))
492
# Note that this will clobber an existing pack with the same name,
493
# without checking for hash collisions. While this is undesirable this
494
# is something that can be rectified in a subsequent release. One way
495
# to rectify it may be to leave the pack at the original name, writing
496
# its pack-names entry as something like 'HASH: index-sizes
497
# temporary-name'. Allocate that and check for collisions, if it is
498
# collision free then rename it into place. If clients know this scheme
499
# they can handle missing-file errors by:
500
# - try for HASH.pack
501
# - try for temporary-name
502
# - refresh the pack-list to see if the pack is now absent
503
new_name = self.name + '.pack'
505
new_name = '../packs/' + new_name
506
self.upload_transport.move(self.random_name, new_name)
507
self._state = 'finished'
508
if 'pack' in debug.debug_flags:
509
# XXX: size might be interesting?
510
mutter('%s: create_pack: pack finished: %s%s->%s t+%6.3fs',
511
time.ctime(), self.upload_transport.base, self.random_name,
512
new_name, time.time() - self.start_time)
515
"""Flush any current data."""
517
bytes = b''.join(self._buffer[0])
518
self.write_stream.write(bytes)
519
self._hash.update(bytes)
520
self._buffer[:] = [[], 0]
522
def _get_external_refs(self, index):
523
return index._external_references()
525
def set_write_cache_size(self, size):
526
self._cache_limit = size
528
def _write_index(self, index_type, index, label, suspend=False):
529
"""Write out an index.
531
:param index_type: The type of index to write - e.g. 'revision'.
532
:param index: The index object to serialise.
533
:param label: What label to give the index e.g. 'revision'.
535
index_name = self.index_name(index_type, self.name)
537
transport = self.upload_transport
539
transport = self.index_transport
540
index_tempfile = index.finish()
541
index_bytes = index_tempfile.read()
542
write_stream = transport.open_write_stream(index_name,
543
mode=self._file_mode)
544
write_stream.write(index_bytes)
546
want_fdatasync=self._pack_collection.config_stack.get('repository.fdatasync'))
547
self.index_sizes[self.index_offset(index_type)] = len(index_bytes)
548
if 'pack' in debug.debug_flags:
549
# XXX: size might be interesting?
550
mutter('%s: create_pack: wrote %s index: %s%s t+%6.3fs',
551
time.ctime(), label, self.upload_transport.base,
552
self.random_name, time.time() - self.start_time)
553
# Replace the writable index on this object with a readonly,
554
# presently unloaded index. We should alter
555
# the index layer to make its finish() error if add_node is
556
# subsequently used. RBC
557
self._replace_index_with_readonly(index_type)
560
class AggregateIndex(object):
561
"""An aggregated index for the RepositoryPackCollection.
563
AggregateIndex is reponsible for managing the PackAccess object,
564
Index-To-Pack mapping, and all indices list for a specific type of index
565
such as 'revision index'.
567
A CombinedIndex provides an index on a single key space built up
568
from several on-disk indices. The AggregateIndex builds on this
569
to provide a knit access layer, and allows having up to one writable
570
index within the collection.
572
# XXX: Probably 'can be written to' could/should be separated from 'acts
573
# like a knit index' -- mbp 20071024
575
def __init__(self, reload_func=None, flush_func=None):
576
"""Create an AggregateIndex.
578
:param reload_func: A function to call if we find we are missing an
579
index. Should have the form reload_func() => True if the list of
580
active pack files has changed.
582
self._reload_func = reload_func
583
self.index_to_pack = {}
584
self.combined_index = CombinedGraphIndex([], reload_func=reload_func)
585
self.data_access = _DirectPackAccess(self.index_to_pack,
586
reload_func=reload_func,
587
flush_func=flush_func)
588
self.add_callback = None
590
def add_index(self, index, pack):
591
"""Add index to the aggregate, which is an index for Pack pack.
593
Future searches on the aggregate index will seach this new index
594
before all previously inserted indices.
596
:param index: An Index for the pack.
597
:param pack: A Pack instance.
599
# expose it to the index map
600
self.index_to_pack[index] = pack.access_tuple()
601
# put it at the front of the linear index list
602
self.combined_index.insert_index(0, index, pack.name)
604
def add_writable_index(self, index, pack):
605
"""Add an index which is able to have data added to it.
607
There can be at most one writable index at any time. Any
608
modifications made to the knit are put into this index.
610
:param index: An index from the pack parameter.
611
:param pack: A Pack instance.
613
if self.add_callback is not None:
614
raise AssertionError(
615
"%s already has a writable index through %s" %
616
(self, self.add_callback))
617
# allow writing: queue writes to a new index
618
self.add_index(index, pack)
619
# Updates the index to packs mapping as a side effect,
620
self.data_access.set_writer(pack._writer, index, pack.access_tuple())
621
self.add_callback = index.add_nodes
624
"""Reset all the aggregate data to nothing."""
625
self.data_access.set_writer(None, None, (None, None))
626
self.index_to_pack.clear()
627
del self.combined_index._indices[:]
628
del self.combined_index._index_names[:]
629
self.add_callback = None
631
def remove_index(self, index):
632
"""Remove index from the indices used to answer queries.
634
:param index: An index from the pack parameter.
636
del self.index_to_pack[index]
637
pos = self.combined_index._indices.index(index)
638
del self.combined_index._indices[pos]
639
del self.combined_index._index_names[pos]
640
if (self.add_callback is not None and
641
getattr(index, 'add_nodes', None) == self.add_callback):
642
self.add_callback = None
643
self.data_access.set_writer(None, None, (None, None))
646
class Packer(object):
647
"""Create a pack from packs."""
649
def __init__(self, pack_collection, packs, suffix, revision_ids=None,
653
:param pack_collection: A RepositoryPackCollection object where the
654
new pack is being written to.
655
:param packs: The packs to combine.
656
:param suffix: The suffix to use on the temporary files for the pack.
657
:param revision_ids: Revision ids to limit the pack to.
658
:param reload_func: A function to call if a pack file/index goes
659
missing. The side effect of calling this function should be to
660
update self.packs. See also AggregateIndex
664
self.revision_ids = revision_ids
665
# The pack object we are creating.
667
self._pack_collection = pack_collection
668
self._reload_func = reload_func
669
# The index layer keys for the revisions being copied. None for 'all
671
self._revision_keys = None
672
# What text keys to copy. None for 'all texts'. This is set by
673
# _copy_inventory_texts
674
self._text_filter = None
676
def pack(self, pb=None):
677
"""Create a new pack by reading data from other packs.
679
This does little more than a bulk copy of data. One key difference
680
is that data with the same item key across multiple packs is elided
681
from the output. The new pack is written into the current pack store
682
along with its indices, and the name added to the pack names. The
683
source packs are not altered and are not required to be in the current
686
:param pb: An optional progress bar to use. A nested bar is created if
688
:return: A Pack object, or None if nothing was copied.
690
# open a pack - using the same name as the last temporary file
691
# - which has already been flushed, so it's safe.
692
# XXX: - duplicate code warning with start_write_group; fix before
693
# considering 'done'.
694
if self._pack_collection._new_pack is not None:
695
raise errors.BzrError('call to %s.pack() while another pack is'
697
% (self.__class__.__name__,))
698
if self.revision_ids is not None:
699
if len(self.revision_ids) == 0:
700
# silly fetch request.
703
self.revision_ids = frozenset(self.revision_ids)
704
self.revision_keys = frozenset((revid,) for revid in
707
self.pb = ui.ui_factory.nested_progress_bar()
711
return self._create_pack_from_packs()
717
"""Open a pack for the pack we are creating."""
718
new_pack = self._pack_collection.pack_factory(self._pack_collection,
719
upload_suffix=self.suffix,
720
file_mode=self._pack_collection.repo.controldir._get_file_mode())
721
# We know that we will process all nodes in order, and don't need to
722
# query, so don't combine any indices spilled to disk until we are done
723
new_pack.revision_index.set_optimize(combine_backing_indices=False)
724
new_pack.inventory_index.set_optimize(combine_backing_indices=False)
725
new_pack.text_index.set_optimize(combine_backing_indices=False)
726
new_pack.signature_index.set_optimize(combine_backing_indices=False)
729
def _copy_revision_texts(self):
730
"""Copy revision data to the new pack."""
731
raise NotImplementedError(self._copy_revision_texts)
733
def _copy_inventory_texts(self):
734
"""Copy the inventory texts to the new pack.
736
self._revision_keys is used to determine what inventories to copy.
738
Sets self._text_filter appropriately.
740
raise NotImplementedError(self._copy_inventory_texts)
742
def _copy_text_texts(self):
743
raise NotImplementedError(self._copy_text_texts)
745
def _create_pack_from_packs(self):
746
raise NotImplementedError(self._create_pack_from_packs)
748
def _log_copied_texts(self):
749
if 'pack' in debug.debug_flags:
750
mutter('%s: create_pack: file texts copied: %s%s %d items t+%6.3fs',
751
time.ctime(), self._pack_collection._upload_transport.base,
752
self.new_pack.random_name,
753
self.new_pack.text_index.key_count(),
754
time.time() - self.new_pack.start_time)
756
def _use_pack(self, new_pack):
757
"""Return True if new_pack should be used.
759
:param new_pack: The pack that has just been created.
760
:return: True if the pack should be used.
762
return new_pack.data_inserted()
765
class RepositoryPackCollection(object):
766
"""Management of packs within a repository.
768
:ivar _names: map of {pack_name: (index_size,)}
772
resumed_pack_factory = None
773
normal_packer_class = None
774
optimising_packer_class = None
776
def __init__(self, repo, transport, index_transport, upload_transport,
777
pack_transport, index_builder_class, index_class,
779
"""Create a new RepositoryPackCollection.
781
:param transport: Addresses the repository base directory
782
(typically .bzr/repository/).
783
:param index_transport: Addresses the directory containing indices.
784
:param upload_transport: Addresses the directory into which packs are written
785
while they're being created.
786
:param pack_transport: Addresses the directory of existing complete packs.
787
:param index_builder_class: The index builder class to use.
788
:param index_class: The index class to use.
789
:param use_chk_index: Whether to setup and manage a CHK index.
791
# XXX: This should call self.reset()
793
self.transport = transport
794
self._index_transport = index_transport
795
self._upload_transport = upload_transport
796
self._pack_transport = pack_transport
797
self._index_builder_class = index_builder_class
798
self._index_class = index_class
799
self._suffix_offsets = {'.rix': 0, '.iix': 1, '.tix': 2, '.six': 3,
804
self._packs_by_name = {}
805
# the previous pack-names content
806
self._packs_at_load = None
807
# when a pack is being created by this object, the state of that pack.
808
self._new_pack = None
809
# aggregated revision index data
810
flush = self._flush_new_pack
811
self.revision_index = AggregateIndex(self.reload_pack_names, flush)
812
self.inventory_index = AggregateIndex(self.reload_pack_names, flush)
813
self.text_index = AggregateIndex(self.reload_pack_names, flush)
814
self.signature_index = AggregateIndex(self.reload_pack_names, flush)
815
all_indices = [self.revision_index, self.inventory_index,
816
self.text_index, self.signature_index]
818
self.chk_index = AggregateIndex(self.reload_pack_names, flush)
819
all_indices.append(self.chk_index)
821
# used to determine if we're using a chk_index elsewhere.
822
self.chk_index = None
823
# Tell all the CombinedGraphIndex objects about each other, so they can
824
# share hints about which pack names to search first.
825
all_combined = [agg_idx.combined_index for agg_idx in all_indices]
826
for combined_idx in all_combined:
827
combined_idx.set_sibling_indices(
828
set(all_combined).difference([combined_idx]))
830
self._resumed_packs = []
831
self.config_stack = config.LocationStack(self.transport.base)
834
return '%s(%r)' % (self.__class__.__name__, self.repo)
836
def add_pack_to_memory(self, pack):
837
"""Make a Pack object available to the repository to satisfy queries.
839
:param pack: A Pack object.
841
if pack.name in self._packs_by_name:
842
raise AssertionError(
843
'pack %s already in _packs_by_name' % (pack.name,))
844
self.packs.append(pack)
845
self._packs_by_name[pack.name] = pack
846
self.revision_index.add_index(pack.revision_index, pack)
847
self.inventory_index.add_index(pack.inventory_index, pack)
848
self.text_index.add_index(pack.text_index, pack)
849
self.signature_index.add_index(pack.signature_index, pack)
850
if self.chk_index is not None:
851
self.chk_index.add_index(pack.chk_index, pack)
854
"""Return a list of all the Pack objects this repository has.
856
Note that an in-progress pack being created is not returned.
858
:return: A list of Pack objects for all the packs in the repository.
861
for name in self.names():
862
result.append(self.get_pack_by_name(name))
866
"""Pack the pack collection incrementally.
868
This will not attempt global reorganisation or recompression,
869
rather it will just ensure that the total number of packs does
870
not grow without bound. It uses the _max_pack_count method to
871
determine if autopacking is needed, and the pack_distribution
872
method to determine the number of revisions in each pack.
874
If autopacking takes place then the packs name collection will have
875
been flushed to disk - packing requires updating the name collection
876
in synchronisation with certain steps. Otherwise the names collection
879
:return: Something evaluating true if packing took place.
883
return self._do_autopack()
884
except errors.RetryAutopack:
885
# If we get a RetryAutopack exception, we should abort the
886
# current action, and retry.
889
def _do_autopack(self):
890
# XXX: Should not be needed when the management of indices is sane.
891
total_revisions = self.revision_index.combined_index.key_count()
892
total_packs = len(self._names)
893
if self._max_pack_count(total_revisions) >= total_packs:
895
# determine which packs need changing
896
pack_distribution = self.pack_distribution(total_revisions)
898
for pack in self.all_packs():
899
revision_count = pack.get_revision_count()
900
if revision_count == 0:
901
# revision less packs are not generated by normal operation,
902
# only by operations like sign-my-commits, and thus will not
903
# tend to grow rapdily or without bound like commit containing
904
# packs do - leave them alone as packing them really should
905
# group their data with the relevant commit, and that may
906
# involve rewriting ancient history - which autopack tries to
907
# avoid. Alternatively we could not group the data but treat
908
# each of these as having a single revision, and thus add
909
# one revision for each to the total revision count, to get
910
# a matching distribution.
912
existing_packs.append((revision_count, pack))
913
pack_operations = self.plan_autopack_combinations(
914
existing_packs, pack_distribution)
915
num_new_packs = len(pack_operations)
916
num_old_packs = sum([len(po[1]) for po in pack_operations])
917
num_revs_affected = sum([po[0] for po in pack_operations])
918
mutter('Auto-packing repository %s, which has %d pack files, '
919
'containing %d revisions. Packing %d files into %d affecting %d'
921
self), total_packs, total_revisions, num_old_packs,
922
num_new_packs, num_revs_affected)
923
result = self._execute_pack_operations(pack_operations, packer_class=self.normal_packer_class,
924
reload_func=self._restart_autopack)
925
mutter('Auto-packing repository %s completed', str(self))
928
def _execute_pack_operations(self, pack_operations, packer_class,
930
"""Execute a series of pack operations.
932
:param pack_operations: A list of [revision_count, packs_to_combine].
933
:param packer_class: The class of packer to use
934
:return: The new pack names.
936
for revision_count, packs in pack_operations:
937
# we may have no-ops from the setup logic
940
packer = packer_class(self, packs, '.autopack',
941
reload_func=reload_func)
943
result = packer.pack()
944
except errors.RetryWithNewPacks:
945
# An exception is propagating out of this context, make sure
946
# this packer has cleaned up. Packer() doesn't set its new_pack
947
# state into the RepositoryPackCollection object, so we only
948
# have access to it directly here.
949
if packer.new_pack is not None:
950
packer.new_pack.abort()
955
self._remove_pack_from_memory(pack)
956
# record the newly available packs and stop advertising the old
959
for _, packs in pack_operations:
960
to_be_obsoleted.extend(packs)
961
result = self._save_pack_names(clear_obsolete_packs=True,
962
obsolete_packs=to_be_obsoleted)
965
def _flush_new_pack(self):
966
if self._new_pack is not None:
967
self._new_pack.flush()
969
def lock_names(self):
970
"""Acquire the mutex around the pack-names index.
972
This cannot be used in the middle of a read-only transaction on the
975
self.repo.control_files.lock_write()
977
def _already_packed(self):
978
"""Is the collection already packed?"""
979
return not (self.repo._format.pack_compresses or (len(self._names) > 1))
981
def pack(self, hint=None, clean_obsolete_packs=False):
982
"""Pack the pack collection totally."""
984
total_packs = len(self._names)
985
if self._already_packed():
987
total_revisions = self.revision_index.combined_index.key_count()
988
# XXX: the following may want to be a class, to pack with a given
990
mutter('Packing repository %s, which has %d pack files, '
991
'containing %d revisions with hint %r.', str(self), total_packs,
992
total_revisions, hint)
995
self._try_pack_operations(hint)
996
except RetryPackOperations:
1000
if clean_obsolete_packs:
1001
self._clear_obsolete_packs()
1003
def _try_pack_operations(self, hint):
1004
"""Calculate the pack operations based on the hint (if any), and
1007
# determine which packs need changing
1008
pack_operations = [[0, []]]
1009
for pack in self.all_packs():
1010
if hint is None or pack.name in hint:
1011
# Either no hint was provided (so we are packing everything),
1012
# or this pack was included in the hint.
1013
pack_operations[-1][0] += pack.get_revision_count()
1014
pack_operations[-1][1].append(pack)
1015
self._execute_pack_operations(pack_operations,
1016
packer_class=self.optimising_packer_class,
1017
reload_func=self._restart_pack_operations)
1019
def plan_autopack_combinations(self, existing_packs, pack_distribution):
1020
"""Plan a pack operation.
1022
:param existing_packs: The packs to pack. (A list of (revcount, Pack)
1024
:param pack_distribution: A list with the number of revisions desired
1027
if len(existing_packs) <= len(pack_distribution):
1029
existing_packs.sort(reverse=True)
1030
pack_operations = [[0, []]]
1031
# plan out what packs to keep, and what to reorganise
1032
while len(existing_packs):
1033
# take the largest pack, and if it's less than the head of the
1034
# distribution chart we will include its contents in the new pack
1035
# for that position. If it's larger, we remove its size from the
1036
# distribution chart
1037
next_pack_rev_count, next_pack = existing_packs.pop(0)
1038
if next_pack_rev_count >= pack_distribution[0]:
1039
# this is already packed 'better' than this, so we can
1040
# not waste time packing it.
1041
while next_pack_rev_count > 0:
1042
next_pack_rev_count -= pack_distribution[0]
1043
if next_pack_rev_count >= 0:
1045
del pack_distribution[0]
1047
# didn't use that entire bucket up
1048
pack_distribution[0] = -next_pack_rev_count
1050
# add the revisions we're going to add to the next output pack
1051
pack_operations[-1][0] += next_pack_rev_count
1052
# allocate this pack to the next pack sub operation
1053
pack_operations[-1][1].append(next_pack)
1054
if pack_operations[-1][0] >= pack_distribution[0]:
1055
# this pack is used up, shift left.
1056
del pack_distribution[0]
1057
pack_operations.append([0, []])
1058
# Now that we know which pack files we want to move, shove them all
1059
# into a single pack file.
1061
final_pack_list = []
1062
for num_revs, pack_files in pack_operations:
1063
final_rev_count += num_revs
1064
final_pack_list.extend(pack_files)
1065
if len(final_pack_list) == 1:
1066
raise AssertionError('We somehow generated an autopack with a'
1067
' single pack file being moved.')
1069
return [[final_rev_count, final_pack_list]]
1071
def ensure_loaded(self):
1072
"""Ensure we have read names from disk.
1074
:return: True if the disk names had not been previously read.
1076
# NB: if you see an assertion error here, it's probably access against
1077
# an unlocked repo. Naughty.
1078
if not self.repo.is_locked():
1079
raise errors.ObjectNotLocked(self.repo)
1080
if self._names is None:
1082
self._packs_at_load = set()
1083
for index, key, value in self._iter_disk_pack_index():
1084
name = key[0].decode('ascii')
1085
self._names[name] = self._parse_index_sizes(value)
1086
self._packs_at_load.add((name, value))
1090
# populate all the metadata.
1094
def _parse_index_sizes(self, value):
1095
"""Parse a string of index sizes."""
1096
return tuple(int(digits) for digits in value.split(b' '))
1098
def get_pack_by_name(self, name):
1099
"""Get a Pack object by name.
1101
:param name: The name of the pack - e.g. '123456'
1102
:return: A Pack object.
1105
return self._packs_by_name[name]
1107
rev_index = self._make_index(name, '.rix')
1108
inv_index = self._make_index(name, '.iix')
1109
txt_index = self._make_index(name, '.tix')
1110
sig_index = self._make_index(name, '.six')
1111
if self.chk_index is not None:
1112
chk_index = self._make_index(name, '.cix', is_chk=True)
1115
result = ExistingPack(self._pack_transport, name, rev_index,
1116
inv_index, txt_index, sig_index, chk_index)
1117
self.add_pack_to_memory(result)
1120
def _resume_pack(self, name):
1121
"""Get a suspended Pack object by name.
1123
:param name: The name of the pack - e.g. '123456'
1124
:return: A Pack object.
1126
if not re.match('[a-f0-9]{32}', name):
1127
# Tokens should be md5sums of the suspended pack file, i.e. 32 hex
1129
raise errors.UnresumableWriteGroup(
1130
self.repo, [name], 'Malformed write group token')
1132
rev_index = self._make_index(name, '.rix', resume=True)
1133
inv_index = self._make_index(name, '.iix', resume=True)
1134
txt_index = self._make_index(name, '.tix', resume=True)
1135
sig_index = self._make_index(name, '.six', resume=True)
1136
if self.chk_index is not None:
1137
chk_index = self._make_index(name, '.cix', resume=True,
1141
result = self.resumed_pack_factory(name, rev_index, inv_index,
1142
txt_index, sig_index, self._upload_transport,
1143
self._pack_transport, self._index_transport, self,
1144
chk_index=chk_index)
1145
except errors.NoSuchFile as e:
1146
raise errors.UnresumableWriteGroup(self.repo, [name], str(e))
1147
self.add_pack_to_memory(result)
1148
self._resumed_packs.append(result)
1151
def allocate(self, a_new_pack):
1152
"""Allocate name in the list of packs.
1154
:param a_new_pack: A NewPack instance to be added to the collection of
1155
packs for this repository.
1157
self.ensure_loaded()
1158
if a_new_pack.name in self._names:
1159
raise errors.BzrError(
1160
'Pack %r already exists in %s' % (a_new_pack.name, self))
1161
self._names[a_new_pack.name] = tuple(a_new_pack.index_sizes)
1162
self.add_pack_to_memory(a_new_pack)
1164
def _iter_disk_pack_index(self):
1165
"""Iterate over the contents of the pack-names index.
1167
This is used when loading the list from disk, and before writing to
1168
detect updates from others during our write operation.
1169
:return: An iterator of the index contents.
1171
return self._index_class(self.transport, 'pack-names', None
1172
).iter_all_entries()
1174
def _make_index(self, name, suffix, resume=False, is_chk=False):
1175
size_offset = self._suffix_offsets[suffix]
1176
index_name = name + suffix
1178
transport = self._upload_transport
1179
index_size = transport.stat(index_name).st_size
1181
transport = self._index_transport
1182
index_size = self._names[name][size_offset]
1183
index = self._index_class(transport, index_name, index_size,
1184
unlimited_cache=is_chk)
1185
if is_chk and self._index_class is btree_index.BTreeGraphIndex:
1186
index._leaf_factory = btree_index._gcchk_factory
1189
def _max_pack_count(self, total_revisions):
1190
"""Return the maximum number of packs to use for total revisions.
1192
:param total_revisions: The total number of revisions in the
1195
if not total_revisions:
1197
digits = str(total_revisions)
1199
for digit in digits:
1200
result += int(digit)
1204
"""Provide an order to the underlying names."""
1205
return sorted(self._names.keys())
1207
def _obsolete_packs(self, packs):
1208
"""Move a number of packs which have been obsoleted out of the way.
1210
Each pack and its associated indices are moved out of the way.
1212
Note: for correctness this function should only be called after a new
1213
pack names index has been written without these pack names, and with
1214
the names of packs that contain the data previously available via these
1217
:param packs: The packs to obsolete.
1218
:param return: None.
1223
pack.pack_transport.move(pack.file_name(),
1224
'../obsolete_packs/' + pack.file_name())
1225
except errors.NoSuchFile:
1226
# perhaps obsolete_packs was removed? Let's create it and
1229
pack.pack_transport.mkdir('../obsolete_packs/')
1230
except errors.FileExists:
1232
pack.pack_transport.move(pack.file_name(),
1233
'../obsolete_packs/' + pack.file_name())
1234
except (errors.PathError, errors.TransportError) as e:
1235
# TODO: Should these be warnings or mutters?
1236
mutter("couldn't rename obsolete pack, skipping it:\n%s"
1238
# TODO: Probably needs to know all possible indices for this pack
1239
# - or maybe list the directory and move all indices matching this
1240
# name whether we recognize it or not?
1241
suffixes = ['.iix', '.six', '.tix', '.rix']
1242
if self.chk_index is not None:
1243
suffixes.append('.cix')
1244
for suffix in suffixes:
1246
self._index_transport.move(pack.name + suffix,
1247
'../obsolete_packs/' + pack.name + suffix)
1248
except (errors.PathError, errors.TransportError) as e:
1249
mutter("couldn't rename obsolete index, skipping it:\n%s"
1252
def pack_distribution(self, total_revisions):
1253
"""Generate a list of the number of revisions to put in each pack.
1255
:param total_revisions: The total number of revisions in the
1258
if total_revisions == 0:
1260
digits = reversed(str(total_revisions))
1262
for exponent, count in enumerate(digits):
1263
size = 10 ** exponent
1264
for pos in range(int(count)):
1266
return list(reversed(result))
1268
def _pack_tuple(self, name):
1269
"""Return a tuple with the transport and file name for a pack name."""
1270
return self._pack_transport, name + '.pack'
1272
def _remove_pack_from_memory(self, pack):
1273
"""Remove pack from the packs accessed by this repository.
1275
Only affects memory state, until self._save_pack_names() is invoked.
1277
self._names.pop(pack.name)
1278
self._packs_by_name.pop(pack.name)
1279
self._remove_pack_indices(pack)
1280
self.packs.remove(pack)
1282
def _remove_pack_indices(self, pack, ignore_missing=False):
1283
"""Remove the indices for pack from the aggregated indices.
1285
:param ignore_missing: Suppress KeyErrors from calling remove_index.
1287
for index_type in Pack.index_definitions:
1288
attr_name = index_type + '_index'
1289
aggregate_index = getattr(self, attr_name)
1290
if aggregate_index is not None:
1291
pack_index = getattr(pack, attr_name)
1293
aggregate_index.remove_index(pack_index)
1300
"""Clear all cached data."""
1301
# cached revision data
1302
self.revision_index.clear()
1303
# cached signature data
1304
self.signature_index.clear()
1305
# cached file text data
1306
self.text_index.clear()
1307
# cached inventory data
1308
self.inventory_index.clear()
1310
if self.chk_index is not None:
1311
self.chk_index.clear()
1312
# remove the open pack
1313
self._new_pack = None
1314
# information about packs.
1317
self._packs_by_name = {}
1318
self._packs_at_load = None
1320
def _unlock_names(self):
1321
"""Release the mutex around the pack-names index."""
1322
self.repo.control_files.unlock()
1324
def _diff_pack_names(self):
1325
"""Read the pack names from disk, and compare it to the one in memory.
1327
:return: (disk_nodes, deleted_nodes, new_nodes)
1328
disk_nodes The final set of nodes that should be referenced
1329
deleted_nodes Nodes which have been removed from when we started
1330
new_nodes Nodes that are newly introduced
1332
# load the disk nodes across
1334
for index, key, value in self._iter_disk_pack_index():
1335
disk_nodes.add((key[0].decode('ascii'), value))
1336
orig_disk_nodes = set(disk_nodes)
1338
# do a two-way diff against our original content
1339
current_nodes = set()
1340
for name, sizes in viewitems(self._names):
1342
(name, b' '.join(b'%d' % size for size in sizes)))
1344
# Packs no longer present in the repository, which were present when we
1345
# locked the repository
1346
deleted_nodes = self._packs_at_load - current_nodes
1347
# Packs which this process is adding
1348
new_nodes = current_nodes - self._packs_at_load
1350
# Update the disk_nodes set to include the ones we are adding, and
1351
# remove the ones which were removed by someone else
1352
disk_nodes.difference_update(deleted_nodes)
1353
disk_nodes.update(new_nodes)
1355
return disk_nodes, deleted_nodes, new_nodes, orig_disk_nodes
1357
def _syncronize_pack_names_from_disk_nodes(self, disk_nodes):
1358
"""Given the correct set of pack files, update our saved info.
1360
:return: (removed, added, modified)
1361
removed pack names removed from self._names
1362
added pack names added to self._names
1363
modified pack names that had changed value
1368
## self._packs_at_load = disk_nodes
1369
new_names = dict(disk_nodes)
1370
# drop no longer present nodes
1371
for pack in self.all_packs():
1372
if pack.name not in new_names:
1373
removed.append(pack.name)
1374
self._remove_pack_from_memory(pack)
1375
# add new nodes/refresh existing ones
1376
for name, value in disk_nodes:
1377
sizes = self._parse_index_sizes(value)
1378
if name in self._names:
1380
if sizes != self._names[name]:
1381
# the pack for name has had its indices replaced - rare but
1382
# important to handle. XXX: probably can never happen today
1383
# because the three-way merge code above does not handle it
1384
# - you may end up adding the same key twice to the new
1385
# disk index because the set values are the same, unless
1386
# the only index shows up as deleted by the set difference
1387
# - which it may. Until there is a specific test for this,
1388
# assume it's broken. RBC 20071017.
1389
self._remove_pack_from_memory(self.get_pack_by_name(name))
1390
self._names[name] = sizes
1391
self.get_pack_by_name(name)
1392
modified.append(name)
1395
self._names[name] = sizes
1396
self.get_pack_by_name(name)
1398
return removed, added, modified
1400
def _save_pack_names(self, clear_obsolete_packs=False, obsolete_packs=None):
1401
"""Save the list of packs.
1403
This will take out the mutex around the pack names list for the
1404
duration of the method call. If concurrent updates have been made, a
1405
three-way merge between the current list and the current in memory list
1408
:param clear_obsolete_packs: If True, clear out the contents of the
1409
obsolete_packs directory.
1410
:param obsolete_packs: Packs that are obsolete once the new pack-names
1411
file has been written.
1412
:return: A list of the names saved that were not previously on disk.
1414
already_obsolete = []
1417
builder = self._index_builder_class()
1418
(disk_nodes, deleted_nodes, new_nodes,
1419
orig_disk_nodes) = self._diff_pack_names()
1420
# TODO: handle same-name, index-size-changes here -
1421
# e.g. use the value from disk, not ours, *unless* we're the one
1423
for name, value in disk_nodes:
1424
builder.add_node((name.encode('ascii'), ), value)
1425
self.transport.put_file('pack-names', builder.finish(),
1426
mode=self.repo.controldir._get_file_mode())
1427
self._packs_at_load = disk_nodes
1428
if clear_obsolete_packs:
1431
to_preserve = {o.name for o in obsolete_packs}
1432
already_obsolete = self._clear_obsolete_packs(to_preserve)
1434
self._unlock_names()
1435
# synchronise the memory packs list with what we just wrote:
1436
self._syncronize_pack_names_from_disk_nodes(disk_nodes)
1438
# TODO: We could add one more condition here. "if o.name not in
1439
# orig_disk_nodes and o != the new_pack we haven't written to
1440
# disk yet. However, the new pack object is not easily
1441
# accessible here (it would have to be passed through the
1442
# autopacking code, etc.)
1443
obsolete_packs = [o for o in obsolete_packs
1444
if o.name not in already_obsolete]
1445
self._obsolete_packs(obsolete_packs)
1446
return [new_node[0] for new_node in new_nodes]
1448
def reload_pack_names(self):
1449
"""Sync our pack listing with what is present in the repository.
1451
This should be called when we find out that something we thought was
1452
present is now missing. This happens when another process re-packs the
1455
:return: True if the in-memory list of packs has been altered at all.
1457
# The ensure_loaded call is to handle the case where the first call
1458
# made involving the collection was to reload_pack_names, where we
1459
# don't have a view of disk contents. It's a bit of a bandaid, and
1460
# causes two reads of pack-names, but it's a rare corner case not
1461
# struck with regular push/pull etc.
1462
first_read = self.ensure_loaded()
1465
# out the new value.
1466
(disk_nodes, deleted_nodes, new_nodes,
1467
orig_disk_nodes) = self._diff_pack_names()
1468
# _packs_at_load is meant to be the explicit list of names in
1469
# 'pack-names' at then start. As such, it should not contain any
1470
# pending names that haven't been written out yet.
1471
self._packs_at_load = orig_disk_nodes
1473
modified) = self._syncronize_pack_names_from_disk_nodes(disk_nodes)
1474
if removed or added or modified:
1478
def _restart_autopack(self):
1479
"""Reload the pack names list, and restart the autopack code."""
1480
if not self.reload_pack_names():
1481
# Re-raise the original exception, because something went missing
1482
# and a restart didn't find it
1484
raise errors.RetryAutopack(self.repo, False, sys.exc_info())
1486
def _restart_pack_operations(self):
1487
"""Reload the pack names list, and restart the autopack code."""
1488
if not self.reload_pack_names():
1489
# Re-raise the original exception, because something went missing
1490
# and a restart didn't find it
1492
raise RetryPackOperations(self.repo, False, sys.exc_info())
1494
def _clear_obsolete_packs(self, preserve=None):
1495
"""Delete everything from the obsolete-packs directory.
1497
:return: A list of pack identifiers (the filename without '.pack') that
1498
were found in obsolete_packs.
1501
obsolete_pack_transport = self.transport.clone('obsolete_packs')
1502
if preserve is None:
1505
obsolete_pack_files = obsolete_pack_transport.list_dir('.')
1506
except errors.NoSuchFile:
1508
for filename in obsolete_pack_files:
1509
name, ext = osutils.splitext(filename)
1512
if name in preserve:
1515
obsolete_pack_transport.delete(filename)
1516
except (errors.PathError, errors.TransportError) as e:
1517
warning("couldn't delete obsolete pack, skipping it:\n%s"
1521
def _start_write_group(self):
1522
# Do not permit preparation for writing if we're not in a 'write lock'.
1523
if not self.repo.is_write_locked():
1524
raise errors.NotWriteLocked(self)
1525
self._new_pack = self.pack_factory(self, upload_suffix='.pack',
1526
file_mode=self.repo.controldir._get_file_mode())
1527
# allow writing: queue writes to a new index
1528
self.revision_index.add_writable_index(self._new_pack.revision_index,
1530
self.inventory_index.add_writable_index(self._new_pack.inventory_index,
1532
self.text_index.add_writable_index(self._new_pack.text_index,
1534
self._new_pack.text_index.set_optimize(combine_backing_indices=False)
1535
self.signature_index.add_writable_index(self._new_pack.signature_index,
1537
if self.chk_index is not None:
1538
self.chk_index.add_writable_index(self._new_pack.chk_index,
1540
self.repo.chk_bytes._index._add_callback = self.chk_index.add_callback
1541
self._new_pack.chk_index.set_optimize(
1542
combine_backing_indices=False)
1544
self.repo.inventories._index._add_callback = self.inventory_index.add_callback
1545
self.repo.revisions._index._add_callback = self.revision_index.add_callback
1546
self.repo.signatures._index._add_callback = self.signature_index.add_callback
1547
self.repo.texts._index._add_callback = self.text_index.add_callback
1549
def _abort_write_group(self):
1550
# FIXME: just drop the transient index.
1551
# forget what names there are
1552
if self._new_pack is not None:
1553
with cleanup.ExitStack() as stack:
1554
stack.callback(setattr, self, '_new_pack', None)
1555
# If we aborted while in the middle of finishing the write
1556
# group, _remove_pack_indices could fail because the indexes are
1557
# already gone. But they're not there we shouldn't fail in this
1558
# case, so we pass ignore_missing=True.
1559
stack.callback(self._remove_pack_indices, self._new_pack,
1560
ignore_missing=True)
1561
self._new_pack.abort()
1562
for resumed_pack in self._resumed_packs:
1563
with cleanup.ExitStack() as stack:
1564
# See comment in previous finally block.
1565
stack.callback(self._remove_pack_indices, resumed_pack,
1566
ignore_missing=True)
1567
resumed_pack.abort()
1568
del self._resumed_packs[:]
1570
def _remove_resumed_pack_indices(self):
1571
for resumed_pack in self._resumed_packs:
1572
self._remove_pack_indices(resumed_pack)
1573
del self._resumed_packs[:]
1575
def _check_new_inventories(self):
1576
"""Detect missing inventories in this write group.
1578
:returns: list of strs, summarising any problems found. If the list is
1579
empty no problems were found.
1581
# The base implementation does no checks. GCRepositoryPackCollection
1585
def _commit_write_group(self):
1587
for prefix, versioned_file in (
1588
('revisions', self.repo.revisions),
1589
('inventories', self.repo.inventories),
1590
('texts', self.repo.texts),
1591
('signatures', self.repo.signatures),
1593
missing = versioned_file.get_missing_compression_parent_keys()
1594
all_missing.update([(prefix,) + key for key in missing])
1596
raise errors.BzrCheckError(
1597
"Repository %s has missing compression parent(s) %r "
1598
% (self.repo, sorted(all_missing)))
1599
problems = self._check_new_inventories()
1601
problems_summary = '\n'.join(problems)
1602
raise errors.BzrCheckError(
1603
"Cannot add revision(s) to repository: " + problems_summary)
1604
self._remove_pack_indices(self._new_pack)
1605
any_new_content = False
1606
if self._new_pack.data_inserted():
1607
# get all the data to disk and read to use
1608
self._new_pack.finish()
1609
self.allocate(self._new_pack)
1610
self._new_pack = None
1611
any_new_content = True
1613
self._new_pack.abort()
1614
self._new_pack = None
1615
for resumed_pack in self._resumed_packs:
1616
# XXX: this is a pretty ugly way to turn the resumed pack into a
1617
# properly committed pack.
1618
self._names[resumed_pack.name] = None
1619
self._remove_pack_from_memory(resumed_pack)
1620
resumed_pack.finish()
1621
self.allocate(resumed_pack)
1622
any_new_content = True
1623
del self._resumed_packs[:]
1625
result = self.autopack()
1627
# when autopack takes no steps, the names list is still
1629
return self._save_pack_names()
1633
def _suspend_write_group(self):
1634
tokens = [pack.name for pack in self._resumed_packs]
1635
self._remove_pack_indices(self._new_pack)
1636
if self._new_pack.data_inserted():
1637
# get all the data to disk and read to use
1638
self._new_pack.finish(suspend=True)
1639
tokens.append(self._new_pack.name)
1640
self._new_pack = None
1642
self._new_pack.abort()
1643
self._new_pack = None
1644
self._remove_resumed_pack_indices()
1647
def _resume_write_group(self, tokens):
1648
for token in tokens:
1649
self._resume_pack(token)
1652
class PackRepository(MetaDirVersionedFileRepository):
1653
"""Repository with knit objects stored inside pack containers.
1655
The layering for a KnitPackRepository is:
1657
Graph | HPSS | Repository public layer |
1658
===================================================
1659
Tuple based apis below, string based, and key based apis above
1660
---------------------------------------------------
1662
Provides .texts, .revisions etc
1663
This adapts the N-tuple keys to physical knit records which only have a
1664
single string identifier (for historical reasons), which in older formats
1665
was always the revision_id, and in the mapped code for packs is always
1666
the last element of key tuples.
1667
---------------------------------------------------
1669
A separate GraphIndex is used for each of the
1670
texts/inventories/revisions/signatures contained within each individual
1671
pack file. The GraphIndex layer works in N-tuples and is unaware of any
1673
===================================================
1677
# These attributes are inherited from the Repository base class. Setting
1678
# them to None ensures that if the constructor is changed to not initialize
1679
# them, or a subclass fails to call the constructor, that an error will
1680
# occur rather than the system working but generating incorrect data.
1681
_commit_builder_class = None
1684
def __init__(self, _format, a_controldir, control_files, _commit_builder_class,
1686
MetaDirRepository.__init__(self, _format, a_controldir, control_files)
1687
self._commit_builder_class = _commit_builder_class
1688
self._serializer = _serializer
1689
self._reconcile_fixes_text_parents = True
1690
if self._format.supports_external_lookups:
1691
self._unstacked_provider = graph.CachingParentsProvider(
1692
self._make_parents_provider_unstacked())
1694
self._unstacked_provider = graph.CachingParentsProvider(self)
1695
self._unstacked_provider.disable_cache()
1697
def _all_revision_ids(self):
1698
"""See Repository.all_revision_ids()."""
1699
with self.lock_read():
1700
return [key[0] for key in self.revisions.keys()]
1702
def _abort_write_group(self):
1703
self.revisions._index._key_dependencies.clear()
1704
self._pack_collection._abort_write_group()
1706
def _make_parents_provider(self):
1707
if not self._format.supports_external_lookups:
1708
return self._unstacked_provider
1709
return graph.StackedParentsProvider(_LazyListJoin(
1710
[self._unstacked_provider], self._fallback_repositories))
1712
def _refresh_data(self):
1713
if not self.is_locked():
1715
self._pack_collection.reload_pack_names()
1716
self._unstacked_provider.disable_cache()
1717
self._unstacked_provider.enable_cache()
1719
def _start_write_group(self):
1720
self._pack_collection._start_write_group()
1722
def _commit_write_group(self):
1723
hint = self._pack_collection._commit_write_group()
1724
self.revisions._index._key_dependencies.clear()
1725
# The commit may have added keys that were previously cached as
1726
# missing, so reset the cache.
1727
self._unstacked_provider.disable_cache()
1728
self._unstacked_provider.enable_cache()
1731
def suspend_write_group(self):
1732
# XXX check self._write_group is self.get_transaction()?
1733
tokens = self._pack_collection._suspend_write_group()
1734
self.revisions._index._key_dependencies.clear()
1735
self._write_group = None
1738
def _resume_write_group(self, tokens):
1739
self._start_write_group()
1741
self._pack_collection._resume_write_group(tokens)
1742
except errors.UnresumableWriteGroup:
1743
self._abort_write_group()
1745
for pack in self._pack_collection._resumed_packs:
1746
self.revisions._index.scan_unvalidated_index(pack.revision_index)
1748
def get_transaction(self):
1749
if self._write_lock_count:
1750
return self._transaction
1752
return self.control_files.get_transaction()
1754
def is_locked(self):
1755
return self._write_lock_count or self.control_files.is_locked()
1757
def is_write_locked(self):
1758
return self._write_lock_count
1760
def lock_write(self, token=None):
1761
"""Lock the repository for writes.
1763
:return: A breezy.repository.RepositoryWriteLockResult.
1765
locked = self.is_locked()
1766
if not self._write_lock_count and locked:
1767
raise errors.ReadOnlyError(self)
1768
self._write_lock_count += 1
1769
if self._write_lock_count == 1:
1770
self._transaction = transactions.WriteTransaction()
1772
if 'relock' in debug.debug_flags and self._prev_lock == 'w':
1773
note('%r was write locked again', self)
1774
self._prev_lock = 'w'
1775
self._unstacked_provider.enable_cache()
1776
for repo in self._fallback_repositories:
1777
# Writes don't affect fallback repos
1779
self._refresh_data()
1780
return RepositoryWriteLockResult(self.unlock, None)
1782
def lock_read(self):
1783
"""Lock the repository for reads.
1785
:return: A breezy.lock.LogicalLockResult.
1787
locked = self.is_locked()
1788
if self._write_lock_count:
1789
self._write_lock_count += 1
1791
self.control_files.lock_read()
1793
if 'relock' in debug.debug_flags and self._prev_lock == 'r':
1794
note('%r was read locked again', self)
1795
self._prev_lock = 'r'
1796
self._unstacked_provider.enable_cache()
1797
for repo in self._fallback_repositories:
1799
self._refresh_data()
1800
return LogicalLockResult(self.unlock)
1802
def leave_lock_in_place(self):
1803
# not supported - raise an error
1804
raise NotImplementedError(self.leave_lock_in_place)
1806
def dont_leave_lock_in_place(self):
1807
# not supported - raise an error
1808
raise NotImplementedError(self.dont_leave_lock_in_place)
1810
def pack(self, hint=None, clean_obsolete_packs=False):
1811
"""Compress the data within the repository.
1813
This will pack all the data to a single pack. In future it may
1814
recompress deltas or do other such expensive operations.
1816
with self.lock_write():
1817
self._pack_collection.pack(
1818
hint=hint, clean_obsolete_packs=clean_obsolete_packs)
1820
def reconcile(self, other=None, thorough=False):
1821
"""Reconcile this repository."""
1822
from .reconcile import PackReconciler
1823
with self.lock_write():
1824
reconciler = PackReconciler(self, thorough=thorough)
1825
return reconciler.reconcile()
1827
def _reconcile_pack(self, collection, packs, extension, revs, pb):
1828
raise NotImplementedError(self._reconcile_pack)
1830
@only_raises(errors.LockNotHeld, errors.LockBroken)
1832
if self._write_lock_count == 1 and self._write_group is not None:
1833
self.abort_write_group()
1834
self._unstacked_provider.disable_cache()
1835
self._transaction = None
1836
self._write_lock_count = 0
1837
raise errors.BzrError(
1838
'Must end write group before releasing write lock on %s'
1840
if self._write_lock_count:
1841
self._write_lock_count -= 1
1842
if not self._write_lock_count:
1843
transaction = self._transaction
1844
self._transaction = None
1845
transaction.finish()
1847
self.control_files.unlock()
1849
if not self.is_locked():
1850
self._unstacked_provider.disable_cache()
1851
for repo in self._fallback_repositories:
1855
class RepositoryFormatPack(MetaDirVersionedFileRepositoryFormat):
1856
"""Format logic for pack structured repositories.
1858
This repository format has:
1859
- a list of packs in pack-names
1860
- packs in packs/NAME.pack
1861
- indices in indices/NAME.{iix,six,tix,rix}
1862
- knit deltas in the packs, knit indices mapped to the indices.
1863
- thunk objects to support the knits programming API.
1864
- a format marker of its own
1865
- an optional 'shared-storage' flag
1866
- an optional 'no-working-trees' flag
1870
# Set this attribute in derived classes to control the repository class
1871
# created by open and initialize.
1872
repository_class = None
1873
# Set this attribute in derived classes to control the
1874
# _commit_builder_class that the repository objects will have passed to
1875
# their constructor.
1876
_commit_builder_class = None
1877
# Set this attribute in derived clases to control the _serializer that the
1878
# repository objects will have passed to their constructor.
1880
# Packs are not confused by ghosts.
1881
supports_ghosts = True
1882
# External references are not supported in pack repositories yet.
1883
supports_external_lookups = False
1884
# Most pack formats do not use chk lookups.
1885
supports_chks = False
1886
# What index classes to use
1887
index_builder_class = None
1889
_fetch_uses_deltas = True
1891
supports_funky_characters = True
1892
revision_graph_can_have_wrong_parents = True
1894
def initialize(self, a_controldir, shared=False):
1895
"""Create a pack based repository.
1897
:param a_controldir: bzrdir to contain the new repository; must already
1899
:param shared: If true the repository will be initialized as a shared
1902
mutter('creating repository in %s.', a_controldir.transport.base)
1903
dirs = ['indices', 'obsolete_packs', 'packs', 'upload']
1904
builder = self.index_builder_class()
1905
files = [('pack-names', builder.finish())]
1906
utf8_files = [('format', self.get_format_string())]
1908
self._upload_blank_content(
1909
a_controldir, dirs, files, utf8_files, shared)
1910
repository = self.open(a_controldir=a_controldir, _found=True)
1911
self._run_post_repo_init_hooks(repository, a_controldir, shared)
1914
def open(self, a_controldir, _found=False, _override_transport=None):
1915
"""See RepositoryFormat.open().
1917
:param _override_transport: INTERNAL USE ONLY. Allows opening the
1918
repository at a slightly different url
1919
than normal. I.e. during 'upgrade'.
1922
format = RepositoryFormatMetaDir.find_format(a_controldir)
1923
if _override_transport is not None:
1924
repo_transport = _override_transport
1926
repo_transport = a_controldir.get_repository_transport(None)
1927
control_files = lockable_files.LockableFiles(repo_transport,
1928
'lock', lockdir.LockDir)
1929
return self.repository_class(_format=self,
1930
a_controldir=a_controldir,
1931
control_files=control_files,
1932
_commit_builder_class=self._commit_builder_class,
1933
_serializer=self._serializer)
1936
class RetryPackOperations(errors.RetryWithNewPacks):
1937
"""Raised when we are packing and we find a missing file.
1939
Meant as a signaling exception, to tell the RepositoryPackCollection.pack
1940
code it should try again.
1943
internal_error = True
1945
_fmt = ("Pack files have changed, reload and try pack again."
1946
" context: %(context)s %(orig_error)s")
1949
class _DirectPackAccess(object):
1950
"""Access to data in one or more packs with less translation."""
1952
def __init__(self, index_to_packs, reload_func=None, flush_func=None):
1953
"""Create a _DirectPackAccess object.
1955
:param index_to_packs: A dict mapping index objects to the transport
1956
and file names for obtaining data.
1957
:param reload_func: A function to call if we determine that the pack
1958
files have moved and we need to reload our caches. See
1959
breezy.repo_fmt.pack_repo.AggregateIndex for more details.
1961
self._container_writer = None
1962
self._write_index = None
1963
self._indices = index_to_packs
1964
self._reload_func = reload_func
1965
self._flush_func = flush_func
1967
def add_raw_record(self, key, size, raw_data):
1968
"""Add raw knit bytes to a storage area.
1970
The data is spooled to the container writer in one bytes-record per
1973
:param key: key of the data segment
1974
:param size: length of the data segment
1975
:param raw_data: A bytestring containing the data.
1976
:return: An opaque index memo For _DirectPackAccess the memo is
1977
(index, pos, length), where the index field is the write_index
1978
object supplied to the PackAccess object.
1980
p_offset, p_length = self._container_writer.add_bytes_record(
1982
return (self._write_index, p_offset, p_length)
1984
def add_raw_records(self, key_sizes, raw_data):
1985
"""Add raw knit bytes to a storage area.
1987
The data is spooled to the container writer in one bytes-record per
1990
:param sizes: An iterable of tuples containing the key and size of each
1992
:param raw_data: A bytestring containing the data.
1993
:return: A list of memos to retrieve the record later. Each memo is an
1994
opaque index memo. For _DirectPackAccess the memo is (index, pos,
1995
length), where the index field is the write_index object supplied
1996
to the PackAccess object.
1998
raw_data = b''.join(raw_data)
1999
if not isinstance(raw_data, bytes):
2000
raise AssertionError(
2001
'data must be plain bytes was %s' % type(raw_data))
2004
for key, size in key_sizes:
2006
self.add_raw_record(key, size, [raw_data[offset:offset + size]]))
2011
"""Flush pending writes on this access object.
2013
This will flush any buffered writes to a NewPack.
2015
if self._flush_func is not None:
2018
def get_raw_records(self, memos_for_retrieval):
2019
"""Get the raw bytes for a records.
2021
:param memos_for_retrieval: An iterable containing the (index, pos,
2022
length) memo for retrieving the bytes. The Pack access method
2023
looks up the pack to use for a given record in its index_to_pack
2025
:return: An iterator over the bytes of the records.
2027
# first pass, group into same-index requests
2029
current_index = None
2030
for (index, offset, length) in memos_for_retrieval:
2031
if current_index == index:
2032
current_list.append((offset, length))
2034
if current_index is not None:
2035
request_lists.append((current_index, current_list))
2036
current_index = index
2037
current_list = [(offset, length)]
2038
# handle the last entry
2039
if current_index is not None:
2040
request_lists.append((current_index, current_list))
2041
for index, offsets in request_lists:
2043
transport, path = self._indices[index]
2045
# A KeyError here indicates that someone has triggered an index
2046
# reload, and this index has gone missing, we need to start
2048
if self._reload_func is None:
2049
# If we don't have a _reload_func there is nothing that can
2052
raise errors.RetryWithNewPacks(index,
2053
reload_occurred=True,
2054
exc_info=sys.exc_info())
2056
reader = pack.make_readv_reader(transport, path, offsets)
2057
for names, read_func in reader.iter_records():
2058
yield read_func(None)
2059
except errors.NoSuchFile:
2060
# A NoSuchFile error indicates that a pack file has gone
2061
# missing on disk, we need to trigger a reload, and start over.
2062
if self._reload_func is None:
2064
raise errors.RetryWithNewPacks(transport.abspath(path),
2065
reload_occurred=False,
2066
exc_info=sys.exc_info())
2068
def set_writer(self, writer, index, transport_packname):
2069
"""Set a writer to use for adding data."""
2070
if index is not None:
2071
self._indices[index] = transport_packname
2072
self._container_writer = writer
2073
self._write_index = index
2075
def reload_or_raise(self, retry_exc):
2076
"""Try calling the reload function, or re-raise the original exception.
2078
This should be called after _DirectPackAccess raises a
2079
RetryWithNewPacks exception. This function will handle the common logic
2080
of determining when the error is fatal versus being temporary.
2081
It will also make sure that the original exception is raised, rather
2082
than the RetryWithNewPacks exception.
2084
If this function returns, then the calling function should retry
2085
whatever operation was being performed. Otherwise an exception will
2088
:param retry_exc: A RetryWithNewPacks exception.
2091
if self._reload_func is None:
2093
elif not self._reload_func():
2094
# The reload claimed that nothing changed
2095
if not retry_exc.reload_occurred:
2096
# If there wasn't an earlier reload, then we really were
2097
# expecting to find changes. We didn't find them, so this is a
2101
# GZ 2017-03-27: No real reason this needs the original traceback.
2102
reraise(*retry_exc.exc_info)