1
# Copyright (C) 2005, 2006, 2007 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17
from bzrlib.lazy_import import lazy_import
18
lazy_import(globals(), """
19
from itertools import izip
29
from bzrlib.graph import Graph
30
from bzrlib.index import (
35
GraphIndexPrefixAdapter,
37
from bzrlib.knit import KnitGraphIndex, _PackAccess, _KnitData
38
from bzrlib.osutils import rand_chars
39
from bzrlib.pack import ContainerWriter
40
from bzrlib.store import revision
56
from bzrlib.decorators import needs_read_lock, needs_write_lock
57
from bzrlib.repofmt.knitrepo import KnitRepository
58
from bzrlib.repository import (
61
MetaDirRepositoryFormat,
64
import bzrlib.revision as _mod_revision
65
from bzrlib.store.revision.knit import KnitRevisionStore
66
from bzrlib.store.versioned import VersionedFileStore
67
from bzrlib.trace import mutter, note, warning
70
class PackCommitBuilder(CommitBuilder):
71
"""A subclass of CommitBuilder to add texts with pack semantics.
73
Specifically this uses one knit object rather than one knit object per
74
added text, reducing memory and object pressure.
77
def __init__(self, repository, parents, config, timestamp=None,
78
timezone=None, committer=None, revprops=None,
80
CommitBuilder.__init__(self, repository, parents, config,
81
timestamp=timestamp, timezone=timezone, committer=committer,
82
revprops=revprops, revision_id=revision_id)
83
self._file_graph = Graph(
84
repository._pack_collection.text_index.combined_index)
86
def _add_text_to_weave(self, file_id, new_lines, parents, nostore_sha):
87
return self.repository._pack_collection._add_text_to_weave(file_id,
88
self._new_revision_id, new_lines, parents, nostore_sha,
91
def _heads(self, file_id, revision_ids):
92
keys = [(file_id, revision_id) for revision_id in revision_ids]
93
return set([key[1] for key in self._file_graph.heads(keys)])
96
class PackRootCommitBuilder(RootCommitBuilder):
97
"""A subclass of RootCommitBuilder to add texts with pack semantics.
99
Specifically this uses one knit object rather than one knit object per
100
added text, reducing memory and object pressure.
103
def __init__(self, repository, parents, config, timestamp=None,
104
timezone=None, committer=None, revprops=None,
106
CommitBuilder.__init__(self, repository, parents, config,
107
timestamp=timestamp, timezone=timezone, committer=committer,
108
revprops=revprops, revision_id=revision_id)
109
self._file_graph = Graph(
110
repository._pack_collection.text_index.combined_index)
112
def _add_text_to_weave(self, file_id, new_lines, parents, nostore_sha):
113
return self.repository._pack_collection._add_text_to_weave(file_id,
114
self._new_revision_id, new_lines, parents, nostore_sha,
117
def _heads(self, file_id, revision_ids):
118
keys = [(file_id, revision_id) for revision_id in revision_ids]
119
return set([key[1] for key in self._file_graph.heads(keys)])
123
"""An in memory proxy for a pack and its indices.
125
This is a base class that is not directly used, instead the classes
126
ExistingPack and NewPack are used.
129
def __init__(self, revision_index, inventory_index, text_index,
131
"""Create a pack instance.
133
:param revision_index: A GraphIndex for determining what revisions are
134
present in the Pack and accessing the locations of their texts.
135
:param inventory_index: A GraphIndex for determining what inventories are
136
present in the Pack and accessing the locations of their
138
:param text_index: A GraphIndex for determining what file texts
139
are present in the pack and accessing the locations of their
140
texts/deltas (via (fileid, revisionid) tuples).
141
:param revision_index: A GraphIndex for determining what signatures are
142
present in the Pack and accessing the locations of their texts.
144
self.revision_index = revision_index
145
self.inventory_index = inventory_index
146
self.text_index = text_index
147
self.signature_index = signature_index
149
def access_tuple(self):
150
"""Return a tuple (transport, name) for the pack content."""
151
return self.pack_transport, self.file_name()
154
"""Get the file name for the pack on disk."""
155
return self.name + '.pack'
157
def get_revision_count(self):
158
return self.revision_index.key_count()
160
def inventory_index_name(self, name):
161
"""The inv index is the name + .iix."""
162
return self.index_name('inventory', name)
164
def revision_index_name(self, name):
165
"""The revision index is the name + .rix."""
166
return self.index_name('revision', name)
168
def signature_index_name(self, name):
169
"""The signature index is the name + .six."""
170
return self.index_name('signature', name)
172
def text_index_name(self, name):
173
"""The text index is the name + .tix."""
174
return self.index_name('text', name)
177
class ExistingPack(Pack):
178
"""An in memory proxy for an existing .pack and its disk indices."""
180
def __init__(self, pack_transport, name, revision_index, inventory_index,
181
text_index, signature_index):
182
"""Create an ExistingPack object.
184
:param pack_transport: The transport where the pack file resides.
185
:param name: The name of the pack on disk in the pack_transport.
187
Pack.__init__(self, revision_index, inventory_index, text_index,
190
self.pack_transport = pack_transport
191
assert None not in (revision_index, inventory_index, text_index,
192
signature_index, name, pack_transport)
194
def __eq__(self, other):
195
return self.__dict__ == other.__dict__
197
def __ne__(self, other):
198
return not self.__eq__(other)
201
return "<bzrlib.repofmt.pack_repo.Pack object at 0x%x, %s, %s" % (
202
id(self), self.transport, self.name)
206
"""An in memory proxy for a pack which is being created."""
208
# A map of index 'type' to the file extension and position in the
210
index_definitions = {
211
'revision': ('.rix', 0),
212
'inventory': ('.iix', 1),
214
'signature': ('.six', 3),
217
def __init__(self, upload_transport, index_transport, pack_transport,
218
upload_suffix='', file_mode=None):
219
"""Create a NewPack instance.
221
:param upload_transport: A writable transport for the pack to be
222
incrementally uploaded to.
223
:param index_transport: A writable transport for the pack's indices to
224
be written to when the pack is finished.
225
:param pack_transport: A writable transport for the pack to be renamed
226
to when the upload is complete. This *must* be the same as
227
upload_transport.clone('../packs').
228
:param upload_suffix: An optional suffix to be given to any temporary
229
files created during the pack creation. e.g '.autopack'
230
:param file_mode: An optional file mode to create the new files with.
232
# The relative locations of the packs are constrained, but all are
233
# passed in because the caller has them, so as to avoid object churn.
235
# Revisions: parents list, no text compression.
236
InMemoryGraphIndex(reference_lists=1),
237
# Inventory: We want to map compression only, but currently the
238
# knit code hasn't been updated enough to understand that, so we
239
# have a regular 2-list index giving parents and compression
241
InMemoryGraphIndex(reference_lists=2),
242
# Texts: compression and per file graph, for all fileids - so two
243
# reference lists and two elements in the key tuple.
244
InMemoryGraphIndex(reference_lists=2, key_elements=2),
245
# Signatures: Just blobs to store, no compression, no parents
247
InMemoryGraphIndex(reference_lists=0),
249
# where should the new pack be opened
250
self.upload_transport = upload_transport
251
# where are indices written out to
252
self.index_transport = index_transport
253
# where is the pack renamed to when it is finished?
254
self.pack_transport = pack_transport
255
# What file mode to upload the pack and indices with.
256
self._file_mode = file_mode
257
# tracks the content written to the .pack file.
258
self._hash = md5.new()
259
# a four-tuple with the length in bytes of the indices, once the pack
260
# is finalised. (rev, inv, text, sigs)
261
self.index_sizes = None
262
# How much data to cache when writing packs. Note that this is not
263
# synchronised with reads, because it's not in the transport layer, so
264
# is not safe unless the client knows it won't be reading from the pack
266
self._cache_limit = 0
267
# the temporary pack file name.
268
self.random_name = rand_chars(20) + upload_suffix
269
# when was this pack started ?
270
self.start_time = time.time()
271
# open an output stream for the data added to the pack.
272
self.write_stream = self.upload_transport.open_write_stream(
273
self.random_name, mode=self._file_mode)
274
if 'pack' in debug.debug_flags:
275
mutter('%s: create_pack: pack stream open: %s%s t+%6.3fs',
276
time.ctime(), self.upload_transport.base, self.random_name,
277
time.time() - self.start_time)
278
# A list of byte sequences to be written to the new pack, and the
279
# aggregate size of them. Stored as a list rather than separate
280
# variables so that the _write_data closure below can update them.
281
self._buffer = [[], 0]
282
# create a callable for adding data
284
# robertc says- this is a closure rather than a method on the object
285
# so that the variables are locals, and faster than accessing object
287
def _write_data(bytes, flush=False, _buffer=self._buffer,
288
_write=self.write_stream.write, _update=self._hash.update):
289
_buffer[0].append(bytes)
290
_buffer[1] += len(bytes)
292
if _buffer[1] > self._cache_limit or flush:
293
bytes = ''.join(_buffer[0])
297
# expose this on self, for the occasion when clients want to add data.
298
self._write_data = _write_data
299
# a pack writer object to serialise pack records.
300
self._writer = pack.ContainerWriter(self._write_data)
302
# what state is the pack in? (open, finished, aborted)
306
"""Cancel creating this pack."""
307
self._state = 'aborted'
308
self.write_stream.close()
309
# Remove the temporary pack file.
310
self.upload_transport.delete(self.random_name)
311
# The indices have no state on disk.
313
def access_tuple(self):
314
"""Return a tuple (transport, name) for the pack content."""
315
assert self._state in ('open', 'finished')
316
if self._state == 'finished':
317
return Pack.access_tuple(self)
319
return self.upload_transport, self.random_name
321
def data_inserted(self):
322
"""True if data has been added to this pack."""
323
return bool(self.get_revision_count() or
324
self.inventory_index.key_count() or
325
self.text_index.key_count() or
326
self.signature_index.key_count())
329
"""Finish the new pack.
332
- finalises the content
333
- assigns a name (the md5 of the content, currently)
334
- writes out the associated indices
335
- renames the pack into place.
336
- stores the index size tuple for the pack in the index_sizes
341
self._write_data('', flush=True)
342
self.name = self._hash.hexdigest()
344
# XXX: It'd be better to write them all to temporary names, then
345
# rename them all into place, so that the window when only some are
346
# visible is smaller. On the other hand none will be seen until
347
# they're in the names list.
348
self.index_sizes = [None, None, None, None]
349
self._write_index('revision', self.revision_index, 'revision')
350
self._write_index('inventory', self.inventory_index, 'inventory')
351
self._write_index('text', self.text_index, 'file texts')
352
self._write_index('signature', self.signature_index,
353
'revision signatures')
354
self.write_stream.close()
355
# Note that this will clobber an existing pack with the same name,
356
# without checking for hash collisions. While this is undesirable this
357
# is something that can be rectified in a subsequent release. One way
358
# to rectify it may be to leave the pack at the original name, writing
359
# its pack-names entry as something like 'HASH: index-sizes
360
# temporary-name'. Allocate that and check for collisions, if it is
361
# collision free then rename it into place. If clients know this scheme
362
# they can handle missing-file errors by:
363
# - try for HASH.pack
364
# - try for temporary-name
365
# - refresh the pack-list to see if the pack is now absent
366
self.upload_transport.rename(self.random_name,
367
'../packs/' + self.name + '.pack')
368
self._state = 'finished'
369
if 'pack' in debug.debug_flags:
370
# XXX: size might be interesting?
371
mutter('%s: create_pack: pack renamed into place: %s%s->%s%s t+%6.3fs',
372
time.ctime(), self.upload_transport.base, self.random_name,
373
self.pack_transport, self.name,
374
time.time() - self.start_time)
376
def index_name(self, index_type, name):
377
"""Get the disk name of an index type for pack name 'name'."""
378
return name + NewPack.index_definitions[index_type][0]
380
def index_offset(self, index_type):
381
"""Get the position in a index_size array for a given index type."""
382
return NewPack.index_definitions[index_type][1]
384
def _replace_index_with_readonly(self, index_type):
385
setattr(self, index_type + '_index',
386
GraphIndex(self.index_transport,
387
self.index_name(index_type, self.name),
388
self.index_sizes[self.index_offset(index_type)]))
390
def set_write_cache_size(self, size):
391
self._cache_limit = size
393
def _write_index(self, index_type, index, label):
394
"""Write out an index.
396
:param index_type: The type of index to write - e.g. 'revision'.
397
:param index: The index object to serialise.
398
:param label: What label to give the index e.g. 'revision'.
400
index_name = self.index_name(index_type, self.name)
401
self.index_sizes[self.index_offset(index_type)] = \
402
self.index_transport.put_file(index_name, index.finish(),
403
mode=self._file_mode)
404
if 'pack' in debug.debug_flags:
405
# XXX: size might be interesting?
406
mutter('%s: create_pack: wrote %s index: %s%s t+%6.3fs',
407
time.ctime(), label, self.upload_transport.base,
408
self.random_name, time.time() - self.start_time)
409
# Replace the writable index on this object with a readonly,
410
# presently unloaded index. We should alter
411
# the index layer to make its finish() error if add_node is
412
# subsequently used. RBC
413
self._replace_index_with_readonly(index_type)
416
class AggregateIndex(object):
417
"""An aggregated index for the RepositoryPackCollection.
419
AggregateIndex is reponsible for managing the PackAccess object,
420
Index-To-Pack mapping, and all indices list for a specific type of index
421
such as 'revision index'.
423
A CombinedIndex provides an index on a single key space built up
424
from several on-disk indices. The AggregateIndex builds on this
425
to provide a knit access layer, and allows having up to one writable
426
index within the collection.
428
# XXX: Probably 'can be written to' could/should be separated from 'acts
429
# like a knit index' -- mbp 20071024
432
"""Create an AggregateIndex."""
433
self.index_to_pack = {}
434
self.combined_index = CombinedGraphIndex([])
435
self.knit_access = _PackAccess(self.index_to_pack)
437
def replace_indices(self, index_to_pack, indices):
438
"""Replace the current mappings with fresh ones.
440
This should probably not be used eventually, rather incremental add and
441
removal of indices. It has been added during refactoring of existing
444
:param index_to_pack: A mapping from index objects to
445
(transport, name) tuples for the pack file data.
446
:param indices: A list of indices.
448
# refresh the revision pack map dict without replacing the instance.
449
self.index_to_pack.clear()
450
self.index_to_pack.update(index_to_pack)
451
# XXX: API break - clearly a 'replace' method would be good?
452
self.combined_index._indices[:] = indices
453
# the current add nodes callback for the current writable index if
455
self.add_callback = None
457
def add_index(self, index, pack):
458
"""Add index to the aggregate, which is an index for Pack pack.
460
Future searches on the aggregate index will seach this new index
461
before all previously inserted indices.
463
:param index: An Index for the pack.
464
:param pack: A Pack instance.
466
# expose it to the index map
467
self.index_to_pack[index] = pack.access_tuple()
468
# put it at the front of the linear index list
469
self.combined_index.insert_index(0, index)
471
def add_writable_index(self, index, pack):
472
"""Add an index which is able to have data added to it.
474
There can be at most one writable index at any time. Any
475
modifications made to the knit are put into this index.
477
:param index: An index from the pack parameter.
478
:param pack: A Pack instance.
480
assert self.add_callback is None, \
481
"%s already has a writable index through %s" % \
482
(self, self.add_callback)
483
# allow writing: queue writes to a new index
484
self.add_index(index, pack)
485
# Updates the index to packs mapping as a side effect,
486
self.knit_access.set_writer(pack._writer, index, pack.access_tuple())
487
self.add_callback = index.add_nodes
490
"""Reset all the aggregate data to nothing."""
491
self.knit_access.set_writer(None, None, (None, None))
492
self.index_to_pack.clear()
493
del self.combined_index._indices[:]
494
self.add_callback = None
496
def remove_index(self, index, pack):
497
"""Remove index from the indices used to answer queries.
499
:param index: An index from the pack parameter.
500
:param pack: A Pack instance.
502
del self.index_to_pack[index]
503
self.combined_index._indices.remove(index)
504
if (self.add_callback is not None and
505
getattr(index, 'add_nodes', None) == self.add_callback):
506
self.add_callback = None
507
self.knit_access.set_writer(None, None, (None, None))
510
class Packer(object):
511
"""Create a pack from packs."""
513
def __init__(self, pack_collection, packs, suffix, revision_ids=None):
516
:param pack_collection: A RepositoryPackCollection object where the
517
new pack is being written to.
518
:param packs: The packs to combine.
519
:param suffix: The suffix to use on the temporary files for the pack.
520
:param revision_ids: Revision ids to limit the pack to.
524
self.revision_ids = revision_ids
525
# The pack object we are creating.
527
self._pack_collection = pack_collection
528
# The index layer keys for the revisions being copied. None for 'all
530
self._revision_keys = None
531
# What text keys to copy. None for 'all texts'. This is set by
532
# _copy_inventory_texts
533
self._text_filter = None
535
def pack(self, pb=None):
536
"""Create a new pack by reading data from other packs.
538
This does little more than a bulk copy of data. One key difference
539
is that data with the same item key across multiple packs is elided
540
from the output. The new pack is written into the current pack store
541
along with its indices, and the name added to the pack names. The
542
source packs are not altered and are not required to be in the current
545
:param pb: An optional progress bar to use. A nested bar is created if
547
:return: A Pack object, or None if nothing was copied.
549
# open a pack - using the same name as the last temporary file
550
# - which has already been flushed, so its safe.
551
# XXX: - duplicate code warning with start_write_group; fix before
552
# considering 'done'.
553
if self._pack_collection._new_pack is not None:
554
raise errors.BzrError('call to create_pack_from_packs while '
555
'another pack is being written.')
556
if self.revision_ids is not None:
557
if len(self.revision_ids) == 0:
558
# silly fetch request.
561
self.revision_ids = frozenset(self.revision_ids)
563
self.pb = ui.ui_factory.nested_progress_bar()
567
return self._create_pack_from_packs()
573
"""Open a pack for the pack we are creating."""
574
return NewPack(self._pack_collection._upload_transport,
575
self._pack_collection._index_transport,
576
self._pack_collection._pack_transport, upload_suffix=self.suffix,
577
file_mode=self._pack_collection.repo.control_files._file_mode)
579
def _copy_revision_texts(self):
580
"""Copy revision data to the new pack."""
582
if self.revision_ids:
583
revision_keys = [(revision_id,) for revision_id in self.revision_ids]
586
# select revision keys
587
revision_index_map = self._pack_collection._packs_list_to_pack_map_and_index_list(
588
self.packs, 'revision_index')[0]
589
revision_nodes = self._pack_collection._index_contents(revision_index_map, revision_keys)
590
# copy revision keys and adjust values
591
self.pb.update("Copying revision texts", 1)
592
list(self._copy_nodes_graph(revision_nodes, revision_index_map,
593
self.new_pack._writer, self.new_pack.revision_index))
594
if 'pack' in debug.debug_flags:
595
mutter('%s: create_pack: revisions copied: %s%s %d items t+%6.3fs',
596
time.ctime(), self._pack_collection._upload_transport.base,
597
self.new_pack.random_name,
598
self.new_pack.revision_index.key_count(),
599
time.time() - self.new_pack.start_time)
600
self._revision_keys = revision_keys
602
def _copy_inventory_texts(self):
603
"""Copy the inventory texts to the new pack.
605
self._revision_keys is used to determine what inventories to copy.
607
Sets self._text_filter appropriately.
609
# select inventory keys
610
inv_keys = self._revision_keys # currently the same keyspace, and note that
611
# querying for keys here could introduce a bug where an inventory item
612
# is missed, so do not change it to query separately without cross
613
# checking like the text key check below.
614
inventory_index_map = self._pack_collection._packs_list_to_pack_map_and_index_list(
615
self.packs, 'inventory_index')[0]
616
inv_nodes = self._pack_collection._index_contents(inventory_index_map, inv_keys)
617
# copy inventory keys and adjust values
618
# XXX: Should be a helper function to allow different inv representation
620
self.pb.update("Copying inventory texts", 2)
621
inv_lines = self._copy_nodes_graph(inv_nodes, inventory_index_map,
622
self.new_pack._writer, self.new_pack.inventory_index, output_lines=True)
623
if self.revision_ids:
624
fileid_revisions = self._pack_collection.repo._find_file_ids_from_xml_inventory_lines(
625
inv_lines, self.revision_ids)
627
for fileid, file_revids in fileid_revisions.iteritems():
629
[(fileid, file_revid) for file_revid in file_revids])
631
# eat the iterator to cause it to execute.
634
if 'pack' in debug.debug_flags:
635
mutter('%s: create_pack: inventories copied: %s%s %d items t+%6.3fs',
636
time.ctime(), self._pack_collection._upload_transport.base,
637
self.new_pack.random_name,
638
self.new_pack.inventory_index.key_count(),
639
time.time() - new_pack.start_time)
640
self._text_filter = text_filter
642
def _create_pack_from_packs(self):
643
self.pb.update("Opening pack", 0, 5)
644
self.new_pack = self.open_pack()
645
new_pack = self.new_pack
646
# buffer data - we won't be reading-back during the pack creation and
647
# this makes a significant difference on sftp pushes.
648
new_pack.set_write_cache_size(1024*1024)
649
if 'pack' in debug.debug_flags:
650
plain_pack_list = ['%s%s' % (a_pack.pack_transport.base, a_pack.name)
651
for a_pack in self.packs]
652
if self.revision_ids is not None:
653
rev_count = len(self.revision_ids)
656
mutter('%s: create_pack: creating pack from source packs: '
657
'%s%s %s revisions wanted %s t=0',
658
time.ctime(), self._pack_collection._upload_transport.base, new_pack.random_name,
659
plain_pack_list, rev_count)
660
self._copy_revision_texts()
661
self._copy_inventory_texts()
663
text_index_map = self._pack_collection._packs_list_to_pack_map_and_index_list(
664
self.packs, 'text_index')[0]
665
text_nodes = self._pack_collection._index_contents(text_index_map,
667
if self._text_filter is not None:
668
# We could return the keys copied as part of the return value from
669
# _copy_nodes_graph but this doesn't work all that well with the
670
# need to get line output too, so we check separately, and as we're
671
# going to buffer everything anyway, we check beforehand, which
672
# saves reading knit data over the wire when we know there are
674
text_nodes = set(text_nodes)
675
present_text_keys = set(_node[1] for _node in text_nodes)
676
missing_text_keys = set(self._text_filter) - present_text_keys
677
if missing_text_keys:
678
# TODO: raise a specific error that can handle many missing
680
a_missing_key = missing_text_keys.pop()
681
raise errors.RevisionNotPresent(a_missing_key[1],
683
# copy text keys and adjust values
684
self.pb.update("Copying content texts", 3)
685
list(self._copy_nodes_graph(text_nodes, text_index_map,
686
new_pack._writer, new_pack.text_index))
687
if 'pack' in debug.debug_flags:
688
mutter('%s: create_pack: file texts copied: %s%s %d items t+%6.3fs',
689
time.ctime(), self._pack_collection._upload_transport.base, new_pack.random_name,
690
new_pack.text_index.key_count(),
691
time.time() - new_pack.start_time)
692
# select signature keys
693
signature_filter = self._revision_keys # same keyspace
694
signature_index_map = self._pack_collection._packs_list_to_pack_map_and_index_list(
695
self.packs, 'signature_index')[0]
696
signature_nodes = self._pack_collection._index_contents(signature_index_map,
698
# copy signature keys and adjust values
699
self.pb.update("Copying signature texts", 4)
700
self._copy_nodes(signature_nodes, signature_index_map, new_pack._writer,
701
new_pack.signature_index)
702
if 'pack' in debug.debug_flags:
703
mutter('%s: create_pack: revision signatures copied: %s%s %d items t+%6.3fs',
704
time.ctime(), self._pack_collection._upload_transport.base, new_pack.random_name,
705
new_pack.signature_index.key_count(),
706
time.time() - new_pack.start_time)
707
if not self._use_pack(new_pack):
710
self.pb.update("Finishing pack", 5)
712
self._pack_collection.allocate(new_pack)
715
def _copy_nodes(self, nodes, index_map, writer, write_index):
716
"""Copy knit nodes between packs with no graph references."""
717
pb = ui.ui_factory.nested_progress_bar()
719
return self._do_copy_nodes(nodes, index_map, writer,
724
def _do_copy_nodes(self, nodes, index_map, writer, write_index, pb):
725
# for record verification
726
knit_data = _KnitData(None)
727
# plan a readv on each source pack:
729
nodes = sorted(nodes)
730
# how to map this into knit.py - or knit.py into this?
731
# we don't want the typical knit logic, we want grouping by pack
732
# at this point - perhaps a helper library for the following code
733
# duplication points?
735
for index, key, value in nodes:
736
if index not in request_groups:
737
request_groups[index] = []
738
request_groups[index].append((key, value))
740
pb.update("Copied record", record_index, len(nodes))
741
for index, items in request_groups.iteritems():
742
pack_readv_requests = []
743
for key, value in items:
744
# ---- KnitGraphIndex.get_position
745
bits = value[1:].split(' ')
746
offset, length = int(bits[0]), int(bits[1])
747
pack_readv_requests.append((offset, length, (key, value[0])))
748
# linear scan up the pack
749
pack_readv_requests.sort()
751
transport, path = index_map[index]
752
reader = pack.make_readv_reader(transport, path,
753
[offset[0:2] for offset in pack_readv_requests])
754
for (names, read_func), (_1, _2, (key, eol_flag)) in \
755
izip(reader.iter_records(), pack_readv_requests):
756
raw_data = read_func(None)
757
# check the header only
758
df, _ = knit_data._parse_record_header(key[-1], raw_data)
760
pos, size = writer.add_bytes_record(raw_data, names)
761
write_index.add_node(key, eol_flag + "%d %d" % (pos, size))
762
pb.update("Copied record", record_index)
765
def _copy_nodes_graph(self, nodes, index_map, writer, write_index,
767
"""Copy knit nodes between packs.
769
:param output_lines: Return lines present in the copied data as
770
an iterator of line,version_id.
772
pb = ui.ui_factory.nested_progress_bar()
774
return self._do_copy_nodes_graph(nodes, index_map, writer,
775
write_index, output_lines, pb)
779
def _do_copy_nodes_graph(self, nodes, index_map, writer, write_index,
781
# for record verification
782
knit_data = _KnitData(None)
783
# for line extraction when requested (inventories only)
785
factory = knit.KnitPlainFactory()
786
# plan a readv on each source pack:
788
nodes = sorted(nodes)
789
# how to map this into knit.py - or knit.py into this?
790
# we don't want the typical knit logic, we want grouping by pack
791
# at this point - perhaps a helper library for the following code
792
# duplication points?
795
pb.update("Copied record", record_index, len(nodes))
796
for index, key, value, references in nodes:
797
if index not in request_groups:
798
request_groups[index] = []
799
request_groups[index].append((key, value, references))
800
for index, items in request_groups.iteritems():
801
pack_readv_requests = []
802
for key, value, references in items:
803
# ---- KnitGraphIndex.get_position
804
bits = value[1:].split(' ')
805
offset, length = int(bits[0]), int(bits[1])
806
pack_readv_requests.append((offset, length, (key, value[0], references)))
807
# linear scan up the pack
808
pack_readv_requests.sort()
810
transport, path = index_map[index]
811
reader = pack.make_readv_reader(transport, path,
812
[offset[0:2] for offset in pack_readv_requests])
813
for (names, read_func), (_1, _2, (key, eol_flag, references)) in \
814
izip(reader.iter_records(), pack_readv_requests):
815
raw_data = read_func(None)
818
# read the entire thing
819
content, _ = knit_data._parse_record(version_id, raw_data)
820
if len(references[-1]) == 0:
821
line_iterator = factory.get_fulltext_content(content)
823
line_iterator = factory.get_linedelta_content(content)
824
for line in line_iterator:
825
yield line, version_id
827
# check the header only
828
df, _ = knit_data._parse_record_header(version_id, raw_data)
830
pos, size = writer.add_bytes_record(raw_data, names)
831
write_index.add_node(key, eol_flag + "%d %d" % (pos, size), references)
832
pb.update("Copied record", record_index)
835
def _use_pack(self, new_pack):
836
"""Return True if new_pack should be used.
838
:param new_pack: The pack that has just been created.
839
:return: True if the pack should be used.
841
return new_pack.data_inserted()
844
class ReconcilePacker(Packer):
845
"""A packer which regenerates indices etc as it copies.
847
This is used by ``bzr reconcile`` to cause parent text pointers to be
851
def _use_pack(self, new_pack):
852
"""Override _use_pack to check for reconcile having changed content."""
853
self._data_changed = False
854
# XXX: we might be better checking this at the copy time.
855
original_inventory_keys = set()
856
inv_index = self._pack_collection.inventory_index.combined_index
857
for entry in inv_index.iter_all_entries():
858
original_inventory_keys.add(entry[1])
859
new_inventory_keys = set()
860
for entry in new_pack.inventory_index.iter_all_entries():
861
new_inventory_keys.add(entry[1])
862
if new_inventory_keys != original_inventory_keys:
863
self._data_changed = True
864
return new_pack.data_inserted() and self._data_changed
867
class RepositoryPackCollection(object):
868
"""Management of packs within a repository."""
870
def __init__(self, repo, transport, index_transport, upload_transport,
872
"""Create a new RepositoryPackCollection.
874
:param transport: Addresses the repository base directory
875
(typically .bzr/repository/).
876
:param index_transport: Addresses the directory containing indices.
877
:param upload_transport: Addresses the directory into which packs are written
878
while they're being created.
879
:param pack_transport: Addresses the directory of existing complete packs.
882
self.transport = transport
883
self._index_transport = index_transport
884
self._upload_transport = upload_transport
885
self._pack_transport = pack_transport
886
self._suffix_offsets = {'.rix': 0, '.iix': 1, '.tix': 2, '.six': 3}
889
self._packs_by_name = {}
890
# the previous pack-names content
891
self._packs_at_load = None
892
# when a pack is being created by this object, the state of that pack.
893
self._new_pack = None
894
# aggregated revision index data
895
self.revision_index = AggregateIndex()
896
self.inventory_index = AggregateIndex()
897
self.text_index = AggregateIndex()
898
self.signature_index = AggregateIndex()
900
def add_pack_to_memory(self, pack):
901
"""Make a Pack object available to the repository to satisfy queries.
903
:param pack: A Pack object.
905
assert pack.name not in self._packs_by_name
906
self.packs.append(pack)
907
self._packs_by_name[pack.name] = pack
908
self.revision_index.add_index(pack.revision_index, pack)
909
self.inventory_index.add_index(pack.inventory_index, pack)
910
self.text_index.add_index(pack.text_index, pack)
911
self.signature_index.add_index(pack.signature_index, pack)
913
def _add_text_to_weave(self, file_id, revision_id, new_lines, parents,
914
nostore_sha, random_revid):
915
file_id_index = GraphIndexPrefixAdapter(
916
self.text_index.combined_index,
918
add_nodes_callback=self.text_index.add_callback)
919
self.repo._text_knit._index._graph_index = file_id_index
920
self.repo._text_knit._index._add_callback = file_id_index.add_nodes
921
return self.repo._text_knit.add_lines_with_ghosts(
922
revision_id, parents, new_lines, nostore_sha=nostore_sha,
923
random_id=random_revid, check_content=False)[0:2]
926
"""Return a list of all the Pack objects this repository has.
928
Note that an in-progress pack being created is not returned.
930
:return: A list of Pack objects for all the packs in the repository.
933
for name in self.names():
934
result.append(self.get_pack_by_name(name))
938
"""Pack the pack collection incrementally.
940
This will not attempt global reorganisation or recompression,
941
rather it will just ensure that the total number of packs does
942
not grow without bound. It uses the _max_pack_count method to
943
determine if autopacking is needed, and the pack_distribution
944
method to determine the number of revisions in each pack.
946
If autopacking takes place then the packs name collection will have
947
been flushed to disk - packing requires updating the name collection
948
in synchronisation with certain steps. Otherwise the names collection
951
:return: True if packing took place.
953
# XXX: Should not be needed when the management of indices is sane.
954
total_revisions = self.revision_index.combined_index.key_count()
955
total_packs = len(self._names)
956
if self._max_pack_count(total_revisions) >= total_packs:
958
# XXX: the following may want to be a class, to pack with a given
960
mutter('Auto-packing repository %s, which has %d pack files, '
961
'containing %d revisions into %d packs.', self, total_packs,
962
total_revisions, self._max_pack_count(total_revisions))
963
# determine which packs need changing
964
pack_distribution = self.pack_distribution(total_revisions)
966
for pack in self.all_packs():
967
revision_count = pack.get_revision_count()
968
if revision_count == 0:
969
# revision less packs are not generated by normal operation,
970
# only by operations like sign-my-commits, and thus will not
971
# tend to grow rapdily or without bound like commit containing
972
# packs do - leave them alone as packing them really should
973
# group their data with the relevant commit, and that may
974
# involve rewriting ancient history - which autopack tries to
975
# avoid. Alternatively we could not group the data but treat
976
# each of these as having a single revision, and thus add
977
# one revision for each to the total revision count, to get
978
# a matching distribution.
980
existing_packs.append((revision_count, pack))
981
pack_operations = self.plan_autopack_combinations(
982
existing_packs, pack_distribution)
983
self._execute_pack_operations(pack_operations)
986
def _execute_pack_operations(self, pack_operations):
987
"""Execute a series of pack operations.
989
:param pack_operations: A list of [revision_count, packs_to_combine].
992
for revision_count, packs in pack_operations:
993
# we may have no-ops from the setup logic
996
Packer(self, packs, '.autopack').pack()
998
self._remove_pack_from_memory(pack)
999
# record the newly available packs and stop advertising the old
1001
self._save_pack_names(clear_obsolete_packs=True)
1002
# Move the old packs out of the way now they are no longer referenced.
1003
for revision_count, packs in pack_operations:
1004
self._obsolete_packs(packs)
1006
def lock_names(self):
1007
"""Acquire the mutex around the pack-names index.
1009
This cannot be used in the middle of a read-only transaction on the
1012
self.repo.control_files.lock_write()
1015
"""Pack the pack collection totally."""
1016
self.ensure_loaded()
1017
total_packs = len(self._names)
1020
total_revisions = self.revision_index.combined_index.key_count()
1021
# XXX: the following may want to be a class, to pack with a given
1023
mutter('Packing repository %s, which has %d pack files, '
1024
'containing %d revisions into 1 packs.', self, total_packs,
1026
# determine which packs need changing
1027
pack_distribution = [1]
1028
pack_operations = [[0, []]]
1029
for pack in self.all_packs():
1030
revision_count = pack.get_revision_count()
1031
pack_operations[-1][0] += revision_count
1032
pack_operations[-1][1].append(pack)
1033
self._execute_pack_operations(pack_operations)
1035
def plan_autopack_combinations(self, existing_packs, pack_distribution):
1036
"""Plan a pack operation.
1038
:param existing_packs: The packs to pack. (A list of (revcount, Pack)
1040
:param pack_distribution: A list with the number of revisions desired
1043
if len(existing_packs) <= len(pack_distribution):
1045
existing_packs.sort(reverse=True)
1046
pack_operations = [[0, []]]
1047
# plan out what packs to keep, and what to reorganise
1048
while len(existing_packs):
1049
# take the largest pack, and if its less than the head of the
1050
# distribution chart we will include its contents in the new pack for
1051
# that position. If its larger, we remove its size from the
1052
# distribution chart
1053
next_pack_rev_count, next_pack = existing_packs.pop(0)
1054
if next_pack_rev_count >= pack_distribution[0]:
1055
# this is already packed 'better' than this, so we can
1056
# not waste time packing it.
1057
while next_pack_rev_count > 0:
1058
next_pack_rev_count -= pack_distribution[0]
1059
if next_pack_rev_count >= 0:
1061
del pack_distribution[0]
1063
# didn't use that entire bucket up
1064
pack_distribution[0] = -next_pack_rev_count
1066
# add the revisions we're going to add to the next output pack
1067
pack_operations[-1][0] += next_pack_rev_count
1068
# allocate this pack to the next pack sub operation
1069
pack_operations[-1][1].append(next_pack)
1070
if pack_operations[-1][0] >= pack_distribution[0]:
1071
# this pack is used up, shift left.
1072
del pack_distribution[0]
1073
pack_operations.append([0, []])
1075
return pack_operations
1077
def ensure_loaded(self):
1078
# NB: if you see an assertion error here, its probably access against
1079
# an unlocked repo. Naughty.
1080
assert self.repo.is_locked()
1081
if self._names is None:
1083
self._packs_at_load = set()
1084
for index, key, value in self._iter_disk_pack_index():
1086
self._names[name] = self._parse_index_sizes(value)
1087
self._packs_at_load.add((key, value))
1088
# populate all the metadata.
1091
def _parse_index_sizes(self, value):
1092
"""Parse a string of index sizes."""
1093
return tuple([int(digits) for digits in value.split(' ')])
1095
def get_pack_by_name(self, name):
1096
"""Get a Pack object by name.
1098
:param name: The name of the pack - e.g. '123456'
1099
:return: A Pack object.
1102
return self._packs_by_name[name]
1104
rev_index = self._make_index(name, '.rix')
1105
inv_index = self._make_index(name, '.iix')
1106
txt_index = self._make_index(name, '.tix')
1107
sig_index = self._make_index(name, '.six')
1108
result = ExistingPack(self._pack_transport, name, rev_index,
1109
inv_index, txt_index, sig_index)
1110
self.add_pack_to_memory(result)
1113
def allocate(self, a_new_pack):
1114
"""Allocate name in the list of packs.
1116
:param a_new_pack: A NewPack instance to be added to the collection of
1117
packs for this repository.
1119
self.ensure_loaded()
1120
if a_new_pack.name in self._names:
1121
raise errors.BzrError(
1122
'Pack %r already exists in %s' % (a_new_pack.name, self))
1123
self._names[a_new_pack.name] = tuple(a_new_pack.index_sizes)
1124
self.add_pack_to_memory(a_new_pack)
1126
def _iter_disk_pack_index(self):
1127
"""Iterate over the contents of the pack-names index.
1129
This is used when loading the list from disk, and before writing to
1130
detect updates from others during our write operation.
1131
:return: An iterator of the index contents.
1133
return GraphIndex(self.transport, 'pack-names', None
1134
).iter_all_entries()
1136
def _make_index(self, name, suffix):
1137
size_offset = self._suffix_offsets[suffix]
1138
index_name = name + suffix
1139
index_size = self._names[name][size_offset]
1141
self._index_transport, index_name, index_size)
1143
def _max_pack_count(self, total_revisions):
1144
"""Return the maximum number of packs to use for total revisions.
1146
:param total_revisions: The total number of revisions in the
1149
if not total_revisions:
1151
digits = str(total_revisions)
1153
for digit in digits:
1154
result += int(digit)
1158
"""Provide an order to the underlying names."""
1159
return sorted(self._names.keys())
1161
def _obsolete_packs(self, packs):
1162
"""Move a number of packs which have been obsoleted out of the way.
1164
Each pack and its associated indices are moved out of the way.
1166
Note: for correctness this function should only be called after a new
1167
pack names index has been written without these pack names, and with
1168
the names of packs that contain the data previously available via these
1171
:param packs: The packs to obsolete.
1172
:param return: None.
1175
pack.pack_transport.rename(pack.file_name(),
1176
'../obsolete_packs/' + pack.file_name())
1177
# TODO: Probably needs to know all possible indices for this pack
1178
# - or maybe list the directory and move all indices matching this
1179
# name whether we recognize it or not?
1180
for suffix in ('.iix', '.six', '.tix', '.rix'):
1181
self._index_transport.rename(pack.name + suffix,
1182
'../obsolete_packs/' + pack.name + suffix)
1184
def pack_distribution(self, total_revisions):
1185
"""Generate a list of the number of revisions to put in each pack.
1187
:param total_revisions: The total number of revisions in the
1190
if total_revisions == 0:
1192
digits = reversed(str(total_revisions))
1194
for exponent, count in enumerate(digits):
1195
size = 10 ** exponent
1196
for pos in range(int(count)):
1198
return list(reversed(result))
1200
def _pack_tuple(self, name):
1201
"""Return a tuple with the transport and file name for a pack name."""
1202
return self._pack_transport, name + '.pack'
1204
def _remove_pack_from_memory(self, pack):
1205
"""Remove pack from the packs accessed by this repository.
1207
Only affects memory state, until self._save_pack_names() is invoked.
1209
self._names.pop(pack.name)
1210
self._packs_by_name.pop(pack.name)
1211
self._remove_pack_indices(pack)
1213
def _remove_pack_indices(self, pack):
1214
"""Remove the indices for pack from the aggregated indices."""
1215
self.revision_index.remove_index(pack.revision_index, pack)
1216
self.inventory_index.remove_index(pack.inventory_index, pack)
1217
self.text_index.remove_index(pack.text_index, pack)
1218
self.signature_index.remove_index(pack.signature_index, pack)
1221
"""Clear all cached data."""
1222
# cached revision data
1223
self.repo._revision_knit = None
1224
self.revision_index.clear()
1225
# cached signature data
1226
self.repo._signature_knit = None
1227
self.signature_index.clear()
1228
# cached file text data
1229
self.text_index.clear()
1230
self.repo._text_knit = None
1231
# cached inventory data
1232
self.inventory_index.clear()
1233
# remove the open pack
1234
self._new_pack = None
1235
# information about packs.
1238
self._packs_by_name = {}
1239
self._packs_at_load = None
1241
def _make_index_map(self, index_suffix):
1242
"""Return information on existing indices.
1244
:param suffix: Index suffix added to pack name.
1246
:returns: (pack_map, indices) where indices is a list of GraphIndex
1247
objects, and pack_map is a mapping from those objects to the
1248
pack tuple they describe.
1250
# TODO: stop using this; it creates new indices unnecessarily.
1251
self.ensure_loaded()
1252
suffix_map = {'.rix': 'revision_index',
1253
'.six': 'signature_index',
1254
'.iix': 'inventory_index',
1255
'.tix': 'text_index',
1257
return self._packs_list_to_pack_map_and_index_list(self.all_packs(),
1258
suffix_map[index_suffix])
1260
def _packs_list_to_pack_map_and_index_list(self, packs, index_attribute):
1261
"""Convert a list of packs to an index pack map and index list.
1263
:param packs: The packs list to process.
1264
:param index_attribute: The attribute that the desired index is found
1266
:return: A tuple (map, list) where map contains the dict from
1267
index:pack_tuple, and lsit contains the indices in the same order
1273
index = getattr(pack, index_attribute)
1274
indices.append(index)
1275
pack_map[index] = (pack.pack_transport, pack.file_name())
1276
return pack_map, indices
1278
def _index_contents(self, pack_map, key_filter=None):
1279
"""Get an iterable of the index contents from a pack_map.
1281
:param pack_map: A map from indices to pack details.
1282
:param key_filter: An optional filter to limit the
1285
indices = [index for index in pack_map.iterkeys()]
1286
all_index = CombinedGraphIndex(indices)
1287
if key_filter is None:
1288
return all_index.iter_all_entries()
1290
return all_index.iter_entries(key_filter)
1292
def _unlock_names(self):
1293
"""Release the mutex around the pack-names index."""
1294
self.repo.control_files.unlock()
1296
def _save_pack_names(self, clear_obsolete_packs=False):
1297
"""Save the list of packs.
1299
This will take out the mutex around the pack names list for the
1300
duration of the method call. If concurrent updates have been made, a
1301
three-way merge between the current list and the current in memory list
1304
:param clear_obsolete_packs: If True, clear out the contents of the
1305
obsolete_packs directory.
1309
builder = GraphIndexBuilder()
1310
# load the disk nodes across
1312
for index, key, value in self._iter_disk_pack_index():
1313
disk_nodes.add((key, value))
1314
# do a two-way diff against our original content
1315
current_nodes = set()
1316
for name, sizes in self._names.iteritems():
1318
((name, ), ' '.join(str(size) for size in sizes)))
1319
deleted_nodes = self._packs_at_load - current_nodes
1320
new_nodes = current_nodes - self._packs_at_load
1321
disk_nodes.difference_update(deleted_nodes)
1322
disk_nodes.update(new_nodes)
1323
# TODO: handle same-name, index-size-changes here -
1324
# e.g. use the value from disk, not ours, *unless* we're the one
1326
for key, value in disk_nodes:
1327
builder.add_node(key, value)
1328
self.transport.put_file('pack-names', builder.finish(),
1329
mode=self.repo.control_files._file_mode)
1330
# move the baseline forward
1331
self._packs_at_load = disk_nodes
1332
# now clear out the obsolete packs directory
1333
if clear_obsolete_packs:
1334
self.transport.clone('obsolete_packs').delete_multi(
1335
self.transport.list_dir('obsolete_packs'))
1337
self._unlock_names()
1338
# synchronise the memory packs list with what we just wrote:
1339
new_names = dict(disk_nodes)
1340
# drop no longer present nodes
1341
for pack in self.all_packs():
1342
if (pack.name,) not in new_names:
1343
self._remove_pack_from_memory(pack)
1344
# add new nodes/refresh existing ones
1345
for key, value in disk_nodes:
1347
sizes = self._parse_index_sizes(value)
1348
if name in self._names:
1350
if sizes != self._names[name]:
1351
# the pack for name has had its indices replaced - rare but
1352
# important to handle. XXX: probably can never happen today
1353
# because the three-way merge code above does not handle it
1354
# - you may end up adding the same key twice to the new
1355
# disk index because the set values are the same, unless
1356
# the only index shows up as deleted by the set difference
1357
# - which it may. Until there is a specific test for this,
1358
# assume its broken. RBC 20071017.
1359
self._remove_pack_from_memory(self.get_pack_by_name(name))
1360
self._names[name] = sizes
1361
self.get_pack_by_name(name)
1364
self._names[name] = sizes
1365
self.get_pack_by_name(name)
1367
def _start_write_group(self):
1368
# Do not permit preparation for writing if we're not in a 'write lock'.
1369
if not self.repo.is_write_locked():
1370
raise errors.NotWriteLocked(self)
1371
self._new_pack = NewPack(self._upload_transport, self._index_transport,
1372
self._pack_transport, upload_suffix='.pack',
1373
file_mode=self.repo.control_files._file_mode)
1374
# allow writing: queue writes to a new index
1375
self.revision_index.add_writable_index(self._new_pack.revision_index,
1377
self.inventory_index.add_writable_index(self._new_pack.inventory_index,
1379
self.text_index.add_writable_index(self._new_pack.text_index,
1381
self.signature_index.add_writable_index(self._new_pack.signature_index,
1384
# reused revision and signature knits may need updating
1386
# "Hysterical raisins. client code in bzrlib grabs those knits outside
1387
# of write groups and then mutates it inside the write group."
1388
if self.repo._revision_knit is not None:
1389
self.repo._revision_knit._index._add_callback = \
1390
self.revision_index.add_callback
1391
if self.repo._signature_knit is not None:
1392
self.repo._signature_knit._index._add_callback = \
1393
self.signature_index.add_callback
1394
# create a reused knit object for text addition in commit.
1395
self.repo._text_knit = self.repo.weave_store.get_weave_or_empty(
1398
def _abort_write_group(self):
1399
# FIXME: just drop the transient index.
1400
# forget what names there are
1401
self._new_pack.abort()
1402
self._remove_pack_indices(self._new_pack)
1403
self._new_pack = None
1404
self.repo._text_knit = None
1406
def _commit_write_group(self):
1407
self._remove_pack_indices(self._new_pack)
1408
if self._new_pack.data_inserted():
1409
# get all the data to disk and read to use
1410
self._new_pack.finish()
1411
self.allocate(self._new_pack)
1412
self._new_pack = None
1413
if not self.autopack():
1414
# when autopack takes no steps, the names list is still
1416
self._save_pack_names()
1418
self._new_pack.abort()
1419
self._new_pack = None
1420
self.repo._text_knit = None
1423
class KnitPackRevisionStore(KnitRevisionStore):
1424
"""An object to adapt access from RevisionStore's to use KnitPacks.
1426
This class works by replacing the original RevisionStore.
1427
We need to do this because the KnitPackRevisionStore is less
1428
isolated in its layering - it uses services from the repo.
1431
def __init__(self, repo, transport, revisionstore):
1432
"""Create a KnitPackRevisionStore on repo with revisionstore.
1434
This will store its state in the Repository, use the
1435
indices to provide a KnitGraphIndex,
1436
and at the end of transactions write new indices.
1438
KnitRevisionStore.__init__(self, revisionstore.versioned_file_store)
1440
self._serializer = revisionstore._serializer
1441
self.transport = transport
1443
def get_revision_file(self, transaction):
1444
"""Get the revision versioned file object."""
1445
if getattr(self.repo, '_revision_knit', None) is not None:
1446
return self.repo._revision_knit
1447
self.repo._pack_collection.ensure_loaded()
1448
add_callback = self.repo._pack_collection.revision_index.add_callback
1449
# setup knit specific objects
1450
knit_index = KnitGraphIndex(
1451
self.repo._pack_collection.revision_index.combined_index,
1452
add_callback=add_callback)
1453
self.repo._revision_knit = knit.KnitVersionedFile(
1454
'revisions', self.transport.clone('..'),
1455
self.repo.control_files._file_mode,
1456
create=False, access_mode=self.repo._access_mode(),
1457
index=knit_index, delta=False, factory=knit.KnitPlainFactory(),
1458
access_method=self.repo._pack_collection.revision_index.knit_access)
1459
return self.repo._revision_knit
1461
def get_signature_file(self, transaction):
1462
"""Get the signature versioned file object."""
1463
if getattr(self.repo, '_signature_knit', None) is not None:
1464
return self.repo._signature_knit
1465
self.repo._pack_collection.ensure_loaded()
1466
add_callback = self.repo._pack_collection.signature_index.add_callback
1467
# setup knit specific objects
1468
knit_index = KnitGraphIndex(
1469
self.repo._pack_collection.signature_index.combined_index,
1470
add_callback=add_callback, parents=False)
1471
self.repo._signature_knit = knit.KnitVersionedFile(
1472
'signatures', self.transport.clone('..'),
1473
self.repo.control_files._file_mode,
1474
create=False, access_mode=self.repo._access_mode(),
1475
index=knit_index, delta=False, factory=knit.KnitPlainFactory(),
1476
access_method=self.repo._pack_collection.signature_index.knit_access)
1477
return self.repo._signature_knit
1480
class KnitPackTextStore(VersionedFileStore):
1481
"""Presents a TextStore abstraction on top of packs.
1483
This class works by replacing the original VersionedFileStore.
1484
We need to do this because the KnitPackRevisionStore is less
1485
isolated in its layering - it uses services from the repo and shares them
1486
with all the data written in a single write group.
1489
def __init__(self, repo, transport, weavestore):
1490
"""Create a KnitPackTextStore on repo with weavestore.
1492
This will store its state in the Repository, use the
1493
indices FileNames to provide a KnitGraphIndex,
1494
and at the end of transactions write new indices.
1496
# don't call base class constructor - it's not suitable.
1497
# no transient data stored in the transaction
1499
self._precious = False
1501
self.transport = transport
1502
self.weavestore = weavestore
1503
# XXX for check() which isn't updated yet
1504
self._transport = weavestore._transport
1506
def get_weave_or_empty(self, file_id, transaction):
1507
"""Get a 'Knit' backed by the .tix indices.
1509
The transaction parameter is ignored.
1511
self.repo._pack_collection.ensure_loaded()
1512
add_callback = self.repo._pack_collection.text_index.add_callback
1513
# setup knit specific objects
1514
file_id_index = GraphIndexPrefixAdapter(
1515
self.repo._pack_collection.text_index.combined_index,
1516
(file_id, ), 1, add_nodes_callback=add_callback)
1517
knit_index = KnitGraphIndex(file_id_index,
1518
add_callback=file_id_index.add_nodes,
1519
deltas=True, parents=True)
1520
return knit.KnitVersionedFile('text:' + file_id,
1521
self.transport.clone('..'),
1524
access_method=self.repo._pack_collection.text_index.knit_access,
1525
factory=knit.KnitPlainFactory())
1527
get_weave = get_weave_or_empty
1530
"""Generate a list of the fileids inserted, for use by check."""
1531
self.repo._pack_collection.ensure_loaded()
1533
for index, key, value, refs in \
1534
self.repo._pack_collection.text_index.combined_index.iter_all_entries():
1539
class InventoryKnitThunk(object):
1540
"""An object to manage thunking get_inventory_weave to pack based knits."""
1542
def __init__(self, repo, transport):
1543
"""Create an InventoryKnitThunk for repo at transport.
1545
This will store its state in the Repository, use the
1546
indices FileNames to provide a KnitGraphIndex,
1547
and at the end of transactions write a new index..
1550
self.transport = transport
1552
def get_weave(self):
1553
"""Get a 'Knit' that contains inventory data."""
1554
self.repo._pack_collection.ensure_loaded()
1555
add_callback = self.repo._pack_collection.inventory_index.add_callback
1556
# setup knit specific objects
1557
knit_index = KnitGraphIndex(
1558
self.repo._pack_collection.inventory_index.combined_index,
1559
add_callback=add_callback, deltas=True, parents=True)
1560
return knit.KnitVersionedFile(
1561
'inventory', self.transport.clone('..'),
1562
self.repo.control_files._file_mode,
1563
create=False, access_mode=self.repo._access_mode(),
1564
index=knit_index, delta=True, factory=knit.KnitPlainFactory(),
1565
access_method=self.repo._pack_collection.inventory_index.knit_access)
1568
class KnitPackRepository(KnitRepository):
1569
"""Experimental graph-knit using repository."""
1571
def __init__(self, _format, a_bzrdir, control_files, _revision_store,
1572
control_store, text_store, _commit_builder_class, _serializer):
1573
KnitRepository.__init__(self, _format, a_bzrdir, control_files,
1574
_revision_store, control_store, text_store, _commit_builder_class,
1576
index_transport = control_files._transport.clone('indices')
1577
self._pack_collection = RepositoryPackCollection(self, control_files._transport,
1579
control_files._transport.clone('upload'),
1580
control_files._transport.clone('packs'))
1581
self._revision_store = KnitPackRevisionStore(self, index_transport, self._revision_store)
1582
self.weave_store = KnitPackTextStore(self, index_transport, self.weave_store)
1583
self._inv_thunk = InventoryKnitThunk(self, index_transport)
1584
# True when the repository object is 'write locked' (as opposed to the
1585
# physical lock only taken out around changes to the pack-names list.)
1586
# Another way to represent this would be a decorator around the control
1587
# files object that presents logical locks as physical ones - if this
1588
# gets ugly consider that alternative design. RBC 20071011
1589
self._write_lock_count = 0
1590
self._transaction = None
1592
self._reconcile_does_inventory_gc = True
1593
self._reconcile_fixes_text_parents = False
1594
self._reconcile_backsup_inventory = False
1596
def _abort_write_group(self):
1597
self._pack_collection._abort_write_group()
1599
def _access_mode(self):
1600
"""Return 'w' or 'r' for depending on whether a write lock is active.
1602
This method is a helper for the Knit-thunking support objects.
1604
if self.is_write_locked():
1608
def _find_inconsistent_revision_parents(self):
1609
"""Find revisions with incorrectly cached parents.
1611
:returns: an iterator yielding tuples of (revison-id, parents-in-index,
1612
parents-in-revision).
1614
assert self.is_locked()
1615
pb = ui.ui_factory.nested_progress_bar()
1618
revision_nodes = self._pack_collection.revision_index \
1619
.combined_index.iter_all_entries()
1620
index_positions = []
1621
# Get the cached index values for all revisions, and also the location
1622
# in each index of the revision text so we can perform linear IO.
1623
for index, key, value, refs in revision_nodes:
1624
pos, length = value[1:].split(' ')
1625
index_positions.append((index, int(pos), key[0],
1626
tuple(parent[0] for parent in refs[0])))
1627
pb.update("Reading revision index.", 0, 0)
1628
index_positions.sort()
1629
batch_count = len(index_positions) / 1000 + 1
1630
pb.update("Checking cached revision graph.", 0, batch_count)
1631
for offset in xrange(batch_count):
1632
pb.update("Checking cached revision graph.", offset)
1633
to_query = index_positions[offset * 1000:(offset + 1) * 1000]
1636
rev_ids = [item[2] for item in to_query]
1637
revs = self.get_revisions(rev_ids)
1638
for revision, item in zip(revs, to_query):
1639
index_parents = item[3]
1640
rev_parents = tuple(revision.parent_ids)
1641
if index_parents != rev_parents:
1642
result.append((revision.revision_id, index_parents, rev_parents))
1647
def get_parents(self, revision_ids):
1648
"""See StackedParentsProvider.get_parents.
1650
This implementation accesses the combined revision index to provide
1653
self._pack_collection.ensure_loaded()
1654
index = self._pack_collection.revision_index.combined_index
1656
for revision_id in revision_ids:
1657
if revision_id != _mod_revision.NULL_REVISION:
1658
search_keys.add((revision_id,))
1659
found_parents = {_mod_revision.NULL_REVISION:[]}
1660
for index, key, value, refs in index.iter_entries(search_keys):
1663
parents = (_mod_revision.NULL_REVISION,)
1665
parents = tuple(parent[0] for parent in parents)
1666
found_parents[key[0]] = parents
1668
for revision_id in revision_ids:
1670
result.append(found_parents[revision_id])
1675
def _make_parents_provider(self):
1678
def _refresh_data(self):
1679
if self._write_lock_count == 1 or (
1680
self.control_files._lock_count == 1 and
1681
self.control_files._lock_mode == 'r'):
1682
# forget what names there are
1683
self._pack_collection.reset()
1684
# XXX: Better to do an in-memory merge when acquiring a new lock -
1685
# factor out code from _save_pack_names.
1686
self._pack_collection.ensure_loaded()
1688
def _start_write_group(self):
1689
self._pack_collection._start_write_group()
1691
def _commit_write_group(self):
1692
return self._pack_collection._commit_write_group()
1694
def get_inventory_weave(self):
1695
return self._inv_thunk.get_weave()
1697
def get_transaction(self):
1698
if self._write_lock_count:
1699
return self._transaction
1701
return self.control_files.get_transaction()
1703
def is_locked(self):
1704
return self._write_lock_count or self.control_files.is_locked()
1706
def is_write_locked(self):
1707
return self._write_lock_count
1709
def lock_write(self, token=None):
1710
if not self._write_lock_count and self.is_locked():
1711
raise errors.ReadOnlyError(self)
1712
self._write_lock_count += 1
1713
if self._write_lock_count == 1:
1714
from bzrlib import transactions
1715
self._transaction = transactions.WriteTransaction()
1716
self._refresh_data()
1718
def lock_read(self):
1719
if self._write_lock_count:
1720
self._write_lock_count += 1
1722
self.control_files.lock_read()
1723
self._refresh_data()
1725
def leave_lock_in_place(self):
1726
# not supported - raise an error
1727
raise NotImplementedError(self.leave_lock_in_place)
1729
def dont_leave_lock_in_place(self):
1730
# not supported - raise an error
1731
raise NotImplementedError(self.dont_leave_lock_in_place)
1735
"""Compress the data within the repository.
1737
This will pack all the data to a single pack. In future it may
1738
recompress deltas or do other such expensive operations.
1740
self._pack_collection.pack()
1743
def reconcile(self, other=None, thorough=False):
1744
"""Reconcile this repository."""
1745
from bzrlib.reconcile import PackReconciler
1746
reconciler = PackReconciler(self, thorough=thorough)
1747
reconciler.reconcile()
1751
if self._write_lock_count == 1 and self._write_group is not None:
1752
self.abort_write_group()
1753
self._transaction = None
1754
self._write_lock_count = 0
1755
raise errors.BzrError(
1756
'Must end write group before releasing write lock on %s'
1758
if self._write_lock_count:
1759
self._write_lock_count -= 1
1760
if not self._write_lock_count:
1761
transaction = self._transaction
1762
self._transaction = None
1763
transaction.finish()
1765
self.control_files.unlock()
1768
class RepositoryFormatPack(MetaDirRepositoryFormat):
1769
"""Format logic for pack structured repositories.
1771
This repository format has:
1772
- a list of packs in pack-names
1773
- packs in packs/NAME.pack
1774
- indices in indices/NAME.{iix,six,tix,rix}
1775
- knit deltas in the packs, knit indices mapped to the indices.
1776
- thunk objects to support the knits programming API.
1777
- a format marker of its own
1778
- an optional 'shared-storage' flag
1779
- an optional 'no-working-trees' flag
1783
# Set this attribute in derived classes to control the repository class
1784
# created by open and initialize.
1785
repository_class = None
1786
# Set this attribute in derived classes to control the
1787
# _commit_builder_class that the repository objects will have passed to
1788
# their constructor.
1789
_commit_builder_class = None
1790
# Set this attribute in derived clases to control the _serializer that the
1791
# repository objects will have passed to their constructor.
1794
def _get_control_store(self, repo_transport, control_files):
1795
"""Return the control store for this repository."""
1796
return VersionedFileStore(
1799
file_mode=control_files._file_mode,
1800
versionedfile_class=knit.KnitVersionedFile,
1801
versionedfile_kwargs={'factory': knit.KnitPlainFactory()},
1804
def _get_revision_store(self, repo_transport, control_files):
1805
"""See RepositoryFormat._get_revision_store()."""
1806
versioned_file_store = VersionedFileStore(
1808
file_mode=control_files._file_mode,
1811
versionedfile_class=knit.KnitVersionedFile,
1812
versionedfile_kwargs={'delta': False,
1813
'factory': knit.KnitPlainFactory(),
1817
return KnitRevisionStore(versioned_file_store)
1819
def _get_text_store(self, transport, control_files):
1820
"""See RepositoryFormat._get_text_store()."""
1821
return self._get_versioned_file_store('knits',
1824
versionedfile_class=knit.KnitVersionedFile,
1825
versionedfile_kwargs={
1826
'create_parent_dir': True,
1827
'delay_create': True,
1828
'dir_mode': control_files._dir_mode,
1832
def initialize(self, a_bzrdir, shared=False):
1833
"""Create a pack based repository.
1835
:param a_bzrdir: bzrdir to contain the new repository; must already
1837
:param shared: If true the repository will be initialized as a shared
1840
mutter('creating repository in %s.', a_bzrdir.transport.base)
1841
dirs = ['indices', 'obsolete_packs', 'packs', 'upload']
1842
builder = GraphIndexBuilder()
1843
files = [('pack-names', builder.finish())]
1844
utf8_files = [('format', self.get_format_string())]
1846
self._upload_blank_content(a_bzrdir, dirs, files, utf8_files, shared)
1847
return self.open(a_bzrdir=a_bzrdir, _found=True)
1849
def open(self, a_bzrdir, _found=False, _override_transport=None):
1850
"""See RepositoryFormat.open().
1852
:param _override_transport: INTERNAL USE ONLY. Allows opening the
1853
repository at a slightly different url
1854
than normal. I.e. during 'upgrade'.
1857
format = RepositoryFormat.find_format(a_bzrdir)
1858
assert format.__class__ == self.__class__
1859
if _override_transport is not None:
1860
repo_transport = _override_transport
1862
repo_transport = a_bzrdir.get_repository_transport(None)
1863
control_files = lockable_files.LockableFiles(repo_transport,
1864
'lock', lockdir.LockDir)
1865
text_store = self._get_text_store(repo_transport, control_files)
1866
control_store = self._get_control_store(repo_transport, control_files)
1867
_revision_store = self._get_revision_store(repo_transport, control_files)
1868
return self.repository_class(_format=self,
1870
control_files=control_files,
1871
_revision_store=_revision_store,
1872
control_store=control_store,
1873
text_store=text_store,
1874
_commit_builder_class=self._commit_builder_class,
1875
_serializer=self._serializer)
1878
class RepositoryFormatKnitPack1(RepositoryFormatPack):
1879
"""A no-subtrees parameterised Pack repository.
1881
This format was introduced in 0.92.
1884
repository_class = KnitPackRepository
1885
_commit_builder_class = PackCommitBuilder
1886
_serializer = xml5.serializer_v5
1888
def _get_matching_bzrdir(self):
1889
return bzrdir.format_registry.make_bzrdir('pack-0.92')
1891
def _ignore_setting_bzrdir(self, format):
1894
_matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
1896
def get_format_string(self):
1897
"""See RepositoryFormat.get_format_string()."""
1898
return "Bazaar pack repository format 1 (needs bzr 0.92)\n"
1900
def get_format_description(self):
1901
"""See RepositoryFormat.get_format_description()."""
1902
return "Packs containing knits without subtree support"
1904
def check_conversion_target(self, target_format):
1908
class RepositoryFormatKnitPack3(RepositoryFormatPack):
1909
"""A subtrees parameterised Pack repository.
1911
This repository format uses the xml7 serializer to get:
1912
- support for recording full info about the tree root
1913
- support for recording tree-references
1915
This format was introduced in 0.92.
1918
repository_class = KnitPackRepository
1919
_commit_builder_class = PackRootCommitBuilder
1920
rich_root_data = True
1921
supports_tree_reference = True
1922
_serializer = xml7.serializer_v7
1924
def _get_matching_bzrdir(self):
1925
return bzrdir.format_registry.make_bzrdir(
1926
'pack-0.92-subtree')
1928
def _ignore_setting_bzrdir(self, format):
1931
_matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
1933
def check_conversion_target(self, target_format):
1934
if not target_format.rich_root_data:
1935
raise errors.BadConversionTarget(
1936
'Does not support rich root data.', target_format)
1937
if not getattr(target_format, 'supports_tree_reference', False):
1938
raise errors.BadConversionTarget(
1939
'Does not support nested trees', target_format)
1941
def get_format_string(self):
1942
"""See RepositoryFormat.get_format_string()."""
1943
return "Bazaar pack repository format 1 with subtree support (needs bzr 0.92)\n"
1945
def get_format_description(self):
1946
"""See RepositoryFormat.get_format_description()."""
1947
return "Packs containing knits with subtree support\n"
1950
class RepositoryFormatKnitPack4(RepositoryFormatPack):
1951
"""A rich-root, no subtrees parameterised Pack repository.
1953
This repository format uses the xml6 serializer to get:
1954
- support for recording full info about the tree root
1956
This format was introduced in 1.0.
1959
repository_class = KnitPackRepository
1960
_commit_builder_class = PackRootCommitBuilder
1961
rich_root_data = True
1962
supports_tree_reference = False
1963
_serializer = xml6.serializer_v6
1965
def _get_matching_bzrdir(self):
1966
return bzrdir.format_registry.make_bzrdir(
1969
def _ignore_setting_bzrdir(self, format):
1972
_matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
1974
def check_conversion_target(self, target_format):
1975
if not target_format.rich_root_data:
1976
raise errors.BadConversionTarget(
1977
'Does not support rich root data.', target_format)
1979
def get_format_string(self):
1980
"""See RepositoryFormat.get_format_string()."""
1981
return ("Bazaar pack repository format 1 with rich root"
1982
" (needs bzr 1.0)\n")
1984
def get_format_description(self):
1985
"""See RepositoryFormat.get_format_description()."""
1986
return "Packs containing knits with rich root support\n"