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(), """
24
from itertools import izip
37
from breezy.bzr import (
41
from breezy.bzr.index import (
43
GraphIndexPrefixAdapter,
55
from ..decorators import (
60
from ..lock import LogicalLockResult
61
from ..repository import (
63
RepositoryWriteLockResult,
65
from ..bzr.repository import (
67
RepositoryFormatMetaDir,
69
from ..sixish import (
72
from ..bzr.vf_repository import (
73
MetaDirVersionedFileRepository,
74
MetaDirVersionedFileRepositoryFormat,
75
VersionedFileCommitBuilder,
76
VersionedFileRootCommitBuilder,
85
class PackCommitBuilder(VersionedFileCommitBuilder):
86
"""Subclass of VersionedFileCommitBuilder to add texts with pack semantics.
88
Specifically this uses one knit object rather than one knit object per
89
added text, reducing memory and object pressure.
92
def __init__(self, repository, parents, config, timestamp=None,
93
timezone=None, committer=None, revprops=None,
94
revision_id=None, lossy=False):
95
VersionedFileCommitBuilder.__init__(self, repository, parents, config,
96
timestamp=timestamp, timezone=timezone, committer=committer,
97
revprops=revprops, revision_id=revision_id, lossy=lossy)
98
self._file_graph = graph.Graph(
99
repository._pack_collection.text_index.combined_index)
101
def _heads(self, file_id, revision_ids):
102
keys = [(file_id, revision_id) for revision_id in revision_ids]
103
return {key[1] for key in self._file_graph.heads(keys)}
106
class PackRootCommitBuilder(VersionedFileRootCommitBuilder):
107
"""A subclass of RootCommitBuilder to add texts with pack semantics.
109
Specifically this uses one knit object rather than one knit object per
110
added text, reducing memory and object pressure.
113
def __init__(self, repository, parents, config, timestamp=None,
114
timezone=None, committer=None, revprops=None,
115
revision_id=None, lossy=False):
116
super(PackRootCommitBuilder, self).__init__(repository, parents,
117
config, timestamp=timestamp, timezone=timezone,
118
committer=committer, revprops=revprops, revision_id=revision_id,
120
self._file_graph = graph.Graph(
121
repository._pack_collection.text_index.combined_index)
123
def _heads(self, file_id, revision_ids):
124
keys = [(file_id, revision_id) for revision_id in revision_ids]
125
return {key[1] for key in self._file_graph.heads(keys)}
129
"""An in memory proxy for a pack and its indices.
131
This is a base class that is not directly used, instead the classes
132
ExistingPack and NewPack are used.
135
# A map of index 'type' to the file extension and position in the
137
index_definitions = {
139
'revision': ('.rix', 0),
140
'inventory': ('.iix', 1),
142
'signature': ('.six', 3),
145
def __init__(self, revision_index, inventory_index, text_index,
146
signature_index, chk_index=None):
147
"""Create a pack instance.
149
:param revision_index: A GraphIndex for determining what revisions are
150
present in the Pack and accessing the locations of their texts.
151
:param inventory_index: A GraphIndex for determining what inventories are
152
present in the Pack and accessing the locations of their
154
:param text_index: A GraphIndex for determining what file texts
155
are present in the pack and accessing the locations of their
156
texts/deltas (via (fileid, revisionid) tuples).
157
:param signature_index: A GraphIndex for determining what signatures are
158
present in the Pack and accessing the locations of their texts.
159
:param chk_index: A GraphIndex for accessing content by CHK, if the
162
self.revision_index = revision_index
163
self.inventory_index = inventory_index
164
self.text_index = text_index
165
self.signature_index = signature_index
166
self.chk_index = chk_index
168
def access_tuple(self):
169
"""Return a tuple (transport, name) for the pack content."""
170
return self.pack_transport, self.file_name()
172
def _check_references(self):
173
"""Make sure our external references are present.
175
Packs are allowed to have deltas whose base is not in the pack, but it
176
must be present somewhere in this collection. It is not allowed to
177
have deltas based on a fallback repository.
178
(See <https://bugs.launchpad.net/bzr/+bug/288751>)
181
for (index_name, external_refs, index) in [
183
self._get_external_refs(self.text_index),
184
self._pack_collection.text_index.combined_index),
186
self._get_external_refs(self.inventory_index),
187
self._pack_collection.inventory_index.combined_index),
189
missing = external_refs.difference(
190
k for (idx, k, v, r) in
191
index.iter_entries(external_refs))
193
missing_items[index_name] = sorted(list(missing))
195
from pprint import pformat
196
raise errors.BzrCheckError(
197
"Newly created pack file %r has delta references to "
198
"items not in its repository:\n%s"
199
% (self, pformat(missing_items)))
202
"""Get the file name for the pack on disk."""
203
return self.name + '.pack'
205
def get_revision_count(self):
206
return self.revision_index.key_count()
208
def index_name(self, index_type, name):
209
"""Get the disk name of an index type for pack name 'name'."""
210
return name + Pack.index_definitions[index_type][0]
212
def index_offset(self, index_type):
213
"""Get the position in a index_size array for a given index type."""
214
return Pack.index_definitions[index_type][1]
216
def inventory_index_name(self, name):
217
"""The inv index is the name + .iix."""
218
return self.index_name('inventory', name)
220
def revision_index_name(self, name):
221
"""The revision index is the name + .rix."""
222
return self.index_name('revision', name)
224
def signature_index_name(self, name):
225
"""The signature index is the name + .six."""
226
return self.index_name('signature', name)
228
def text_index_name(self, name):
229
"""The text index is the name + .tix."""
230
return self.index_name('text', name)
232
def _replace_index_with_readonly(self, index_type):
233
unlimited_cache = False
234
if index_type == 'chk':
235
unlimited_cache = True
236
index = self.index_class(self.index_transport,
237
self.index_name(index_type, self.name),
238
self.index_sizes[self.index_offset(index_type)],
239
unlimited_cache=unlimited_cache)
240
if index_type == 'chk':
241
index._leaf_factory = btree_index._gcchk_factory
242
setattr(self, index_type + '_index', index)
245
class ExistingPack(Pack):
246
"""An in memory proxy for an existing .pack and its disk indices."""
248
def __init__(self, pack_transport, name, revision_index, inventory_index,
249
text_index, signature_index, chk_index=None):
250
"""Create an ExistingPack object.
252
:param pack_transport: The transport where the pack file resides.
253
:param name: The name of the pack on disk in the pack_transport.
255
Pack.__init__(self, revision_index, inventory_index, text_index,
256
signature_index, chk_index)
258
self.pack_transport = pack_transport
259
if None in (revision_index, inventory_index, text_index,
260
signature_index, name, pack_transport):
261
raise AssertionError()
263
def __eq__(self, other):
264
return self.__dict__ == other.__dict__
266
def __ne__(self, other):
267
return not self.__eq__(other)
270
return "<%s.%s object at 0x%x, %s, %s" % (
271
self.__class__.__module__, self.__class__.__name__, id(self),
272
self.pack_transport, self.name)
275
class ResumedPack(ExistingPack):
277
def __init__(self, name, revision_index, inventory_index, text_index,
278
signature_index, upload_transport, pack_transport, index_transport,
279
pack_collection, chk_index=None):
280
"""Create a ResumedPack object."""
281
ExistingPack.__init__(self, pack_transport, name, revision_index,
282
inventory_index, text_index, signature_index,
284
self.upload_transport = upload_transport
285
self.index_transport = index_transport
286
self.index_sizes = [None, None, None, None]
288
('revision', revision_index),
289
('inventory', inventory_index),
290
('text', text_index),
291
('signature', signature_index),
293
if chk_index is not None:
294
indices.append(('chk', chk_index))
295
self.index_sizes.append(None)
296
for index_type, index in indices:
297
offset = self.index_offset(index_type)
298
self.index_sizes[offset] = index._size
299
self.index_class = pack_collection._index_class
300
self._pack_collection = pack_collection
301
self._state = 'resumed'
302
# XXX: perhaps check that the .pack file exists?
304
def access_tuple(self):
305
if self._state == 'finished':
306
return Pack.access_tuple(self)
307
elif self._state == 'resumed':
308
return self.upload_transport, self.file_name()
310
raise AssertionError(self._state)
313
self.upload_transport.delete(self.file_name())
314
indices = [self.revision_index, self.inventory_index, self.text_index,
315
self.signature_index]
316
if self.chk_index is not None:
317
indices.append(self.chk_index)
318
for index in indices:
319
index._transport.delete(index._name)
322
self._check_references()
323
index_types = ['revision', 'inventory', 'text', 'signature']
324
if self.chk_index is not None:
325
index_types.append('chk')
326
for index_type in index_types:
327
old_name = self.index_name(index_type, self.name)
328
new_name = '../indices/' + old_name
329
self.upload_transport.move(old_name, new_name)
330
self._replace_index_with_readonly(index_type)
331
new_name = '../packs/' + self.file_name()
332
self.upload_transport.move(self.file_name(), new_name)
333
self._state = 'finished'
335
def _get_external_refs(self, index):
336
"""Return compression parents for this index that are not present.
338
This returns any compression parents that are referenced by this index,
339
which are not contained *in* this index. They may be present elsewhere.
341
return index.external_references(1)
345
"""An in memory proxy for a pack which is being created."""
347
def __init__(self, pack_collection, upload_suffix='', file_mode=None):
348
"""Create a NewPack instance.
350
:param pack_collection: A PackCollection into which this is being inserted.
351
:param upload_suffix: An optional suffix to be given to any temporary
352
files created during the pack creation. e.g '.autopack'
353
:param file_mode: Unix permissions for newly created file.
355
# The relative locations of the packs are constrained, but all are
356
# passed in because the caller has them, so as to avoid object churn.
357
index_builder_class = pack_collection._index_builder_class
358
if pack_collection.chk_index is not None:
359
chk_index = index_builder_class(reference_lists=0)
363
# Revisions: parents list, no text compression.
364
index_builder_class(reference_lists=1),
365
# Inventory: We want to map compression only, but currently the
366
# knit code hasn't been updated enough to understand that, so we
367
# have a regular 2-list index giving parents and compression
369
index_builder_class(reference_lists=2),
370
# Texts: compression and per file graph, for all fileids - so two
371
# reference lists and two elements in the key tuple.
372
index_builder_class(reference_lists=2, key_elements=2),
373
# Signatures: Just blobs to store, no compression, no parents
375
index_builder_class(reference_lists=0),
376
# CHK based storage - just blobs, no compression or parents.
379
self._pack_collection = pack_collection
380
# When we make readonly indices, we need this.
381
self.index_class = pack_collection._index_class
382
# where should the new pack be opened
383
self.upload_transport = pack_collection._upload_transport
384
# where are indices written out to
385
self.index_transport = pack_collection._index_transport
386
# where is the pack renamed to when it is finished?
387
self.pack_transport = pack_collection._pack_transport
388
# What file mode to upload the pack and indices with.
389
self._file_mode = file_mode
390
# tracks the content written to the .pack file.
391
self._hash = osutils.md5()
392
# a tuple with the length in bytes of the indices, once the pack
393
# is finalised. (rev, inv, text, sigs, chk_if_in_use)
394
self.index_sizes = None
395
# How much data to cache when writing packs. Note that this is not
396
# synchronised with reads, because it's not in the transport layer, so
397
# is not safe unless the client knows it won't be reading from the pack
399
self._cache_limit = 0
400
# the temporary pack file name.
401
self.random_name = osutils.rand_chars(20) + upload_suffix
402
# when was this pack started ?
403
self.start_time = time.time()
404
# open an output stream for the data added to the pack.
405
self.write_stream = self.upload_transport.open_write_stream(
406
self.random_name, mode=self._file_mode)
407
if 'pack' in debug.debug_flags:
408
mutter('%s: create_pack: pack stream open: %s%s t+%6.3fs',
409
time.ctime(), self.upload_transport.base, self.random_name,
410
time.time() - self.start_time)
411
# A list of byte sequences to be written to the new pack, and the
412
# aggregate size of them. Stored as a list rather than separate
413
# variables so that the _write_data closure below can update them.
414
self._buffer = [[], 0]
415
# create a callable for adding data
417
# robertc says- this is a closure rather than a method on the object
418
# so that the variables are locals, and faster than accessing object
420
def _write_data(bytes, flush=False, _buffer=self._buffer,
421
_write=self.write_stream.write, _update=self._hash.update):
422
_buffer[0].append(bytes)
423
_buffer[1] += len(bytes)
425
if _buffer[1] > self._cache_limit or flush:
426
bytes = ''.join(_buffer[0])
430
# expose this on self, for the occasion when clients want to add data.
431
self._write_data = _write_data
432
# a pack writer object to serialise pack records.
433
self._writer = pack.ContainerWriter(self._write_data)
435
# what state is the pack in? (open, finished, aborted)
437
# no name until we finish writing the content
441
"""Cancel creating this pack."""
442
self._state = 'aborted'
443
self.write_stream.close()
444
# Remove the temporary pack file.
445
self.upload_transport.delete(self.random_name)
446
# The indices have no state on disk.
448
def access_tuple(self):
449
"""Return a tuple (transport, name) for the pack content."""
450
if self._state == 'finished':
451
return Pack.access_tuple(self)
452
elif self._state == 'open':
453
return self.upload_transport, self.random_name
455
raise AssertionError(self._state)
457
def data_inserted(self):
458
"""True if data has been added to this pack."""
459
return bool(self.get_revision_count() or
460
self.inventory_index.key_count() or
461
self.text_index.key_count() or
462
self.signature_index.key_count() or
463
(self.chk_index is not None and self.chk_index.key_count()))
465
def finish_content(self):
466
if self.name is not None:
470
self._write_data('', flush=True)
471
self.name = self._hash.hexdigest()
473
def finish(self, suspend=False):
474
"""Finish the new pack.
477
- finalises the content
478
- assigns a name (the md5 of the content, currently)
479
- writes out the associated indices
480
- renames the pack into place.
481
- stores the index size tuple for the pack in the index_sizes
484
self.finish_content()
486
self._check_references()
488
# XXX: It'd be better to write them all to temporary names, then
489
# rename them all into place, so that the window when only some are
490
# visible is smaller. On the other hand none will be seen until
491
# they're in the names list.
492
self.index_sizes = [None, None, None, None]
493
self._write_index('revision', self.revision_index, 'revision',
495
self._write_index('inventory', self.inventory_index, 'inventory',
497
self._write_index('text', self.text_index, 'file texts', suspend)
498
self._write_index('signature', self.signature_index,
499
'revision signatures', suspend)
500
if self.chk_index is not None:
501
self.index_sizes.append(None)
502
self._write_index('chk', self.chk_index,
503
'content hash bytes', suspend)
504
self.write_stream.close(
505
want_fdatasync=self._pack_collection.config_stack.get('repository.fdatasync'))
506
# Note that this will clobber an existing pack with the same name,
507
# without checking for hash collisions. While this is undesirable this
508
# is something that can be rectified in a subsequent release. One way
509
# to rectify it may be to leave the pack at the original name, writing
510
# its pack-names entry as something like 'HASH: index-sizes
511
# temporary-name'. Allocate that and check for collisions, if it is
512
# collision free then rename it into place. If clients know this scheme
513
# they can handle missing-file errors by:
514
# - try for HASH.pack
515
# - try for temporary-name
516
# - refresh the pack-list to see if the pack is now absent
517
new_name = self.name + '.pack'
519
new_name = '../packs/' + new_name
520
self.upload_transport.move(self.random_name, new_name)
521
self._state = 'finished'
522
if 'pack' in debug.debug_flags:
523
# XXX: size might be interesting?
524
mutter('%s: create_pack: pack finished: %s%s->%s t+%6.3fs',
525
time.ctime(), self.upload_transport.base, self.random_name,
526
new_name, time.time() - self.start_time)
529
"""Flush any current data."""
531
bytes = ''.join(self._buffer[0])
532
self.write_stream.write(bytes)
533
self._hash.update(bytes)
534
self._buffer[:] = [[], 0]
536
def _get_external_refs(self, index):
537
return index._external_references()
539
def set_write_cache_size(self, size):
540
self._cache_limit = size
542
def _write_index(self, index_type, index, label, suspend=False):
543
"""Write out an index.
545
:param index_type: The type of index to write - e.g. 'revision'.
546
:param index: The index object to serialise.
547
:param label: What label to give the index e.g. 'revision'.
549
index_name = self.index_name(index_type, self.name)
551
transport = self.upload_transport
553
transport = self.index_transport
554
index_tempfile = index.finish()
555
index_bytes = index_tempfile.read()
556
write_stream = transport.open_write_stream(index_name,
557
mode=self._file_mode)
558
write_stream.write(index_bytes)
560
want_fdatasync=self._pack_collection.config_stack.get('repository.fdatasync'))
561
self.index_sizes[self.index_offset(index_type)] = len(index_bytes)
562
if 'pack' in debug.debug_flags:
563
# XXX: size might be interesting?
564
mutter('%s: create_pack: wrote %s index: %s%s t+%6.3fs',
565
time.ctime(), label, self.upload_transport.base,
566
self.random_name, time.time() - self.start_time)
567
# Replace the writable index on this object with a readonly,
568
# presently unloaded index. We should alter
569
# the index layer to make its finish() error if add_node is
570
# subsequently used. RBC
571
self._replace_index_with_readonly(index_type)
574
class AggregateIndex(object):
575
"""An aggregated index for the RepositoryPackCollection.
577
AggregateIndex is reponsible for managing the PackAccess object,
578
Index-To-Pack mapping, and all indices list for a specific type of index
579
such as 'revision index'.
581
A CombinedIndex provides an index on a single key space built up
582
from several on-disk indices. The AggregateIndex builds on this
583
to provide a knit access layer, and allows having up to one writable
584
index within the collection.
586
# XXX: Probably 'can be written to' could/should be separated from 'acts
587
# like a knit index' -- mbp 20071024
589
def __init__(self, reload_func=None, flush_func=None):
590
"""Create an AggregateIndex.
592
:param reload_func: A function to call if we find we are missing an
593
index. Should have the form reload_func() => True if the list of
594
active pack files has changed.
596
self._reload_func = reload_func
597
self.index_to_pack = {}
598
self.combined_index = CombinedGraphIndex([], reload_func=reload_func)
599
self.data_access = _DirectPackAccess(self.index_to_pack,
600
reload_func=reload_func,
601
flush_func=flush_func)
602
self.add_callback = None
604
def add_index(self, index, pack):
605
"""Add index to the aggregate, which is an index for Pack pack.
607
Future searches on the aggregate index will seach this new index
608
before all previously inserted indices.
610
:param index: An Index for the pack.
611
:param pack: A Pack instance.
613
# expose it to the index map
614
self.index_to_pack[index] = pack.access_tuple()
615
# put it at the front of the linear index list
616
self.combined_index.insert_index(0, index, pack.name)
618
def add_writable_index(self, index, pack):
619
"""Add an index which is able to have data added to it.
621
There can be at most one writable index at any time. Any
622
modifications made to the knit are put into this index.
624
:param index: An index from the pack parameter.
625
:param pack: A Pack instance.
627
if self.add_callback is not None:
628
raise AssertionError(
629
"%s already has a writable index through %s" % \
630
(self, self.add_callback))
631
# allow writing: queue writes to a new index
632
self.add_index(index, pack)
633
# Updates the index to packs mapping as a side effect,
634
self.data_access.set_writer(pack._writer, index, pack.access_tuple())
635
self.add_callback = index.add_nodes
638
"""Reset all the aggregate data to nothing."""
639
self.data_access.set_writer(None, None, (None, None))
640
self.index_to_pack.clear()
641
del self.combined_index._indices[:]
642
del self.combined_index._index_names[:]
643
self.add_callback = None
645
def remove_index(self, index):
646
"""Remove index from the indices used to answer queries.
648
:param index: An index from the pack parameter.
650
del self.index_to_pack[index]
651
pos = self.combined_index._indices.index(index)
652
del self.combined_index._indices[pos]
653
del self.combined_index._index_names[pos]
654
if (self.add_callback is not None and
655
getattr(index, 'add_nodes', None) == self.add_callback):
656
self.add_callback = None
657
self.data_access.set_writer(None, None, (None, None))
660
class Packer(object):
661
"""Create a pack from packs."""
663
def __init__(self, pack_collection, packs, suffix, revision_ids=None,
667
:param pack_collection: A RepositoryPackCollection object where the
668
new pack is being written to.
669
:param packs: The packs to combine.
670
:param suffix: The suffix to use on the temporary files for the pack.
671
:param revision_ids: Revision ids to limit the pack to.
672
:param reload_func: A function to call if a pack file/index goes
673
missing. The side effect of calling this function should be to
674
update self.packs. See also AggregateIndex
678
self.revision_ids = revision_ids
679
# The pack object we are creating.
681
self._pack_collection = pack_collection
682
self._reload_func = reload_func
683
# The index layer keys for the revisions being copied. None for 'all
685
self._revision_keys = None
686
# What text keys to copy. None for 'all texts'. This is set by
687
# _copy_inventory_texts
688
self._text_filter = None
690
def pack(self, pb=None):
691
"""Create a new pack by reading data from other packs.
693
This does little more than a bulk copy of data. One key difference
694
is that data with the same item key across multiple packs is elided
695
from the output. The new pack is written into the current pack store
696
along with its indices, and the name added to the pack names. The
697
source packs are not altered and are not required to be in the current
700
:param pb: An optional progress bar to use. A nested bar is created if
702
:return: A Pack object, or None if nothing was copied.
704
# open a pack - using the same name as the last temporary file
705
# - which has already been flushed, so it's safe.
706
# XXX: - duplicate code warning with start_write_group; fix before
707
# considering 'done'.
708
if self._pack_collection._new_pack is not None:
709
raise errors.BzrError('call to %s.pack() while another pack is'
711
% (self.__class__.__name__,))
712
if self.revision_ids is not None:
713
if len(self.revision_ids) == 0:
714
# silly fetch request.
717
self.revision_ids = frozenset(self.revision_ids)
718
self.revision_keys = frozenset((revid,) for revid in
721
self.pb = ui.ui_factory.nested_progress_bar()
725
return self._create_pack_from_packs()
731
"""Open a pack for the pack we are creating."""
732
new_pack = self._pack_collection.pack_factory(self._pack_collection,
733
upload_suffix=self.suffix,
734
file_mode=self._pack_collection.repo.bzrdir._get_file_mode())
735
# We know that we will process all nodes in order, and don't need to
736
# query, so don't combine any indices spilled to disk until we are done
737
new_pack.revision_index.set_optimize(combine_backing_indices=False)
738
new_pack.inventory_index.set_optimize(combine_backing_indices=False)
739
new_pack.text_index.set_optimize(combine_backing_indices=False)
740
new_pack.signature_index.set_optimize(combine_backing_indices=False)
743
def _copy_revision_texts(self):
744
"""Copy revision data to the new pack."""
745
raise NotImplementedError(self._copy_revision_texts)
747
def _copy_inventory_texts(self):
748
"""Copy the inventory texts to the new pack.
750
self._revision_keys is used to determine what inventories to copy.
752
Sets self._text_filter appropriately.
754
raise NotImplementedError(self._copy_inventory_texts)
756
def _copy_text_texts(self):
757
raise NotImplementedError(self._copy_text_texts)
759
def _create_pack_from_packs(self):
760
raise NotImplementedError(self._create_pack_from_packs)
762
def _log_copied_texts(self):
763
if 'pack' in debug.debug_flags:
764
mutter('%s: create_pack: file texts copied: %s%s %d items t+%6.3fs',
765
time.ctime(), self._pack_collection._upload_transport.base,
766
self.new_pack.random_name,
767
self.new_pack.text_index.key_count(),
768
time.time() - self.new_pack.start_time)
770
def _use_pack(self, new_pack):
771
"""Return True if new_pack should be used.
773
:param new_pack: The pack that has just been created.
774
:return: True if the pack should be used.
776
return new_pack.data_inserted()
779
class RepositoryPackCollection(object):
780
"""Management of packs within a repository.
782
:ivar _names: map of {pack_name: (index_size,)}
786
resumed_pack_factory = None
787
normal_packer_class = None
788
optimising_packer_class = None
790
def __init__(self, repo, transport, index_transport, upload_transport,
791
pack_transport, index_builder_class, index_class,
793
"""Create a new RepositoryPackCollection.
795
:param transport: Addresses the repository base directory
796
(typically .bzr/repository/).
797
:param index_transport: Addresses the directory containing indices.
798
:param upload_transport: Addresses the directory into which packs are written
799
while they're being created.
800
:param pack_transport: Addresses the directory of existing complete packs.
801
:param index_builder_class: The index builder class to use.
802
:param index_class: The index class to use.
803
:param use_chk_index: Whether to setup and manage a CHK index.
805
# XXX: This should call self.reset()
807
self.transport = transport
808
self._index_transport = index_transport
809
self._upload_transport = upload_transport
810
self._pack_transport = pack_transport
811
self._index_builder_class = index_builder_class
812
self._index_class = index_class
813
self._suffix_offsets = {'.rix': 0, '.iix': 1, '.tix': 2, '.six': 3,
818
self._packs_by_name = {}
819
# the previous pack-names content
820
self._packs_at_load = None
821
# when a pack is being created by this object, the state of that pack.
822
self._new_pack = None
823
# aggregated revision index data
824
flush = self._flush_new_pack
825
self.revision_index = AggregateIndex(self.reload_pack_names, flush)
826
self.inventory_index = AggregateIndex(self.reload_pack_names, flush)
827
self.text_index = AggregateIndex(self.reload_pack_names, flush)
828
self.signature_index = AggregateIndex(self.reload_pack_names, flush)
829
all_indices = [self.revision_index, self.inventory_index,
830
self.text_index, self.signature_index]
832
self.chk_index = AggregateIndex(self.reload_pack_names, flush)
833
all_indices.append(self.chk_index)
835
# used to determine if we're using a chk_index elsewhere.
836
self.chk_index = None
837
# Tell all the CombinedGraphIndex objects about each other, so they can
838
# share hints about which pack names to search first.
839
all_combined = [agg_idx.combined_index for agg_idx in all_indices]
840
for combined_idx in all_combined:
841
combined_idx.set_sibling_indices(
842
set(all_combined).difference([combined_idx]))
844
self._resumed_packs = []
845
self.config_stack = config.LocationStack(self.transport.base)
848
return '%s(%r)' % (self.__class__.__name__, self.repo)
850
def add_pack_to_memory(self, pack):
851
"""Make a Pack object available to the repository to satisfy queries.
853
:param pack: A Pack object.
855
if pack.name in self._packs_by_name:
856
raise AssertionError(
857
'pack %s already in _packs_by_name' % (pack.name,))
858
self.packs.append(pack)
859
self._packs_by_name[pack.name] = pack
860
self.revision_index.add_index(pack.revision_index, pack)
861
self.inventory_index.add_index(pack.inventory_index, pack)
862
self.text_index.add_index(pack.text_index, pack)
863
self.signature_index.add_index(pack.signature_index, pack)
864
if self.chk_index is not None:
865
self.chk_index.add_index(pack.chk_index, pack)
868
"""Return a list of all the Pack objects this repository has.
870
Note that an in-progress pack being created is not returned.
872
:return: A list of Pack objects for all the packs in the repository.
875
for name in self.names():
876
result.append(self.get_pack_by_name(name))
880
"""Pack the pack collection incrementally.
882
This will not attempt global reorganisation or recompression,
883
rather it will just ensure that the total number of packs does
884
not grow without bound. It uses the _max_pack_count method to
885
determine if autopacking is needed, and the pack_distribution
886
method to determine the number of revisions in each pack.
888
If autopacking takes place then the packs name collection will have
889
been flushed to disk - packing requires updating the name collection
890
in synchronisation with certain steps. Otherwise the names collection
893
:return: Something evaluating true if packing took place.
897
return self._do_autopack()
898
except errors.RetryAutopack:
899
# If we get a RetryAutopack exception, we should abort the
900
# current action, and retry.
903
def _do_autopack(self):
904
# XXX: Should not be needed when the management of indices is sane.
905
total_revisions = self.revision_index.combined_index.key_count()
906
total_packs = len(self._names)
907
if self._max_pack_count(total_revisions) >= total_packs:
909
# determine which packs need changing
910
pack_distribution = self.pack_distribution(total_revisions)
912
for pack in self.all_packs():
913
revision_count = pack.get_revision_count()
914
if revision_count == 0:
915
# revision less packs are not generated by normal operation,
916
# only by operations like sign-my-commits, and thus will not
917
# tend to grow rapdily or without bound like commit containing
918
# packs do - leave them alone as packing them really should
919
# group their data with the relevant commit, and that may
920
# involve rewriting ancient history - which autopack tries to
921
# avoid. Alternatively we could not group the data but treat
922
# each of these as having a single revision, and thus add
923
# one revision for each to the total revision count, to get
924
# a matching distribution.
926
existing_packs.append((revision_count, pack))
927
pack_operations = self.plan_autopack_combinations(
928
existing_packs, pack_distribution)
929
num_new_packs = len(pack_operations)
930
num_old_packs = sum([len(po[1]) for po in pack_operations])
931
num_revs_affected = sum([po[0] for po in pack_operations])
932
mutter('Auto-packing repository %s, which has %d pack files, '
933
'containing %d revisions. Packing %d files into %d affecting %d'
934
' revisions', self, total_packs, total_revisions, num_old_packs,
935
num_new_packs, num_revs_affected)
936
result = self._execute_pack_operations(pack_operations, packer_class=self.normal_packer_class,
937
reload_func=self._restart_autopack)
938
mutter('Auto-packing repository %s completed', self)
941
def _execute_pack_operations(self, pack_operations, packer_class,
943
"""Execute a series of pack operations.
945
:param pack_operations: A list of [revision_count, packs_to_combine].
946
:param packer_class: The class of packer to use
947
:return: The new pack names.
949
for revision_count, packs in pack_operations:
950
# we may have no-ops from the setup logic
953
packer = packer_class(self, packs, '.autopack',
954
reload_func=reload_func)
956
result = packer.pack()
957
except errors.RetryWithNewPacks:
958
# An exception is propagating out of this context, make sure
959
# this packer has cleaned up. Packer() doesn't set its new_pack
960
# state into the RepositoryPackCollection object, so we only
961
# have access to it directly here.
962
if packer.new_pack is not None:
963
packer.new_pack.abort()
968
self._remove_pack_from_memory(pack)
969
# record the newly available packs and stop advertising the old
972
for _, packs in pack_operations:
973
to_be_obsoleted.extend(packs)
974
result = self._save_pack_names(clear_obsolete_packs=True,
975
obsolete_packs=to_be_obsoleted)
978
def _flush_new_pack(self):
979
if self._new_pack is not None:
980
self._new_pack.flush()
982
def lock_names(self):
983
"""Acquire the mutex around the pack-names index.
985
This cannot be used in the middle of a read-only transaction on the
988
self.repo.control_files.lock_write()
990
def _already_packed(self):
991
"""Is the collection already packed?"""
992
return not (self.repo._format.pack_compresses or (len(self._names) > 1))
994
def pack(self, hint=None, clean_obsolete_packs=False):
995
"""Pack the pack collection totally."""
997
total_packs = len(self._names)
998
if self._already_packed():
1000
total_revisions = self.revision_index.combined_index.key_count()
1001
# XXX: the following may want to be a class, to pack with a given
1003
mutter('Packing repository %s, which has %d pack files, '
1004
'containing %d revisions with hint %r.', self, total_packs,
1005
total_revisions, hint)
1008
self._try_pack_operations(hint)
1009
except RetryPackOperations:
1013
if clean_obsolete_packs:
1014
self._clear_obsolete_packs()
1016
def _try_pack_operations(self, hint):
1017
"""Calculate the pack operations based on the hint (if any), and
1020
# determine which packs need changing
1021
pack_operations = [[0, []]]
1022
for pack in self.all_packs():
1023
if hint is None or pack.name in hint:
1024
# Either no hint was provided (so we are packing everything),
1025
# or this pack was included in the hint.
1026
pack_operations[-1][0] += pack.get_revision_count()
1027
pack_operations[-1][1].append(pack)
1028
self._execute_pack_operations(pack_operations,
1029
packer_class=self.optimising_packer_class,
1030
reload_func=self._restart_pack_operations)
1032
def plan_autopack_combinations(self, existing_packs, pack_distribution):
1033
"""Plan a pack operation.
1035
:param existing_packs: The packs to pack. (A list of (revcount, Pack)
1037
:param pack_distribution: A list with the number of revisions desired
1040
if len(existing_packs) <= len(pack_distribution):
1042
existing_packs.sort(reverse=True)
1043
pack_operations = [[0, []]]
1044
# plan out what packs to keep, and what to reorganise
1045
while len(existing_packs):
1046
# take the largest pack, and if it's less than the head of the
1047
# distribution chart we will include its contents in the new pack
1048
# for that position. If it's larger, we remove its size from the
1049
# distribution chart
1050
next_pack_rev_count, next_pack = existing_packs.pop(0)
1051
if next_pack_rev_count >= pack_distribution[0]:
1052
# this is already packed 'better' than this, so we can
1053
# not waste time packing it.
1054
while next_pack_rev_count > 0:
1055
next_pack_rev_count -= pack_distribution[0]
1056
if next_pack_rev_count >= 0:
1058
del pack_distribution[0]
1060
# didn't use that entire bucket up
1061
pack_distribution[0] = -next_pack_rev_count
1063
# add the revisions we're going to add to the next output pack
1064
pack_operations[-1][0] += next_pack_rev_count
1065
# allocate this pack to the next pack sub operation
1066
pack_operations[-1][1].append(next_pack)
1067
if pack_operations[-1][0] >= pack_distribution[0]:
1068
# this pack is used up, shift left.
1069
del pack_distribution[0]
1070
pack_operations.append([0, []])
1071
# Now that we know which pack files we want to move, shove them all
1072
# into a single pack file.
1074
final_pack_list = []
1075
for num_revs, pack_files in pack_operations:
1076
final_rev_count += num_revs
1077
final_pack_list.extend(pack_files)
1078
if len(final_pack_list) == 1:
1079
raise AssertionError('We somehow generated an autopack with a'
1080
' single pack file being moved.')
1082
return [[final_rev_count, final_pack_list]]
1084
def ensure_loaded(self):
1085
"""Ensure we have read names from disk.
1087
:return: True if the disk names had not been previously read.
1089
# NB: if you see an assertion error here, it's probably access against
1090
# an unlocked repo. Naughty.
1091
if not self.repo.is_locked():
1092
raise errors.ObjectNotLocked(self.repo)
1093
if self._names is None:
1095
self._packs_at_load = set()
1096
for index, key, value in self._iter_disk_pack_index():
1098
self._names[name] = self._parse_index_sizes(value)
1099
self._packs_at_load.add((key, value))
1103
# populate all the metadata.
1107
def _parse_index_sizes(self, value):
1108
"""Parse a string of index sizes."""
1109
return tuple([int(digits) for digits in value.split(' ')])
1111
def get_pack_by_name(self, name):
1112
"""Get a Pack object by name.
1114
:param name: The name of the pack - e.g. '123456'
1115
:return: A Pack object.
1118
return self._packs_by_name[name]
1120
rev_index = self._make_index(name, '.rix')
1121
inv_index = self._make_index(name, '.iix')
1122
txt_index = self._make_index(name, '.tix')
1123
sig_index = self._make_index(name, '.six')
1124
if self.chk_index is not None:
1125
chk_index = self._make_index(name, '.cix', is_chk=True)
1128
result = ExistingPack(self._pack_transport, name, rev_index,
1129
inv_index, txt_index, sig_index, chk_index)
1130
self.add_pack_to_memory(result)
1133
def _resume_pack(self, name):
1134
"""Get a suspended Pack object by name.
1136
:param name: The name of the pack - e.g. '123456'
1137
:return: A Pack object.
1139
if not re.match('[a-f0-9]{32}', name):
1140
# Tokens should be md5sums of the suspended pack file, i.e. 32 hex
1142
raise errors.UnresumableWriteGroup(
1143
self.repo, [name], 'Malformed write group token')
1145
rev_index = self._make_index(name, '.rix', resume=True)
1146
inv_index = self._make_index(name, '.iix', resume=True)
1147
txt_index = self._make_index(name, '.tix', resume=True)
1148
sig_index = self._make_index(name, '.six', resume=True)
1149
if self.chk_index is not None:
1150
chk_index = self._make_index(name, '.cix', resume=True,
1154
result = self.resumed_pack_factory(name, rev_index, inv_index,
1155
txt_index, sig_index, self._upload_transport,
1156
self._pack_transport, self._index_transport, self,
1157
chk_index=chk_index)
1158
except errors.NoSuchFile as e:
1159
raise errors.UnresumableWriteGroup(self.repo, [name], str(e))
1160
self.add_pack_to_memory(result)
1161
self._resumed_packs.append(result)
1164
def allocate(self, a_new_pack):
1165
"""Allocate name in the list of packs.
1167
:param a_new_pack: A NewPack instance to be added to the collection of
1168
packs for this repository.
1170
self.ensure_loaded()
1171
if a_new_pack.name in self._names:
1172
raise errors.BzrError(
1173
'Pack %r already exists in %s' % (a_new_pack.name, self))
1174
self._names[a_new_pack.name] = tuple(a_new_pack.index_sizes)
1175
self.add_pack_to_memory(a_new_pack)
1177
def _iter_disk_pack_index(self):
1178
"""Iterate over the contents of the pack-names index.
1180
This is used when loading the list from disk, and before writing to
1181
detect updates from others during our write operation.
1182
:return: An iterator of the index contents.
1184
return self._index_class(self.transport, 'pack-names', None
1185
).iter_all_entries()
1187
def _make_index(self, name, suffix, resume=False, is_chk=False):
1188
size_offset = self._suffix_offsets[suffix]
1189
index_name = name + suffix
1191
transport = self._upload_transport
1192
index_size = transport.stat(index_name).st_size
1194
transport = self._index_transport
1195
index_size = self._names[name][size_offset]
1196
index = self._index_class(transport, index_name, index_size,
1197
unlimited_cache=is_chk)
1198
if is_chk and self._index_class is btree_index.BTreeGraphIndex:
1199
index._leaf_factory = btree_index._gcchk_factory
1202
def _max_pack_count(self, total_revisions):
1203
"""Return the maximum number of packs to use for total revisions.
1205
:param total_revisions: The total number of revisions in the
1208
if not total_revisions:
1210
digits = str(total_revisions)
1212
for digit in digits:
1213
result += int(digit)
1217
"""Provide an order to the underlying names."""
1218
return sorted(self._names.keys())
1220
def _obsolete_packs(self, packs):
1221
"""Move a number of packs which have been obsoleted out of the way.
1223
Each pack and its associated indices are moved out of the way.
1225
Note: for correctness this function should only be called after a new
1226
pack names index has been written without these pack names, and with
1227
the names of packs that contain the data previously available via these
1230
:param packs: The packs to obsolete.
1231
:param return: None.
1236
pack.pack_transport.move(pack.file_name(),
1237
'../obsolete_packs/' + pack.file_name())
1238
except errors.NoSuchFile:
1239
# perhaps obsolete_packs was removed? Let's create it and
1242
pack.pack_transport.mkdir('../obsolete_packs/')
1243
except errors.FileExists:
1245
pack.pack_transport.move(pack.file_name(),
1246
'../obsolete_packs/' + pack.file_name())
1247
except (errors.PathError, errors.TransportError) as e:
1248
# TODO: Should these be warnings or mutters?
1249
mutter("couldn't rename obsolete pack, skipping it:\n%s"
1251
# TODO: Probably needs to know all possible indices for this pack
1252
# - or maybe list the directory and move all indices matching this
1253
# name whether we recognize it or not?
1254
suffixes = ['.iix', '.six', '.tix', '.rix']
1255
if self.chk_index is not None:
1256
suffixes.append('.cix')
1257
for suffix in suffixes:
1259
self._index_transport.move(pack.name + suffix,
1260
'../obsolete_packs/' + pack.name + suffix)
1261
except (errors.PathError, errors.TransportError) as e:
1262
mutter("couldn't rename obsolete index, skipping it:\n%s"
1265
def pack_distribution(self, total_revisions):
1266
"""Generate a list of the number of revisions to put in each pack.
1268
:param total_revisions: The total number of revisions in the
1271
if total_revisions == 0:
1273
digits = reversed(str(total_revisions))
1275
for exponent, count in enumerate(digits):
1276
size = 10 ** exponent
1277
for pos in range(int(count)):
1279
return list(reversed(result))
1281
def _pack_tuple(self, name):
1282
"""Return a tuple with the transport and file name for a pack name."""
1283
return self._pack_transport, name + '.pack'
1285
def _remove_pack_from_memory(self, pack):
1286
"""Remove pack from the packs accessed by this repository.
1288
Only affects memory state, until self._save_pack_names() is invoked.
1290
self._names.pop(pack.name)
1291
self._packs_by_name.pop(pack.name)
1292
self._remove_pack_indices(pack)
1293
self.packs.remove(pack)
1295
def _remove_pack_indices(self, pack, ignore_missing=False):
1296
"""Remove the indices for pack from the aggregated indices.
1298
:param ignore_missing: Suppress KeyErrors from calling remove_index.
1300
for index_type in Pack.index_definitions:
1301
attr_name = index_type + '_index'
1302
aggregate_index = getattr(self, attr_name)
1303
if aggregate_index is not None:
1304
pack_index = getattr(pack, attr_name)
1306
aggregate_index.remove_index(pack_index)
1313
"""Clear all cached data."""
1314
# cached revision data
1315
self.revision_index.clear()
1316
# cached signature data
1317
self.signature_index.clear()
1318
# cached file text data
1319
self.text_index.clear()
1320
# cached inventory data
1321
self.inventory_index.clear()
1323
if self.chk_index is not None:
1324
self.chk_index.clear()
1325
# remove the open pack
1326
self._new_pack = None
1327
# information about packs.
1330
self._packs_by_name = {}
1331
self._packs_at_load = None
1333
def _unlock_names(self):
1334
"""Release the mutex around the pack-names index."""
1335
self.repo.control_files.unlock()
1337
def _diff_pack_names(self):
1338
"""Read the pack names from disk, and compare it to the one in memory.
1340
:return: (disk_nodes, deleted_nodes, new_nodes)
1341
disk_nodes The final set of nodes that should be referenced
1342
deleted_nodes Nodes which have been removed from when we started
1343
new_nodes Nodes that are newly introduced
1345
# load the disk nodes across
1347
for index, key, value in self._iter_disk_pack_index():
1348
disk_nodes.add((key, value))
1349
orig_disk_nodes = set(disk_nodes)
1351
# do a two-way diff against our original content
1352
current_nodes = set()
1353
for name, sizes in self._names.items():
1355
((name, ), ' '.join(str(size) for size in sizes)))
1357
# Packs no longer present in the repository, which were present when we
1358
# locked the repository
1359
deleted_nodes = self._packs_at_load - current_nodes
1360
# Packs which this process is adding
1361
new_nodes = current_nodes - self._packs_at_load
1363
# Update the disk_nodes set to include the ones we are adding, and
1364
# remove the ones which were removed by someone else
1365
disk_nodes.difference_update(deleted_nodes)
1366
disk_nodes.update(new_nodes)
1368
return disk_nodes, deleted_nodes, new_nodes, orig_disk_nodes
1370
def _syncronize_pack_names_from_disk_nodes(self, disk_nodes):
1371
"""Given the correct set of pack files, update our saved info.
1373
:return: (removed, added, modified)
1374
removed pack names removed from self._names
1375
added pack names added to self._names
1376
modified pack names that had changed value
1381
## self._packs_at_load = disk_nodes
1382
new_names = dict(disk_nodes)
1383
# drop no longer present nodes
1384
for pack in self.all_packs():
1385
if (pack.name,) not in new_names:
1386
removed.append(pack.name)
1387
self._remove_pack_from_memory(pack)
1388
# add new nodes/refresh existing ones
1389
for key, value in disk_nodes:
1391
sizes = self._parse_index_sizes(value)
1392
if name in self._names:
1394
if sizes != self._names[name]:
1395
# the pack for name has had its indices replaced - rare but
1396
# important to handle. XXX: probably can never happen today
1397
# because the three-way merge code above does not handle it
1398
# - you may end up adding the same key twice to the new
1399
# disk index because the set values are the same, unless
1400
# the only index shows up as deleted by the set difference
1401
# - which it may. Until there is a specific test for this,
1402
# assume it's broken. RBC 20071017.
1403
self._remove_pack_from_memory(self.get_pack_by_name(name))
1404
self._names[name] = sizes
1405
self.get_pack_by_name(name)
1406
modified.append(name)
1409
self._names[name] = sizes
1410
self.get_pack_by_name(name)
1412
return removed, added, modified
1414
def _save_pack_names(self, clear_obsolete_packs=False, obsolete_packs=None):
1415
"""Save the list of packs.
1417
This will take out the mutex around the pack names list for the
1418
duration of the method call. If concurrent updates have been made, a
1419
three-way merge between the current list and the current in memory list
1422
:param clear_obsolete_packs: If True, clear out the contents of the
1423
obsolete_packs directory.
1424
:param obsolete_packs: Packs that are obsolete once the new pack-names
1425
file has been written.
1426
:return: A list of the names saved that were not previously on disk.
1428
already_obsolete = []
1431
builder = self._index_builder_class()
1432
(disk_nodes, deleted_nodes, new_nodes,
1433
orig_disk_nodes) = self._diff_pack_names()
1434
# TODO: handle same-name, index-size-changes here -
1435
# e.g. use the value from disk, not ours, *unless* we're the one
1437
for key, value in disk_nodes:
1438
builder.add_node(key, value)
1439
self.transport.put_file('pack-names', builder.finish(),
1440
mode=self.repo.bzrdir._get_file_mode())
1441
self._packs_at_load = disk_nodes
1442
if clear_obsolete_packs:
1445
to_preserve = {o.name for o in obsolete_packs}
1446
already_obsolete = self._clear_obsolete_packs(to_preserve)
1448
self._unlock_names()
1449
# synchronise the memory packs list with what we just wrote:
1450
self._syncronize_pack_names_from_disk_nodes(disk_nodes)
1452
# TODO: We could add one more condition here. "if o.name not in
1453
# orig_disk_nodes and o != the new_pack we haven't written to
1454
# disk yet. However, the new pack object is not easily
1455
# accessible here (it would have to be passed through the
1456
# autopacking code, etc.)
1457
obsolete_packs = [o for o in obsolete_packs
1458
if o.name not in already_obsolete]
1459
self._obsolete_packs(obsolete_packs)
1460
return [new_node[0][0] for new_node in new_nodes]
1462
def reload_pack_names(self):
1463
"""Sync our pack listing with what is present in the repository.
1465
This should be called when we find out that something we thought was
1466
present is now missing. This happens when another process re-packs the
1469
:return: True if the in-memory list of packs has been altered at all.
1471
# The ensure_loaded call is to handle the case where the first call
1472
# made involving the collection was to reload_pack_names, where we
1473
# don't have a view of disk contents. It's a bit of a bandaid, and
1474
# causes two reads of pack-names, but it's a rare corner case not
1475
# struck with regular push/pull etc.
1476
first_read = self.ensure_loaded()
1479
# out the new value.
1480
(disk_nodes, deleted_nodes, new_nodes,
1481
orig_disk_nodes) = self._diff_pack_names()
1482
# _packs_at_load is meant to be the explicit list of names in
1483
# 'pack-names' at then start. As such, it should not contain any
1484
# pending names that haven't been written out yet.
1485
self._packs_at_load = orig_disk_nodes
1487
modified) = self._syncronize_pack_names_from_disk_nodes(disk_nodes)
1488
if removed or added or modified:
1492
def _restart_autopack(self):
1493
"""Reload the pack names list, and restart the autopack code."""
1494
if not self.reload_pack_names():
1495
# Re-raise the original exception, because something went missing
1496
# and a restart didn't find it
1498
raise errors.RetryAutopack(self.repo, False, sys.exc_info())
1500
def _restart_pack_operations(self):
1501
"""Reload the pack names list, and restart the autopack code."""
1502
if not self.reload_pack_names():
1503
# Re-raise the original exception, because something went missing
1504
# and a restart didn't find it
1506
raise RetryPackOperations(self.repo, False, sys.exc_info())
1508
def _clear_obsolete_packs(self, preserve=None):
1509
"""Delete everything from the obsolete-packs directory.
1511
:return: A list of pack identifiers (the filename without '.pack') that
1512
were found in obsolete_packs.
1515
obsolete_pack_transport = self.transport.clone('obsolete_packs')
1516
if preserve is None:
1519
obsolete_pack_files = obsolete_pack_transport.list_dir('.')
1520
except errors.NoSuchFile:
1522
for filename in obsolete_pack_files:
1523
name, ext = osutils.splitext(filename)
1526
if name in preserve:
1529
obsolete_pack_transport.delete(filename)
1530
except (errors.PathError, errors.TransportError) as e:
1531
warning("couldn't delete obsolete pack, skipping it:\n%s"
1535
def _start_write_group(self):
1536
# Do not permit preparation for writing if we're not in a 'write lock'.
1537
if not self.repo.is_write_locked():
1538
raise errors.NotWriteLocked(self)
1539
self._new_pack = self.pack_factory(self, upload_suffix='.pack',
1540
file_mode=self.repo.bzrdir._get_file_mode())
1541
# allow writing: queue writes to a new index
1542
self.revision_index.add_writable_index(self._new_pack.revision_index,
1544
self.inventory_index.add_writable_index(self._new_pack.inventory_index,
1546
self.text_index.add_writable_index(self._new_pack.text_index,
1548
self._new_pack.text_index.set_optimize(combine_backing_indices=False)
1549
self.signature_index.add_writable_index(self._new_pack.signature_index,
1551
if self.chk_index is not None:
1552
self.chk_index.add_writable_index(self._new_pack.chk_index,
1554
self.repo.chk_bytes._index._add_callback = self.chk_index.add_callback
1555
self._new_pack.chk_index.set_optimize(combine_backing_indices=False)
1557
self.repo.inventories._index._add_callback = self.inventory_index.add_callback
1558
self.repo.revisions._index._add_callback = self.revision_index.add_callback
1559
self.repo.signatures._index._add_callback = self.signature_index.add_callback
1560
self.repo.texts._index._add_callback = self.text_index.add_callback
1562
def _abort_write_group(self):
1563
# FIXME: just drop the transient index.
1564
# forget what names there are
1565
if self._new_pack is not None:
1566
operation = cleanup.OperationWithCleanups(self._new_pack.abort)
1567
operation.add_cleanup(setattr, self, '_new_pack', None)
1568
# If we aborted while in the middle of finishing the write
1569
# group, _remove_pack_indices could fail because the indexes are
1570
# already gone. But they're not there we shouldn't fail in this
1571
# case, so we pass ignore_missing=True.
1572
operation.add_cleanup(self._remove_pack_indices, self._new_pack,
1573
ignore_missing=True)
1574
operation.run_simple()
1575
for resumed_pack in self._resumed_packs:
1576
operation = cleanup.OperationWithCleanups(resumed_pack.abort)
1577
# See comment in previous finally block.
1578
operation.add_cleanup(self._remove_pack_indices, resumed_pack,
1579
ignore_missing=True)
1580
operation.run_simple()
1581
del self._resumed_packs[:]
1583
def _remove_resumed_pack_indices(self):
1584
for resumed_pack in self._resumed_packs:
1585
self._remove_pack_indices(resumed_pack)
1586
del self._resumed_packs[:]
1588
def _check_new_inventories(self):
1589
"""Detect missing inventories in this write group.
1591
:returns: list of strs, summarising any problems found. If the list is
1592
empty no problems were found.
1594
# The base implementation does no checks. GCRepositoryPackCollection
1598
def _commit_write_group(self):
1600
for prefix, versioned_file in (
1601
('revisions', self.repo.revisions),
1602
('inventories', self.repo.inventories),
1603
('texts', self.repo.texts),
1604
('signatures', self.repo.signatures),
1606
missing = versioned_file.get_missing_compression_parent_keys()
1607
all_missing.update([(prefix,) + key for key in missing])
1609
raise errors.BzrCheckError(
1610
"Repository %s has missing compression parent(s) %r "
1611
% (self.repo, sorted(all_missing)))
1612
problems = self._check_new_inventories()
1614
problems_summary = '\n'.join(problems)
1615
raise errors.BzrCheckError(
1616
"Cannot add revision(s) to repository: " + problems_summary)
1617
self._remove_pack_indices(self._new_pack)
1618
any_new_content = False
1619
if self._new_pack.data_inserted():
1620
# get all the data to disk and read to use
1621
self._new_pack.finish()
1622
self.allocate(self._new_pack)
1623
self._new_pack = None
1624
any_new_content = True
1626
self._new_pack.abort()
1627
self._new_pack = None
1628
for resumed_pack in self._resumed_packs:
1629
# XXX: this is a pretty ugly way to turn the resumed pack into a
1630
# properly committed pack.
1631
self._names[resumed_pack.name] = None
1632
self._remove_pack_from_memory(resumed_pack)
1633
resumed_pack.finish()
1634
self.allocate(resumed_pack)
1635
any_new_content = True
1636
del self._resumed_packs[:]
1638
result = self.autopack()
1640
# when autopack takes no steps, the names list is still
1642
return self._save_pack_names()
1646
def _suspend_write_group(self):
1647
tokens = [pack.name for pack in self._resumed_packs]
1648
self._remove_pack_indices(self._new_pack)
1649
if self._new_pack.data_inserted():
1650
# get all the data to disk and read to use
1651
self._new_pack.finish(suspend=True)
1652
tokens.append(self._new_pack.name)
1653
self._new_pack = None
1655
self._new_pack.abort()
1656
self._new_pack = None
1657
self._remove_resumed_pack_indices()
1660
def _resume_write_group(self, tokens):
1661
for token in tokens:
1662
self._resume_pack(token)
1665
class PackRepository(MetaDirVersionedFileRepository):
1666
"""Repository with knit objects stored inside pack containers.
1668
The layering for a KnitPackRepository is:
1670
Graph | HPSS | Repository public layer |
1671
===================================================
1672
Tuple based apis below, string based, and key based apis above
1673
---------------------------------------------------
1675
Provides .texts, .revisions etc
1676
This adapts the N-tuple keys to physical knit records which only have a
1677
single string identifier (for historical reasons), which in older formats
1678
was always the revision_id, and in the mapped code for packs is always
1679
the last element of key tuples.
1680
---------------------------------------------------
1682
A separate GraphIndex is used for each of the
1683
texts/inventories/revisions/signatures contained within each individual
1684
pack file. The GraphIndex layer works in N-tuples and is unaware of any
1686
===================================================
1690
# These attributes are inherited from the Repository base class. Setting
1691
# them to None ensures that if the constructor is changed to not initialize
1692
# them, or a subclass fails to call the constructor, that an error will
1693
# occur rather than the system working but generating incorrect data.
1694
_commit_builder_class = None
1697
def __init__(self, _format, a_bzrdir, control_files, _commit_builder_class,
1699
MetaDirRepository.__init__(self, _format, a_bzrdir, control_files)
1700
self._commit_builder_class = _commit_builder_class
1701
self._serializer = _serializer
1702
self._reconcile_fixes_text_parents = True
1703
if self._format.supports_external_lookups:
1704
self._unstacked_provider = graph.CachingParentsProvider(
1705
self._make_parents_provider_unstacked())
1707
self._unstacked_provider = graph.CachingParentsProvider(self)
1708
self._unstacked_provider.disable_cache()
1711
def _all_revision_ids(self):
1712
"""See Repository.all_revision_ids()."""
1713
return [key[0] for key in self.revisions.keys()]
1715
def _abort_write_group(self):
1716
self.revisions._index._key_dependencies.clear()
1717
self._pack_collection._abort_write_group()
1719
def _make_parents_provider(self):
1720
if not self._format.supports_external_lookups:
1721
return self._unstacked_provider
1722
return graph.StackedParentsProvider(_LazyListJoin(
1723
[self._unstacked_provider], self._fallback_repositories))
1725
def _refresh_data(self):
1726
if not self.is_locked():
1728
self._pack_collection.reload_pack_names()
1729
self._unstacked_provider.disable_cache()
1730
self._unstacked_provider.enable_cache()
1732
def _start_write_group(self):
1733
self._pack_collection._start_write_group()
1735
def _commit_write_group(self):
1736
hint = self._pack_collection._commit_write_group()
1737
self.revisions._index._key_dependencies.clear()
1738
# The commit may have added keys that were previously cached as
1739
# missing, so reset the cache.
1740
self._unstacked_provider.disable_cache()
1741
self._unstacked_provider.enable_cache()
1744
def suspend_write_group(self):
1745
# XXX check self._write_group is self.get_transaction()?
1746
tokens = self._pack_collection._suspend_write_group()
1747
self.revisions._index._key_dependencies.clear()
1748
self._write_group = None
1751
def _resume_write_group(self, tokens):
1752
self._start_write_group()
1754
self._pack_collection._resume_write_group(tokens)
1755
except errors.UnresumableWriteGroup:
1756
self._abort_write_group()
1758
for pack in self._pack_collection._resumed_packs:
1759
self.revisions._index.scan_unvalidated_index(pack.revision_index)
1761
def get_transaction(self):
1762
if self._write_lock_count:
1763
return self._transaction
1765
return self.control_files.get_transaction()
1767
def is_locked(self):
1768
return self._write_lock_count or self.control_files.is_locked()
1770
def is_write_locked(self):
1771
return self._write_lock_count
1773
def lock_write(self, token=None):
1774
"""Lock the repository for writes.
1776
:return: A breezy.repository.RepositoryWriteLockResult.
1778
locked = self.is_locked()
1779
if not self._write_lock_count and locked:
1780
raise errors.ReadOnlyError(self)
1781
self._write_lock_count += 1
1782
if self._write_lock_count == 1:
1783
self._transaction = transactions.WriteTransaction()
1785
if 'relock' in debug.debug_flags and self._prev_lock == 'w':
1786
note('%r was write locked again', self)
1787
self._prev_lock = 'w'
1788
self._unstacked_provider.enable_cache()
1789
for repo in self._fallback_repositories:
1790
# Writes don't affect fallback repos
1792
self._refresh_data()
1793
return RepositoryWriteLockResult(self.unlock, None)
1795
def lock_read(self):
1796
"""Lock the repository for reads.
1798
:return: A breezy.lock.LogicalLockResult.
1800
locked = self.is_locked()
1801
if self._write_lock_count:
1802
self._write_lock_count += 1
1804
self.control_files.lock_read()
1806
if 'relock' in debug.debug_flags and self._prev_lock == 'r':
1807
note('%r was read locked again', self)
1808
self._prev_lock = 'r'
1809
self._unstacked_provider.enable_cache()
1810
for repo in self._fallback_repositories:
1812
self._refresh_data()
1813
return LogicalLockResult(self.unlock)
1815
def leave_lock_in_place(self):
1816
# not supported - raise an error
1817
raise NotImplementedError(self.leave_lock_in_place)
1819
def dont_leave_lock_in_place(self):
1820
# not supported - raise an error
1821
raise NotImplementedError(self.dont_leave_lock_in_place)
1824
def pack(self, hint=None, clean_obsolete_packs=False):
1825
"""Compress the data within the repository.
1827
This will pack all the data to a single pack. In future it may
1828
recompress deltas or do other such expensive operations.
1830
self._pack_collection.pack(hint=hint, clean_obsolete_packs=clean_obsolete_packs)
1833
def reconcile(self, other=None, thorough=False):
1834
"""Reconcile this repository."""
1835
from breezy.reconcile import PackReconciler
1836
reconciler = PackReconciler(self, thorough=thorough)
1837
reconciler.reconcile()
1840
def _reconcile_pack(self, collection, packs, extension, revs, pb):
1841
raise NotImplementedError(self._reconcile_pack)
1843
@only_raises(errors.LockNotHeld, errors.LockBroken)
1845
if self._write_lock_count == 1 and self._write_group is not None:
1846
self.abort_write_group()
1847
self._unstacked_provider.disable_cache()
1848
self._transaction = None
1849
self._write_lock_count = 0
1850
raise errors.BzrError(
1851
'Must end write group before releasing write lock on %s'
1853
if self._write_lock_count:
1854
self._write_lock_count -= 1
1855
if not self._write_lock_count:
1856
transaction = self._transaction
1857
self._transaction = None
1858
transaction.finish()
1860
self.control_files.unlock()
1862
if not self.is_locked():
1863
self._unstacked_provider.disable_cache()
1864
for repo in self._fallback_repositories:
1868
class RepositoryFormatPack(MetaDirVersionedFileRepositoryFormat):
1869
"""Format logic for pack structured repositories.
1871
This repository format has:
1872
- a list of packs in pack-names
1873
- packs in packs/NAME.pack
1874
- indices in indices/NAME.{iix,six,tix,rix}
1875
- knit deltas in the packs, knit indices mapped to the indices.
1876
- thunk objects to support the knits programming API.
1877
- a format marker of its own
1878
- an optional 'shared-storage' flag
1879
- an optional 'no-working-trees' flag
1883
# Set this attribute in derived classes to control the repository class
1884
# created by open and initialize.
1885
repository_class = None
1886
# Set this attribute in derived classes to control the
1887
# _commit_builder_class that the repository objects will have passed to
1888
# their constructor.
1889
_commit_builder_class = None
1890
# Set this attribute in derived clases to control the _serializer that the
1891
# repository objects will have passed to their constructor.
1893
# Packs are not confused by ghosts.
1894
supports_ghosts = True
1895
# External references are not supported in pack repositories yet.
1896
supports_external_lookups = False
1897
# Most pack formats do not use chk lookups.
1898
supports_chks = False
1899
# What index classes to use
1900
index_builder_class = None
1902
_fetch_uses_deltas = True
1904
supports_funky_characters = True
1905
revision_graph_can_have_wrong_parents = True
1907
def initialize(self, a_bzrdir, shared=False):
1908
"""Create a pack based repository.
1910
:param a_bzrdir: bzrdir to contain the new repository; must already
1912
:param shared: If true the repository will be initialized as a shared
1915
mutter('creating repository in %s.', a_bzrdir.transport.base)
1916
dirs = ['indices', 'obsolete_packs', 'packs', 'upload']
1917
builder = self.index_builder_class()
1918
files = [('pack-names', builder.finish())]
1919
utf8_files = [('format', self.get_format_string())]
1921
self._upload_blank_content(a_bzrdir, dirs, files, utf8_files, shared)
1922
repository = self.open(a_bzrdir=a_bzrdir, _found=True)
1923
self._run_post_repo_init_hooks(repository, a_bzrdir, shared)
1926
def open(self, a_bzrdir, _found=False, _override_transport=None):
1927
"""See RepositoryFormat.open().
1929
:param _override_transport: INTERNAL USE ONLY. Allows opening the
1930
repository at a slightly different url
1931
than normal. I.e. during 'upgrade'.
1934
format = RepositoryFormatMetaDir.find_format(a_bzrdir)
1935
if _override_transport is not None:
1936
repo_transport = _override_transport
1938
repo_transport = a_bzrdir.get_repository_transport(None)
1939
control_files = lockable_files.LockableFiles(repo_transport,
1940
'lock', lockdir.LockDir)
1941
return self.repository_class(_format=self,
1943
control_files=control_files,
1944
_commit_builder_class=self._commit_builder_class,
1945
_serializer=self._serializer)
1948
class RetryPackOperations(errors.RetryWithNewPacks):
1949
"""Raised when we are packing and we find a missing file.
1951
Meant as a signaling exception, to tell the RepositoryPackCollection.pack
1952
code it should try again.
1955
internal_error = True
1957
_fmt = ("Pack files have changed, reload and try pack again."
1958
" context: %(context)s %(orig_error)s")
1961
class _DirectPackAccess(object):
1962
"""Access to data in one or more packs with less translation."""
1964
def __init__(self, index_to_packs, reload_func=None, flush_func=None):
1965
"""Create a _DirectPackAccess object.
1967
:param index_to_packs: A dict mapping index objects to the transport
1968
and file names for obtaining data.
1969
:param reload_func: A function to call if we determine that the pack
1970
files have moved and we need to reload our caches. See
1971
breezy.repo_fmt.pack_repo.AggregateIndex for more details.
1973
self._container_writer = None
1974
self._write_index = None
1975
self._indices = index_to_packs
1976
self._reload_func = reload_func
1977
self._flush_func = flush_func
1979
def add_raw_records(self, key_sizes, raw_data):
1980
"""Add raw knit bytes to a storage area.
1982
The data is spooled to the container writer in one bytes-record per
1985
:param sizes: An iterable of tuples containing the key and size of each
1987
:param raw_data: A bytestring containing the data.
1988
:return: A list of memos to retrieve the record later. Each memo is an
1989
opaque index memo. For _DirectPackAccess the memo is (index, pos,
1990
length), where the index field is the write_index object supplied
1991
to the PackAccess object.
1993
if not isinstance(raw_data, str):
1994
raise AssertionError(
1995
'data must be plain bytes was %s' % type(raw_data))
1998
for key, size in key_sizes:
1999
p_offset, p_length = self._container_writer.add_bytes_record(
2000
raw_data[offset:offset+size], [])
2002
result.append((self._write_index, p_offset, p_length))
2006
"""Flush pending writes on this access object.
2008
This will flush any buffered writes to a NewPack.
2010
if self._flush_func is not None:
2013
def get_raw_records(self, memos_for_retrieval):
2014
"""Get the raw bytes for a records.
2016
:param memos_for_retrieval: An iterable containing the (index, pos,
2017
length) memo for retrieving the bytes. The Pack access method
2018
looks up the pack to use for a given record in its index_to_pack
2020
:return: An iterator over the bytes of the records.
2022
# first pass, group into same-index requests
2024
current_index = None
2025
for (index, offset, length) in memos_for_retrieval:
2026
if current_index == index:
2027
current_list.append((offset, length))
2029
if current_index is not None:
2030
request_lists.append((current_index, current_list))
2031
current_index = index
2032
current_list = [(offset, length)]
2033
# handle the last entry
2034
if current_index is not None:
2035
request_lists.append((current_index, current_list))
2036
for index, offsets in request_lists:
2038
transport, path = self._indices[index]
2040
# A KeyError here indicates that someone has triggered an index
2041
# reload, and this index has gone missing, we need to start
2043
if self._reload_func is None:
2044
# If we don't have a _reload_func there is nothing that can
2047
raise errors.RetryWithNewPacks(index,
2048
reload_occurred=True,
2049
exc_info=sys.exc_info())
2051
reader = pack.make_readv_reader(transport, path, offsets)
2052
for names, read_func in reader.iter_records():
2053
yield read_func(None)
2054
except errors.NoSuchFile:
2055
# A NoSuchFile error indicates that a pack file has gone
2056
# missing on disk, we need to trigger a reload, and start over.
2057
if self._reload_func is None:
2059
raise errors.RetryWithNewPacks(transport.abspath(path),
2060
reload_occurred=False,
2061
exc_info=sys.exc_info())
2063
def set_writer(self, writer, index, transport_packname):
2064
"""Set a writer to use for adding data."""
2065
if index is not None:
2066
self._indices[index] = transport_packname
2067
self._container_writer = writer
2068
self._write_index = index
2070
def reload_or_raise(self, retry_exc):
2071
"""Try calling the reload function, or re-raise the original exception.
2073
This should be called after _DirectPackAccess raises a
2074
RetryWithNewPacks exception. This function will handle the common logic
2075
of determining when the error is fatal versus being temporary.
2076
It will also make sure that the original exception is raised, rather
2077
than the RetryWithNewPacks exception.
2079
If this function returns, then the calling function should retry
2080
whatever operation was being performed. Otherwise an exception will
2083
:param retry_exc: A RetryWithNewPacks exception.
2086
if self._reload_func is None:
2088
elif not self._reload_func():
2089
# The reload claimed that nothing changed
2090
if not retry_exc.reload_occurred:
2091
# If there wasn't an earlier reload, then we really were
2092
# expecting to find changes. We didn't find them, so this is a
2096
# GZ 2017-03-27: No real reason this needs the original traceback.
2097
reraise(*retry_exc.exc_info)