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)
377
"""Flush any current data."""
379
bytes = ''.join(self._buffer[0])
380
self.write_stream.write(bytes)
381
self._hash.update(bytes)
382
self._buffer[:] = [[], 0]
384
def index_name(self, index_type, name):
385
"""Get the disk name of an index type for pack name 'name'."""
386
return name + NewPack.index_definitions[index_type][0]
388
def index_offset(self, index_type):
389
"""Get the position in a index_size array for a given index type."""
390
return NewPack.index_definitions[index_type][1]
392
def _replace_index_with_readonly(self, index_type):
393
setattr(self, index_type + '_index',
394
GraphIndex(self.index_transport,
395
self.index_name(index_type, self.name),
396
self.index_sizes[self.index_offset(index_type)]))
398
def set_write_cache_size(self, size):
399
self._cache_limit = size
401
def _write_index(self, index_type, index, label):
402
"""Write out an index.
404
:param index_type: The type of index to write - e.g. 'revision'.
405
:param index: The index object to serialise.
406
:param label: What label to give the index e.g. 'revision'.
408
index_name = self.index_name(index_type, self.name)
409
self.index_sizes[self.index_offset(index_type)] = \
410
self.index_transport.put_file(index_name, index.finish(),
411
mode=self._file_mode)
412
if 'pack' in debug.debug_flags:
413
# XXX: size might be interesting?
414
mutter('%s: create_pack: wrote %s index: %s%s t+%6.3fs',
415
time.ctime(), label, self.upload_transport.base,
416
self.random_name, time.time() - self.start_time)
417
# Replace the writable index on this object with a readonly,
418
# presently unloaded index. We should alter
419
# the index layer to make its finish() error if add_node is
420
# subsequently used. RBC
421
self._replace_index_with_readonly(index_type)
424
class AggregateIndex(object):
425
"""An aggregated index for the RepositoryPackCollection.
427
AggregateIndex is reponsible for managing the PackAccess object,
428
Index-To-Pack mapping, and all indices list for a specific type of index
429
such as 'revision index'.
431
A CombinedIndex provides an index on a single key space built up
432
from several on-disk indices. The AggregateIndex builds on this
433
to provide a knit access layer, and allows having up to one writable
434
index within the collection.
436
# XXX: Probably 'can be written to' could/should be separated from 'acts
437
# like a knit index' -- mbp 20071024
440
"""Create an AggregateIndex."""
441
self.index_to_pack = {}
442
self.combined_index = CombinedGraphIndex([])
443
self.knit_access = _PackAccess(self.index_to_pack)
445
def replace_indices(self, index_to_pack, indices):
446
"""Replace the current mappings with fresh ones.
448
This should probably not be used eventually, rather incremental add and
449
removal of indices. It has been added during refactoring of existing
452
:param index_to_pack: A mapping from index objects to
453
(transport, name) tuples for the pack file data.
454
:param indices: A list of indices.
456
# refresh the revision pack map dict without replacing the instance.
457
self.index_to_pack.clear()
458
self.index_to_pack.update(index_to_pack)
459
# XXX: API break - clearly a 'replace' method would be good?
460
self.combined_index._indices[:] = indices
461
# the current add nodes callback for the current writable index if
463
self.add_callback = None
465
def add_index(self, index, pack):
466
"""Add index to the aggregate, which is an index for Pack pack.
468
Future searches on the aggregate index will seach this new index
469
before all previously inserted indices.
471
:param index: An Index for the pack.
472
:param pack: A Pack instance.
474
# expose it to the index map
475
self.index_to_pack[index] = pack.access_tuple()
476
# put it at the front of the linear index list
477
self.combined_index.insert_index(0, index)
479
def add_writable_index(self, index, pack):
480
"""Add an index which is able to have data added to it.
482
There can be at most one writable index at any time. Any
483
modifications made to the knit are put into this index.
485
:param index: An index from the pack parameter.
486
:param pack: A Pack instance.
488
assert self.add_callback is None, \
489
"%s already has a writable index through %s" % \
490
(self, self.add_callback)
491
# allow writing: queue writes to a new index
492
self.add_index(index, pack)
493
# Updates the index to packs mapping as a side effect,
494
self.knit_access.set_writer(pack._writer, index, pack.access_tuple())
495
self.add_callback = index.add_nodes
498
"""Reset all the aggregate data to nothing."""
499
self.knit_access.set_writer(None, None, (None, None))
500
self.index_to_pack.clear()
501
del self.combined_index._indices[:]
502
self.add_callback = None
504
def remove_index(self, index, pack):
505
"""Remove index from the indices used to answer queries.
507
:param index: An index from the pack parameter.
508
:param pack: A Pack instance.
510
del self.index_to_pack[index]
511
self.combined_index._indices.remove(index)
512
if (self.add_callback is not None and
513
getattr(index, 'add_nodes', None) == self.add_callback):
514
self.add_callback = None
515
self.knit_access.set_writer(None, None, (None, None))
518
class Packer(object):
519
"""Create a pack from packs."""
521
def __init__(self, pack_collection, packs, suffix, revision_ids=None):
524
:param pack_collection: A RepositoryPackCollection object where the
525
new pack is being written to.
526
:param packs: The packs to combine.
527
:param suffix: The suffix to use on the temporary files for the pack.
528
:param revision_ids: Revision ids to limit the pack to.
532
self.revision_ids = revision_ids
533
# The pack object we are creating.
535
self._pack_collection = pack_collection
536
# The index layer keys for the revisions being copied. None for 'all
538
self._revision_keys = None
539
# What text keys to copy. None for 'all texts'. This is set by
540
# _copy_inventory_texts
541
self._text_filter = None
544
def _extra_init(self):
545
"""A template hook to allow extending the constructor trivially."""
547
def pack(self, pb=None):
548
"""Create a new pack by reading data from other packs.
550
This does little more than a bulk copy of data. One key difference
551
is that data with the same item key across multiple packs is elided
552
from the output. The new pack is written into the current pack store
553
along with its indices, and the name added to the pack names. The
554
source packs are not altered and are not required to be in the current
557
:param pb: An optional progress bar to use. A nested bar is created if
559
:return: A Pack object, or None if nothing was copied.
561
# open a pack - using the same name as the last temporary file
562
# - which has already been flushed, so its safe.
563
# XXX: - duplicate code warning with start_write_group; fix before
564
# considering 'done'.
565
if self._pack_collection._new_pack is not None:
566
raise errors.BzrError('call to create_pack_from_packs while '
567
'another pack is being written.')
568
if self.revision_ids is not None:
569
if len(self.revision_ids) == 0:
570
# silly fetch request.
573
self.revision_ids = frozenset(self.revision_ids)
575
self.pb = ui.ui_factory.nested_progress_bar()
579
return self._create_pack_from_packs()
585
"""Open a pack for the pack we are creating."""
586
return NewPack(self._pack_collection._upload_transport,
587
self._pack_collection._index_transport,
588
self._pack_collection._pack_transport, upload_suffix=self.suffix,
589
file_mode=self._pack_collection.repo.control_files._file_mode)
591
def _copy_revision_texts(self):
592
"""Copy revision data to the new pack."""
594
if self.revision_ids:
595
revision_keys = [(revision_id,) for revision_id in self.revision_ids]
598
# select revision keys
599
revision_index_map = self._pack_collection._packs_list_to_pack_map_and_index_list(
600
self.packs, 'revision_index')[0]
601
revision_nodes = self._pack_collection._index_contents(revision_index_map, revision_keys)
602
# copy revision keys and adjust values
603
self.pb.update("Copying revision texts", 1)
604
list(self._copy_nodes_graph(revision_nodes, revision_index_map,
605
self.new_pack._writer, self.new_pack.revision_index))
606
if 'pack' in debug.debug_flags:
607
mutter('%s: create_pack: revisions copied: %s%s %d items t+%6.3fs',
608
time.ctime(), self._pack_collection._upload_transport.base,
609
self.new_pack.random_name,
610
self.new_pack.revision_index.key_count(),
611
time.time() - self.new_pack.start_time)
612
self._revision_keys = revision_keys
614
def _copy_inventory_texts(self):
615
"""Copy the inventory texts to the new pack.
617
self._revision_keys is used to determine what inventories to copy.
619
Sets self._text_filter appropriately.
621
# select inventory keys
622
inv_keys = self._revision_keys # currently the same keyspace, and note that
623
# querying for keys here could introduce a bug where an inventory item
624
# is missed, so do not change it to query separately without cross
625
# checking like the text key check below.
626
inventory_index_map = self._pack_collection._packs_list_to_pack_map_and_index_list(
627
self.packs, 'inventory_index')[0]
628
inv_nodes = self._pack_collection._index_contents(inventory_index_map, inv_keys)
629
# copy inventory keys and adjust values
630
# XXX: Should be a helper function to allow different inv representation
632
self.pb.update("Copying inventory texts", 2)
633
inv_lines = self._copy_nodes_graph(inv_nodes, inventory_index_map,
634
self.new_pack._writer, self.new_pack.inventory_index, output_lines=True)
635
if self.revision_ids:
636
self._process_inventory_lines(inv_lines)
638
# eat the iterator to cause it to execute.
640
self._text_filter = None
641
if 'pack' in debug.debug_flags:
642
mutter('%s: create_pack: inventories copied: %s%s %d items t+%6.3fs',
643
time.ctime(), self._pack_collection._upload_transport.base,
644
self.new_pack.random_name,
645
self.new_pack.inventory_index.key_count(),
646
time.time() - new_pack.start_time)
648
def _copy_text_texts(self):
650
text_index_map, text_nodes = self._get_text_nodes()
651
if self._text_filter is not None:
652
# We could return the keys copied as part of the return value from
653
# _copy_nodes_graph but this doesn't work all that well with the
654
# need to get line output too, so we check separately, and as we're
655
# going to buffer everything anyway, we check beforehand, which
656
# saves reading knit data over the wire when we know there are
658
text_nodes = set(text_nodes)
659
present_text_keys = set(_node[1] for _node in text_nodes)
660
missing_text_keys = set(self._text_filter) - present_text_keys
661
if missing_text_keys:
662
# TODO: raise a specific error that can handle many missing
664
a_missing_key = missing_text_keys.pop()
665
raise errors.RevisionNotPresent(a_missing_key[1],
667
# copy text keys and adjust values
668
self.pb.update("Copying content texts", 3)
669
list(self._copy_nodes_graph(text_nodes, text_index_map,
670
self.new_pack._writer, self.new_pack.text_index))
671
self._log_copied_texts()
673
def _create_pack_from_packs(self):
674
self.pb.update("Opening pack", 0, 5)
675
self.new_pack = self.open_pack()
676
new_pack = self.new_pack
677
# buffer data - we won't be reading-back during the pack creation and
678
# this makes a significant difference on sftp pushes.
679
new_pack.set_write_cache_size(1024*1024)
680
if 'pack' in debug.debug_flags:
681
plain_pack_list = ['%s%s' % (a_pack.pack_transport.base, a_pack.name)
682
for a_pack in self.packs]
683
if self.revision_ids is not None:
684
rev_count = len(self.revision_ids)
687
mutter('%s: create_pack: creating pack from source packs: '
688
'%s%s %s revisions wanted %s t=0',
689
time.ctime(), self._pack_collection._upload_transport.base, new_pack.random_name,
690
plain_pack_list, rev_count)
691
self._copy_revision_texts()
692
self._copy_inventory_texts()
693
self._copy_text_texts()
694
# select signature keys
695
signature_filter = self._revision_keys # same keyspace
696
signature_index_map = self._pack_collection._packs_list_to_pack_map_and_index_list(
697
self.packs, 'signature_index')[0]
698
signature_nodes = self._pack_collection._index_contents(signature_index_map,
700
# copy signature keys and adjust values
701
self.pb.update("Copying signature texts", 4)
702
self._copy_nodes(signature_nodes, signature_index_map, new_pack._writer,
703
new_pack.signature_index)
704
if 'pack' in debug.debug_flags:
705
mutter('%s: create_pack: revision signatures copied: %s%s %d items t+%6.3fs',
706
time.ctime(), self._pack_collection._upload_transport.base, new_pack.random_name,
707
new_pack.signature_index.key_count(),
708
time.time() - new_pack.start_time)
709
if not self._use_pack(new_pack):
712
self.pb.update("Finishing pack", 5)
714
self._pack_collection.allocate(new_pack)
717
def _copy_nodes(self, nodes, index_map, writer, write_index):
718
"""Copy knit nodes between packs with no graph references."""
719
pb = ui.ui_factory.nested_progress_bar()
721
return self._do_copy_nodes(nodes, index_map, writer,
726
def _do_copy_nodes(self, nodes, index_map, writer, write_index, pb):
727
# for record verification
728
knit_data = _KnitData(None)
729
# plan a readv on each source pack:
731
nodes = sorted(nodes)
732
# how to map this into knit.py - or knit.py into this?
733
# we don't want the typical knit logic, we want grouping by pack
734
# at this point - perhaps a helper library for the following code
735
# duplication points?
737
for index, key, value in nodes:
738
if index not in request_groups:
739
request_groups[index] = []
740
request_groups[index].append((key, value))
742
pb.update("Copied record", record_index, len(nodes))
743
for index, items in request_groups.iteritems():
744
pack_readv_requests = []
745
for key, value in items:
746
# ---- KnitGraphIndex.get_position
747
bits = value[1:].split(' ')
748
offset, length = int(bits[0]), int(bits[1])
749
pack_readv_requests.append((offset, length, (key, value[0])))
750
# linear scan up the pack
751
pack_readv_requests.sort()
753
transport, path = index_map[index]
754
reader = pack.make_readv_reader(transport, path,
755
[offset[0:2] for offset in pack_readv_requests])
756
for (names, read_func), (_1, _2, (key, eol_flag)) in \
757
izip(reader.iter_records(), pack_readv_requests):
758
raw_data = read_func(None)
759
# check the header only
760
df, _ = knit_data._parse_record_header(key[-1], raw_data)
762
pos, size = writer.add_bytes_record(raw_data, names)
763
write_index.add_node(key, eol_flag + "%d %d" % (pos, size))
764
pb.update("Copied record", record_index)
767
def _copy_nodes_graph(self, nodes, index_map, writer, write_index,
769
"""Copy knit nodes between packs.
771
:param output_lines: Return lines present in the copied data as
772
an iterator of line,version_id.
774
pb = ui.ui_factory.nested_progress_bar()
776
return self._do_copy_nodes_graph(nodes, index_map, writer,
777
write_index, output_lines, pb)
781
def _do_copy_nodes_graph(self, nodes, index_map, writer, write_index,
783
# for record verification
784
knit_data = _KnitData(None)
785
# for line extraction when requested (inventories only)
787
factory = knit.KnitPlainFactory()
788
# plan a readv on each source pack:
790
nodes = sorted(nodes)
791
# how to map this into knit.py - or knit.py into this?
792
# we don't want the typical knit logic, we want grouping by pack
793
# at this point - perhaps a helper library for the following code
794
# duplication points?
797
pb.update("Copied record", record_index, len(nodes))
798
for index, key, value, references in nodes:
799
if index not in request_groups:
800
request_groups[index] = []
801
request_groups[index].append((key, value, references))
802
for index, items in request_groups.iteritems():
803
pack_readv_requests = []
804
for key, value, references in items:
805
# ---- KnitGraphIndex.get_position
806
bits = value[1:].split(' ')
807
offset, length = int(bits[0]), int(bits[1])
808
pack_readv_requests.append((offset, length, (key, value[0], references)))
809
# linear scan up the pack
810
pack_readv_requests.sort()
812
transport, path = index_map[index]
813
reader = pack.make_readv_reader(transport, path,
814
[offset[0:2] for offset in pack_readv_requests])
815
for (names, read_func), (_1, _2, (key, eol_flag, references)) in \
816
izip(reader.iter_records(), pack_readv_requests):
817
raw_data = read_func(None)
820
# read the entire thing
821
content, _ = knit_data._parse_record(version_id, raw_data)
822
if len(references[-1]) == 0:
823
line_iterator = factory.get_fulltext_content(content)
825
line_iterator = factory.get_linedelta_content(content)
826
for line in line_iterator:
827
yield line, version_id
829
# check the header only
830
df, _ = knit_data._parse_record_header(version_id, raw_data)
832
pos, size = writer.add_bytes_record(raw_data, names)
833
write_index.add_node(key, eol_flag + "%d %d" % (pos, size), references)
834
pb.update("Copied record", record_index)
837
def _external_compression_parents_of_new_texts(self)
840
for node in self.new_pack.text_index.iter_all_entries():
842
refs.update(node[3][1])
845
def _get_text_nodes(self):
846
text_index_map = self._pack_collection._packs_list_to_pack_map_and_index_list(
847
self.packs, 'text_index')[0]
848
return text_index_map, self._pack_collection._index_contents(text_index_map,
851
def _log_copied_texts(self):
852
if 'pack' in debug.debug_flags:
853
mutter('%s: create_pack: file texts copied: %s%s %d items t+%6.3fs',
854
time.ctime(), self._pack_collection._upload_transport.base,
855
self.new_pack.random_name,
856
self.new_pack.text_index.key_count(),
857
time.time() - self.new_pack.start_time)
859
def _process_inventory_lines(self, inv_lines):
860
"""Use up the inv_lines generator and setup a text key filter."""
861
repo = self._pack_collection.repo
862
fileid_revisions = repo._find_file_ids_from_xml_inventory_lines(
863
inv_lines, self.revision_ids)
865
for fileid, file_revids in fileid_revisions.iteritems():
866
text_filter.extend([(fileid, file_revid) for file_revid in file_revids])
867
self._text_filter = text_filter
869
def _use_pack(self, new_pack):
870
"""Return True if new_pack should be used.
872
:param new_pack: The pack that has just been created.
873
:return: True if the pack should be used.
875
return new_pack.data_inserted()
878
class ReconcilePacker(Packer):
879
"""A packer which regenerates indices etc as it copies.
881
This is used by ``bzr reconcile`` to cause parent text pointers to be
885
def _extra_init(self):
886
self._data_changed = False
888
def _process_inventory_lines(self, inv_lines):
889
"""Generate a text key reference map rather for reconciling with."""
890
repo = self._pack_collection.repo
891
refs = repo._find_text_key_references_from_xml_inventory_lines(
893
self._text_refs = refs
894
# during reconcile we:
895
# - convert unreferenced texts to full texts
896
# - correct texts which reference a text not copied to be full texts
897
# - copy all others as-is but with corrected parents.
898
# - so at this point we don't know enough to decide what becomes a full
900
self._text_filter = None
902
def _copy_text_texts(self):
903
"""generate what texts we should have and then copy."""
904
self.pb.update("Copying content texts", 3)
905
# we have three major tasks here:
906
# 1) generate the ideal index
907
repo = self._pack_collection.repo
908
ideal_index = repo._generate_text_key_index(self._text_refs)
909
# 2) generate a text_nodes list that contains all the deltas that can
910
# be used as-is, with corrected parents.
914
NULL_REVISION = _mod_revision.NULL_REVISION
915
text_index_map, text_nodes = self._get_text_nodes()
916
for node in text_nodes:
922
ideal_parents = tuple(ideal_index[node[1]])
924
discarded_nodes.append(node)
925
self._data_changed = True
927
if ideal_parents == (NULL_REVISION,):
929
if ideal_parents == node[3][0]:
931
ok_nodes.append(node)
932
elif ideal_parents[0:1] == node[3][0][0:1]:
933
# the left most parent is the same, or there are no parents
934
# today. Either way, we can preserve the representation as
935
# long as we change the refs to be inserted.
936
self._data_changed = True
937
ok_nodes.append((node[0], node[1], node[2],
938
(ideal_parents, node[3][1])))
939
self._data_changed = True
941
# Reinsert this text completely
942
bad_texts.append((node[1], ideal_parents))
943
self._data_changed = True
944
# we're finished with some data.
947
# 3) bulk copy the ok data
948
list(self._copy_nodes_graph(ok_nodes, text_index_map,
949
self.new_pack._writer, self.new_pack.text_index))
950
# 3) adhoc copy all the other texts.
951
transaction = repo.get_transaction()
952
file_id_index = GraphIndexPrefixAdapter(
953
self.new_pack.text_index,
955
add_nodes_callback=self.new_pack.text_index.add_nodes)
956
knit_index = KnitGraphIndex(file_id_index,
957
add_callback=file_id_index.add_nodes,
958
deltas=True, parents=True)
959
output_knit = knit.KnitVersionedFile('reconcile-texts',
960
self._pack_collection.transport,
963
access_method=_PackAccess(
964
{self.new_pack.text_index:self.new_pack.access_tuple()},
965
(self.new_pack._writer, self.new_pack.text_index)),
966
factory=knit.KnitPlainFactory())
967
for key, parent_keys in bad_texts:
968
# We refer to the new pack to delta data being output.
969
# A possible improvement would be to catch errors on short reads
970
# and only flush then.
971
self.new_pack.flush()
973
for parent_key in parent_keys:
974
if parent_key[0] != key[0]:
975
# Graph parents must match the fileid
976
raise errors.BzrError('Mismatched key parent %r:%r' %
978
parents.append(parent_key[1])
979
source_weave = repo.weave_store.get_weave(key[0], transaction)
980
text_lines = source_weave.get_lines(key[1])
981
# adapt the 'knit' to the current file_id.
982
file_id_index = GraphIndexPrefixAdapter(
983
self.new_pack.text_index,
985
add_nodes_callback=self.new_pack.text_index.add_nodes)
986
knit_index._graph_index = file_id_index
987
knit_index._add_callback = file_id_index.add_nodes
988
output_knit.add_lines_with_ghosts(
989
key[1], parents, text_lines, random_id=True, check_content=False)
990
# 4) check that nothing inserted has a reference outside the keyspace.
991
missing_text_keys = self._external_compression_parents_of_new_texts()
992
if missing_text_keys:
993
raise errors.BzrError('Reference to missing compression parents %r'
995
self._log_copied_texts()
997
def _use_pack(self, new_pack):
998
"""Override _use_pack to check for reconcile having changed content."""
999
# XXX: we might be better checking this at the copy time.
1000
original_inventory_keys = set()
1001
inv_index = self._pack_collection.inventory_index.combined_index
1002
for entry in inv_index.iter_all_entries():
1003
original_inventory_keys.add(entry[1])
1004
new_inventory_keys = set()
1005
for entry in new_pack.inventory_index.iter_all_entries():
1006
new_inventory_keys.add(entry[1])
1007
if new_inventory_keys != original_inventory_keys:
1008
self._data_changed = True
1009
return new_pack.data_inserted() and self._data_changed
1012
class RepositoryPackCollection(object):
1013
"""Management of packs within a repository."""
1015
def __init__(self, repo, transport, index_transport, upload_transport,
1017
"""Create a new RepositoryPackCollection.
1019
:param transport: Addresses the repository base directory
1020
(typically .bzr/repository/).
1021
:param index_transport: Addresses the directory containing indices.
1022
:param upload_transport: Addresses the directory into which packs are written
1023
while they're being created.
1024
:param pack_transport: Addresses the directory of existing complete packs.
1027
self.transport = transport
1028
self._index_transport = index_transport
1029
self._upload_transport = upload_transport
1030
self._pack_transport = pack_transport
1031
self._suffix_offsets = {'.rix': 0, '.iix': 1, '.tix': 2, '.six': 3}
1034
self._packs_by_name = {}
1035
# the previous pack-names content
1036
self._packs_at_load = None
1037
# when a pack is being created by this object, the state of that pack.
1038
self._new_pack = None
1039
# aggregated revision index data
1040
self.revision_index = AggregateIndex()
1041
self.inventory_index = AggregateIndex()
1042
self.text_index = AggregateIndex()
1043
self.signature_index = AggregateIndex()
1045
def add_pack_to_memory(self, pack):
1046
"""Make a Pack object available to the repository to satisfy queries.
1048
:param pack: A Pack object.
1050
assert pack.name not in self._packs_by_name
1051
self.packs.append(pack)
1052
self._packs_by_name[pack.name] = pack
1053
self.revision_index.add_index(pack.revision_index, pack)
1054
self.inventory_index.add_index(pack.inventory_index, pack)
1055
self.text_index.add_index(pack.text_index, pack)
1056
self.signature_index.add_index(pack.signature_index, pack)
1058
def _add_text_to_weave(self, file_id, revision_id, new_lines, parents,
1059
nostore_sha, random_revid):
1060
file_id_index = GraphIndexPrefixAdapter(
1061
self.text_index.combined_index,
1063
add_nodes_callback=self.text_index.add_callback)
1064
self.repo._text_knit._index._graph_index = file_id_index
1065
self.repo._text_knit._index._add_callback = file_id_index.add_nodes
1066
return self.repo._text_knit.add_lines_with_ghosts(
1067
revision_id, parents, new_lines, nostore_sha=nostore_sha,
1068
random_id=random_revid, check_content=False)[0:2]
1070
def all_packs(self):
1071
"""Return a list of all the Pack objects this repository has.
1073
Note that an in-progress pack being created is not returned.
1075
:return: A list of Pack objects for all the packs in the repository.
1078
for name in self.names():
1079
result.append(self.get_pack_by_name(name))
1083
"""Pack the pack collection incrementally.
1085
This will not attempt global reorganisation or recompression,
1086
rather it will just ensure that the total number of packs does
1087
not grow without bound. It uses the _max_pack_count method to
1088
determine if autopacking is needed, and the pack_distribution
1089
method to determine the number of revisions in each pack.
1091
If autopacking takes place then the packs name collection will have
1092
been flushed to disk - packing requires updating the name collection
1093
in synchronisation with certain steps. Otherwise the names collection
1096
:return: True if packing took place.
1098
# XXX: Should not be needed when the management of indices is sane.
1099
total_revisions = self.revision_index.combined_index.key_count()
1100
total_packs = len(self._names)
1101
if self._max_pack_count(total_revisions) >= total_packs:
1103
# XXX: the following may want to be a class, to pack with a given
1105
mutter('Auto-packing repository %s, which has %d pack files, '
1106
'containing %d revisions into %d packs.', self, total_packs,
1107
total_revisions, self._max_pack_count(total_revisions))
1108
# determine which packs need changing
1109
pack_distribution = self.pack_distribution(total_revisions)
1111
for pack in self.all_packs():
1112
revision_count = pack.get_revision_count()
1113
if revision_count == 0:
1114
# revision less packs are not generated by normal operation,
1115
# only by operations like sign-my-commits, and thus will not
1116
# tend to grow rapdily or without bound like commit containing
1117
# packs do - leave them alone as packing them really should
1118
# group their data with the relevant commit, and that may
1119
# involve rewriting ancient history - which autopack tries to
1120
# avoid. Alternatively we could not group the data but treat
1121
# each of these as having a single revision, and thus add
1122
# one revision for each to the total revision count, to get
1123
# a matching distribution.
1125
existing_packs.append((revision_count, pack))
1126
pack_operations = self.plan_autopack_combinations(
1127
existing_packs, pack_distribution)
1128
self._execute_pack_operations(pack_operations)
1131
def _execute_pack_operations(self, pack_operations):
1132
"""Execute a series of pack operations.
1134
:param pack_operations: A list of [revision_count, packs_to_combine].
1137
for revision_count, packs in pack_operations:
1138
# we may have no-ops from the setup logic
1141
Packer(self, packs, '.autopack').pack()
1143
self._remove_pack_from_memory(pack)
1144
# record the newly available packs and stop advertising the old
1146
self._save_pack_names(clear_obsolete_packs=True)
1147
# Move the old packs out of the way now they are no longer referenced.
1148
for revision_count, packs in pack_operations:
1149
self._obsolete_packs(packs)
1151
def lock_names(self):
1152
"""Acquire the mutex around the pack-names index.
1154
This cannot be used in the middle of a read-only transaction on the
1157
self.repo.control_files.lock_write()
1160
"""Pack the pack collection totally."""
1161
self.ensure_loaded()
1162
total_packs = len(self._names)
1165
total_revisions = self.revision_index.combined_index.key_count()
1166
# XXX: the following may want to be a class, to pack with a given
1168
mutter('Packing repository %s, which has %d pack files, '
1169
'containing %d revisions into 1 packs.', self, total_packs,
1171
# determine which packs need changing
1172
pack_distribution = [1]
1173
pack_operations = [[0, []]]
1174
for pack in self.all_packs():
1175
revision_count = pack.get_revision_count()
1176
pack_operations[-1][0] += revision_count
1177
pack_operations[-1][1].append(pack)
1178
self._execute_pack_operations(pack_operations)
1180
def plan_autopack_combinations(self, existing_packs, pack_distribution):
1181
"""Plan a pack operation.
1183
:param existing_packs: The packs to pack. (A list of (revcount, Pack)
1185
:param pack_distribution: A list with the number of revisions desired
1188
if len(existing_packs) <= len(pack_distribution):
1190
existing_packs.sort(reverse=True)
1191
pack_operations = [[0, []]]
1192
# plan out what packs to keep, and what to reorganise
1193
while len(existing_packs):
1194
# take the largest pack, and if its less than the head of the
1195
# distribution chart we will include its contents in the new pack for
1196
# that position. If its larger, we remove its size from the
1197
# distribution chart
1198
next_pack_rev_count, next_pack = existing_packs.pop(0)
1199
if next_pack_rev_count >= pack_distribution[0]:
1200
# this is already packed 'better' than this, so we can
1201
# not waste time packing it.
1202
while next_pack_rev_count > 0:
1203
next_pack_rev_count -= pack_distribution[0]
1204
if next_pack_rev_count >= 0:
1206
del pack_distribution[0]
1208
# didn't use that entire bucket up
1209
pack_distribution[0] = -next_pack_rev_count
1211
# add the revisions we're going to add to the next output pack
1212
pack_operations[-1][0] += next_pack_rev_count
1213
# allocate this pack to the next pack sub operation
1214
pack_operations[-1][1].append(next_pack)
1215
if pack_operations[-1][0] >= pack_distribution[0]:
1216
# this pack is used up, shift left.
1217
del pack_distribution[0]
1218
pack_operations.append([0, []])
1220
return pack_operations
1222
def ensure_loaded(self):
1223
# NB: if you see an assertion error here, its probably access against
1224
# an unlocked repo. Naughty.
1225
assert self.repo.is_locked()
1226
if self._names is None:
1228
self._packs_at_load = set()
1229
for index, key, value in self._iter_disk_pack_index():
1231
self._names[name] = self._parse_index_sizes(value)
1232
self._packs_at_load.add((key, value))
1233
# populate all the metadata.
1236
def _parse_index_sizes(self, value):
1237
"""Parse a string of index sizes."""
1238
return tuple([int(digits) for digits in value.split(' ')])
1240
def get_pack_by_name(self, name):
1241
"""Get a Pack object by name.
1243
:param name: The name of the pack - e.g. '123456'
1244
:return: A Pack object.
1247
return self._packs_by_name[name]
1249
rev_index = self._make_index(name, '.rix')
1250
inv_index = self._make_index(name, '.iix')
1251
txt_index = self._make_index(name, '.tix')
1252
sig_index = self._make_index(name, '.six')
1253
result = ExistingPack(self._pack_transport, name, rev_index,
1254
inv_index, txt_index, sig_index)
1255
self.add_pack_to_memory(result)
1258
def allocate(self, a_new_pack):
1259
"""Allocate name in the list of packs.
1261
:param a_new_pack: A NewPack instance to be added to the collection of
1262
packs for this repository.
1264
self.ensure_loaded()
1265
if a_new_pack.name in self._names:
1266
raise errors.BzrError(
1267
'Pack %r already exists in %s' % (a_new_pack.name, self))
1268
self._names[a_new_pack.name] = tuple(a_new_pack.index_sizes)
1269
self.add_pack_to_memory(a_new_pack)
1271
def _iter_disk_pack_index(self):
1272
"""Iterate over the contents of the pack-names index.
1274
This is used when loading the list from disk, and before writing to
1275
detect updates from others during our write operation.
1276
:return: An iterator of the index contents.
1278
return GraphIndex(self.transport, 'pack-names', None
1279
).iter_all_entries()
1281
def _make_index(self, name, suffix):
1282
size_offset = self._suffix_offsets[suffix]
1283
index_name = name + suffix
1284
index_size = self._names[name][size_offset]
1286
self._index_transport, index_name, index_size)
1288
def _max_pack_count(self, total_revisions):
1289
"""Return the maximum number of packs to use for total revisions.
1291
:param total_revisions: The total number of revisions in the
1294
if not total_revisions:
1296
digits = str(total_revisions)
1298
for digit in digits:
1299
result += int(digit)
1303
"""Provide an order to the underlying names."""
1304
return sorted(self._names.keys())
1306
def _obsolete_packs(self, packs):
1307
"""Move a number of packs which have been obsoleted out of the way.
1309
Each pack and its associated indices are moved out of the way.
1311
Note: for correctness this function should only be called after a new
1312
pack names index has been written without these pack names, and with
1313
the names of packs that contain the data previously available via these
1316
:param packs: The packs to obsolete.
1317
:param return: None.
1320
pack.pack_transport.rename(pack.file_name(),
1321
'../obsolete_packs/' + pack.file_name())
1322
# TODO: Probably needs to know all possible indices for this pack
1323
# - or maybe list the directory and move all indices matching this
1324
# name whether we recognize it or not?
1325
for suffix in ('.iix', '.six', '.tix', '.rix'):
1326
self._index_transport.rename(pack.name + suffix,
1327
'../obsolete_packs/' + pack.name + suffix)
1329
def pack_distribution(self, total_revisions):
1330
"""Generate a list of the number of revisions to put in each pack.
1332
:param total_revisions: The total number of revisions in the
1335
if total_revisions == 0:
1337
digits = reversed(str(total_revisions))
1339
for exponent, count in enumerate(digits):
1340
size = 10 ** exponent
1341
for pos in range(int(count)):
1343
return list(reversed(result))
1345
def _pack_tuple(self, name):
1346
"""Return a tuple with the transport and file name for a pack name."""
1347
return self._pack_transport, name + '.pack'
1349
def _remove_pack_from_memory(self, pack):
1350
"""Remove pack from the packs accessed by this repository.
1352
Only affects memory state, until self._save_pack_names() is invoked.
1354
self._names.pop(pack.name)
1355
self._packs_by_name.pop(pack.name)
1356
self._remove_pack_indices(pack)
1358
def _remove_pack_indices(self, pack):
1359
"""Remove the indices for pack from the aggregated indices."""
1360
self.revision_index.remove_index(pack.revision_index, pack)
1361
self.inventory_index.remove_index(pack.inventory_index, pack)
1362
self.text_index.remove_index(pack.text_index, pack)
1363
self.signature_index.remove_index(pack.signature_index, pack)
1366
"""Clear all cached data."""
1367
# cached revision data
1368
self.repo._revision_knit = None
1369
self.revision_index.clear()
1370
# cached signature data
1371
self.repo._signature_knit = None
1372
self.signature_index.clear()
1373
# cached file text data
1374
self.text_index.clear()
1375
self.repo._text_knit = None
1376
# cached inventory data
1377
self.inventory_index.clear()
1378
# remove the open pack
1379
self._new_pack = None
1380
# information about packs.
1383
self._packs_by_name = {}
1384
self._packs_at_load = None
1386
def _make_index_map(self, index_suffix):
1387
"""Return information on existing indices.
1389
:param suffix: Index suffix added to pack name.
1391
:returns: (pack_map, indices) where indices is a list of GraphIndex
1392
objects, and pack_map is a mapping from those objects to the
1393
pack tuple they describe.
1395
# TODO: stop using this; it creates new indices unnecessarily.
1396
self.ensure_loaded()
1397
suffix_map = {'.rix': 'revision_index',
1398
'.six': 'signature_index',
1399
'.iix': 'inventory_index',
1400
'.tix': 'text_index',
1402
return self._packs_list_to_pack_map_and_index_list(self.all_packs(),
1403
suffix_map[index_suffix])
1405
def _packs_list_to_pack_map_and_index_list(self, packs, index_attribute):
1406
"""Convert a list of packs to an index pack map and index list.
1408
:param packs: The packs list to process.
1409
:param index_attribute: The attribute that the desired index is found
1411
:return: A tuple (map, list) where map contains the dict from
1412
index:pack_tuple, and lsit contains the indices in the same order
1418
index = getattr(pack, index_attribute)
1419
indices.append(index)
1420
pack_map[index] = (pack.pack_transport, pack.file_name())
1421
return pack_map, indices
1423
def _index_contents(self, pack_map, key_filter=None):
1424
"""Get an iterable of the index contents from a pack_map.
1426
:param pack_map: A map from indices to pack details.
1427
:param key_filter: An optional filter to limit the
1430
indices = [index for index in pack_map.iterkeys()]
1431
all_index = CombinedGraphIndex(indices)
1432
if key_filter is None:
1433
return all_index.iter_all_entries()
1435
return all_index.iter_entries(key_filter)
1437
def _unlock_names(self):
1438
"""Release the mutex around the pack-names index."""
1439
self.repo.control_files.unlock()
1441
def _save_pack_names(self, clear_obsolete_packs=False):
1442
"""Save the list of packs.
1444
This will take out the mutex around the pack names list for the
1445
duration of the method call. If concurrent updates have been made, a
1446
three-way merge between the current list and the current in memory list
1449
:param clear_obsolete_packs: If True, clear out the contents of the
1450
obsolete_packs directory.
1454
builder = GraphIndexBuilder()
1455
# load the disk nodes across
1457
for index, key, value in self._iter_disk_pack_index():
1458
disk_nodes.add((key, value))
1459
# do a two-way diff against our original content
1460
current_nodes = set()
1461
for name, sizes in self._names.iteritems():
1463
((name, ), ' '.join(str(size) for size in sizes)))
1464
deleted_nodes = self._packs_at_load - current_nodes
1465
new_nodes = current_nodes - self._packs_at_load
1466
disk_nodes.difference_update(deleted_nodes)
1467
disk_nodes.update(new_nodes)
1468
# TODO: handle same-name, index-size-changes here -
1469
# e.g. use the value from disk, not ours, *unless* we're the one
1471
for key, value in disk_nodes:
1472
builder.add_node(key, value)
1473
self.transport.put_file('pack-names', builder.finish(),
1474
mode=self.repo.control_files._file_mode)
1475
# move the baseline forward
1476
self._packs_at_load = disk_nodes
1477
# now clear out the obsolete packs directory
1478
if clear_obsolete_packs:
1479
self.transport.clone('obsolete_packs').delete_multi(
1480
self.transport.list_dir('obsolete_packs'))
1482
self._unlock_names()
1483
# synchronise the memory packs list with what we just wrote:
1484
new_names = dict(disk_nodes)
1485
# drop no longer present nodes
1486
for pack in self.all_packs():
1487
if (pack.name,) not in new_names:
1488
self._remove_pack_from_memory(pack)
1489
# add new nodes/refresh existing ones
1490
for key, value in disk_nodes:
1492
sizes = self._parse_index_sizes(value)
1493
if name in self._names:
1495
if sizes != self._names[name]:
1496
# the pack for name has had its indices replaced - rare but
1497
# important to handle. XXX: probably can never happen today
1498
# because the three-way merge code above does not handle it
1499
# - you may end up adding the same key twice to the new
1500
# disk index because the set values are the same, unless
1501
# the only index shows up as deleted by the set difference
1502
# - which it may. Until there is a specific test for this,
1503
# assume its broken. RBC 20071017.
1504
self._remove_pack_from_memory(self.get_pack_by_name(name))
1505
self._names[name] = sizes
1506
self.get_pack_by_name(name)
1509
self._names[name] = sizes
1510
self.get_pack_by_name(name)
1512
def _start_write_group(self):
1513
# Do not permit preparation for writing if we're not in a 'write lock'.
1514
if not self.repo.is_write_locked():
1515
raise errors.NotWriteLocked(self)
1516
self._new_pack = NewPack(self._upload_transport, self._index_transport,
1517
self._pack_transport, upload_suffix='.pack',
1518
file_mode=self.repo.control_files._file_mode)
1519
# allow writing: queue writes to a new index
1520
self.revision_index.add_writable_index(self._new_pack.revision_index,
1522
self.inventory_index.add_writable_index(self._new_pack.inventory_index,
1524
self.text_index.add_writable_index(self._new_pack.text_index,
1526
self.signature_index.add_writable_index(self._new_pack.signature_index,
1529
# reused revision and signature knits may need updating
1531
# "Hysterical raisins. client code in bzrlib grabs those knits outside
1532
# of write groups and then mutates it inside the write group."
1533
if self.repo._revision_knit is not None:
1534
self.repo._revision_knit._index._add_callback = \
1535
self.revision_index.add_callback
1536
if self.repo._signature_knit is not None:
1537
self.repo._signature_knit._index._add_callback = \
1538
self.signature_index.add_callback
1539
# create a reused knit object for text addition in commit.
1540
self.repo._text_knit = self.repo.weave_store.get_weave_or_empty(
1543
def _abort_write_group(self):
1544
# FIXME: just drop the transient index.
1545
# forget what names there are
1546
self._new_pack.abort()
1547
self._remove_pack_indices(self._new_pack)
1548
self._new_pack = None
1549
self.repo._text_knit = None
1551
def _commit_write_group(self):
1552
self._remove_pack_indices(self._new_pack)
1553
if self._new_pack.data_inserted():
1554
# get all the data to disk and read to use
1555
self._new_pack.finish()
1556
self.allocate(self._new_pack)
1557
self._new_pack = None
1558
if not self.autopack():
1559
# when autopack takes no steps, the names list is still
1561
self._save_pack_names()
1563
self._new_pack.abort()
1564
self._new_pack = None
1565
self.repo._text_knit = None
1568
class KnitPackRevisionStore(KnitRevisionStore):
1569
"""An object to adapt access from RevisionStore's to use KnitPacks.
1571
This class works by replacing the original RevisionStore.
1572
We need to do this because the KnitPackRevisionStore is less
1573
isolated in its layering - it uses services from the repo.
1576
def __init__(self, repo, transport, revisionstore):
1577
"""Create a KnitPackRevisionStore on repo with revisionstore.
1579
This will store its state in the Repository, use the
1580
indices to provide a KnitGraphIndex,
1581
and at the end of transactions write new indices.
1583
KnitRevisionStore.__init__(self, revisionstore.versioned_file_store)
1585
self._serializer = revisionstore._serializer
1586
self.transport = transport
1588
def get_revision_file(self, transaction):
1589
"""Get the revision versioned file object."""
1590
if getattr(self.repo, '_revision_knit', None) is not None:
1591
return self.repo._revision_knit
1592
self.repo._pack_collection.ensure_loaded()
1593
add_callback = self.repo._pack_collection.revision_index.add_callback
1594
# setup knit specific objects
1595
knit_index = KnitGraphIndex(
1596
self.repo._pack_collection.revision_index.combined_index,
1597
add_callback=add_callback)
1598
self.repo._revision_knit = knit.KnitVersionedFile(
1599
'revisions', self.transport.clone('..'),
1600
self.repo.control_files._file_mode,
1601
create=False, access_mode=self.repo._access_mode(),
1602
index=knit_index, delta=False, factory=knit.KnitPlainFactory(),
1603
access_method=self.repo._pack_collection.revision_index.knit_access)
1604
return self.repo._revision_knit
1606
def get_signature_file(self, transaction):
1607
"""Get the signature versioned file object."""
1608
if getattr(self.repo, '_signature_knit', None) is not None:
1609
return self.repo._signature_knit
1610
self.repo._pack_collection.ensure_loaded()
1611
add_callback = self.repo._pack_collection.signature_index.add_callback
1612
# setup knit specific objects
1613
knit_index = KnitGraphIndex(
1614
self.repo._pack_collection.signature_index.combined_index,
1615
add_callback=add_callback, parents=False)
1616
self.repo._signature_knit = knit.KnitVersionedFile(
1617
'signatures', self.transport.clone('..'),
1618
self.repo.control_files._file_mode,
1619
create=False, access_mode=self.repo._access_mode(),
1620
index=knit_index, delta=False, factory=knit.KnitPlainFactory(),
1621
access_method=self.repo._pack_collection.signature_index.knit_access)
1622
return self.repo._signature_knit
1625
class KnitPackTextStore(VersionedFileStore):
1626
"""Presents a TextStore abstraction on top of packs.
1628
This class works by replacing the original VersionedFileStore.
1629
We need to do this because the KnitPackRevisionStore is less
1630
isolated in its layering - it uses services from the repo and shares them
1631
with all the data written in a single write group.
1634
def __init__(self, repo, transport, weavestore):
1635
"""Create a KnitPackTextStore on repo with weavestore.
1637
This will store its state in the Repository, use the
1638
indices FileNames to provide a KnitGraphIndex,
1639
and at the end of transactions write new indices.
1641
# don't call base class constructor - it's not suitable.
1642
# no transient data stored in the transaction
1644
self._precious = False
1646
self.transport = transport
1647
self.weavestore = weavestore
1648
# XXX for check() which isn't updated yet
1649
self._transport = weavestore._transport
1651
def get_weave_or_empty(self, file_id, transaction):
1652
"""Get a 'Knit' backed by the .tix indices.
1654
The transaction parameter is ignored.
1656
self.repo._pack_collection.ensure_loaded()
1657
add_callback = self.repo._pack_collection.text_index.add_callback
1658
# setup knit specific objects
1659
file_id_index = GraphIndexPrefixAdapter(
1660
self.repo._pack_collection.text_index.combined_index,
1661
(file_id, ), 1, add_nodes_callback=add_callback)
1662
knit_index = KnitGraphIndex(file_id_index,
1663
add_callback=file_id_index.add_nodes,
1664
deltas=True, parents=True)
1665
return knit.KnitVersionedFile('text:' + file_id,
1666
self.transport.clone('..'),
1669
access_method=self.repo._pack_collection.text_index.knit_access,
1670
factory=knit.KnitPlainFactory())
1672
get_weave = get_weave_or_empty
1675
"""Generate a list of the fileids inserted, for use by check."""
1676
self.repo._pack_collection.ensure_loaded()
1678
for index, key, value, refs in \
1679
self.repo._pack_collection.text_index.combined_index.iter_all_entries():
1684
class InventoryKnitThunk(object):
1685
"""An object to manage thunking get_inventory_weave to pack based knits."""
1687
def __init__(self, repo, transport):
1688
"""Create an InventoryKnitThunk for repo at transport.
1690
This will store its state in the Repository, use the
1691
indices FileNames to provide a KnitGraphIndex,
1692
and at the end of transactions write a new index..
1695
self.transport = transport
1697
def get_weave(self):
1698
"""Get a 'Knit' that contains inventory data."""
1699
self.repo._pack_collection.ensure_loaded()
1700
add_callback = self.repo._pack_collection.inventory_index.add_callback
1701
# setup knit specific objects
1702
knit_index = KnitGraphIndex(
1703
self.repo._pack_collection.inventory_index.combined_index,
1704
add_callback=add_callback, deltas=True, parents=True)
1705
return knit.KnitVersionedFile(
1706
'inventory', self.transport.clone('..'),
1707
self.repo.control_files._file_mode,
1708
create=False, access_mode=self.repo._access_mode(),
1709
index=knit_index, delta=True, factory=knit.KnitPlainFactory(),
1710
access_method=self.repo._pack_collection.inventory_index.knit_access)
1713
class KnitPackRepository(KnitRepository):
1714
"""Experimental graph-knit using repository."""
1716
def __init__(self, _format, a_bzrdir, control_files, _revision_store,
1717
control_store, text_store, _commit_builder_class, _serializer):
1718
KnitRepository.__init__(self, _format, a_bzrdir, control_files,
1719
_revision_store, control_store, text_store, _commit_builder_class,
1721
index_transport = control_files._transport.clone('indices')
1722
self._pack_collection = RepositoryPackCollection(self, control_files._transport,
1724
control_files._transport.clone('upload'),
1725
control_files._transport.clone('packs'))
1726
self._revision_store = KnitPackRevisionStore(self, index_transport, self._revision_store)
1727
self.weave_store = KnitPackTextStore(self, index_transport, self.weave_store)
1728
self._inv_thunk = InventoryKnitThunk(self, index_transport)
1729
# True when the repository object is 'write locked' (as opposed to the
1730
# physical lock only taken out around changes to the pack-names list.)
1731
# Another way to represent this would be a decorator around the control
1732
# files object that presents logical locks as physical ones - if this
1733
# gets ugly consider that alternative design. RBC 20071011
1734
self._write_lock_count = 0
1735
self._transaction = None
1737
self._reconcile_does_inventory_gc = True
1738
self._reconcile_fixes_text_parents = True
1739
self._reconcile_backsup_inventory = False
1741
def _abort_write_group(self):
1742
self._pack_collection._abort_write_group()
1744
def _access_mode(self):
1745
"""Return 'w' or 'r' for depending on whether a write lock is active.
1747
This method is a helper for the Knit-thunking support objects.
1749
if self.is_write_locked():
1753
def _find_inconsistent_revision_parents(self):
1754
"""Find revisions with incorrectly cached parents.
1756
:returns: an iterator yielding tuples of (revison-id, parents-in-index,
1757
parents-in-revision).
1759
assert self.is_locked()
1760
pb = ui.ui_factory.nested_progress_bar()
1763
revision_nodes = self._pack_collection.revision_index \
1764
.combined_index.iter_all_entries()
1765
index_positions = []
1766
# Get the cached index values for all revisions, and also the location
1767
# in each index of the revision text so we can perform linear IO.
1768
for index, key, value, refs in revision_nodes:
1769
pos, length = value[1:].split(' ')
1770
index_positions.append((index, int(pos), key[0],
1771
tuple(parent[0] for parent in refs[0])))
1772
pb.update("Reading revision index.", 0, 0)
1773
index_positions.sort()
1774
batch_count = len(index_positions) / 1000 + 1
1775
pb.update("Checking cached revision graph.", 0, batch_count)
1776
for offset in xrange(batch_count):
1777
pb.update("Checking cached revision graph.", offset)
1778
to_query = index_positions[offset * 1000:(offset + 1) * 1000]
1781
rev_ids = [item[2] for item in to_query]
1782
revs = self.get_revisions(rev_ids)
1783
for revision, item in zip(revs, to_query):
1784
index_parents = item[3]
1785
rev_parents = tuple(revision.parent_ids)
1786
if index_parents != rev_parents:
1787
result.append((revision.revision_id, index_parents, rev_parents))
1792
def get_parents(self, revision_ids):
1793
"""See StackedParentsProvider.get_parents.
1795
This implementation accesses the combined revision index to provide
1798
self._pack_collection.ensure_loaded()
1799
index = self._pack_collection.revision_index.combined_index
1801
for revision_id in revision_ids:
1802
if revision_id != _mod_revision.NULL_REVISION:
1803
search_keys.add((revision_id,))
1804
found_parents = {_mod_revision.NULL_REVISION:[]}
1805
for index, key, value, refs in index.iter_entries(search_keys):
1808
parents = (_mod_revision.NULL_REVISION,)
1810
parents = tuple(parent[0] for parent in parents)
1811
found_parents[key[0]] = parents
1813
for revision_id in revision_ids:
1815
result.append(found_parents[revision_id])
1820
def _make_parents_provider(self):
1823
def _refresh_data(self):
1824
if self._write_lock_count == 1 or (
1825
self.control_files._lock_count == 1 and
1826
self.control_files._lock_mode == 'r'):
1827
# forget what names there are
1828
self._pack_collection.reset()
1829
# XXX: Better to do an in-memory merge when acquiring a new lock -
1830
# factor out code from _save_pack_names.
1831
self._pack_collection.ensure_loaded()
1833
def _start_write_group(self):
1834
self._pack_collection._start_write_group()
1836
def _commit_write_group(self):
1837
return self._pack_collection._commit_write_group()
1839
def get_inventory_weave(self):
1840
return self._inv_thunk.get_weave()
1842
def get_transaction(self):
1843
if self._write_lock_count:
1844
return self._transaction
1846
return self.control_files.get_transaction()
1848
def is_locked(self):
1849
return self._write_lock_count or self.control_files.is_locked()
1851
def is_write_locked(self):
1852
return self._write_lock_count
1854
def lock_write(self, token=None):
1855
if not self._write_lock_count and self.is_locked():
1856
raise errors.ReadOnlyError(self)
1857
self._write_lock_count += 1
1858
if self._write_lock_count == 1:
1859
from bzrlib import transactions
1860
self._transaction = transactions.WriteTransaction()
1861
self._refresh_data()
1863
def lock_read(self):
1864
if self._write_lock_count:
1865
self._write_lock_count += 1
1867
self.control_files.lock_read()
1868
self._refresh_data()
1870
def leave_lock_in_place(self):
1871
# not supported - raise an error
1872
raise NotImplementedError(self.leave_lock_in_place)
1874
def dont_leave_lock_in_place(self):
1875
# not supported - raise an error
1876
raise NotImplementedError(self.dont_leave_lock_in_place)
1880
"""Compress the data within the repository.
1882
This will pack all the data to a single pack. In future it may
1883
recompress deltas or do other such expensive operations.
1885
self._pack_collection.pack()
1888
def reconcile(self, other=None, thorough=False):
1889
"""Reconcile this repository."""
1890
from bzrlib.reconcile import PackReconciler
1891
reconciler = PackReconciler(self, thorough=thorough)
1892
reconciler.reconcile()
1896
if self._write_lock_count == 1 and self._write_group is not None:
1897
self.abort_write_group()
1898
self._transaction = None
1899
self._write_lock_count = 0
1900
raise errors.BzrError(
1901
'Must end write group before releasing write lock on %s'
1903
if self._write_lock_count:
1904
self._write_lock_count -= 1
1905
if not self._write_lock_count:
1906
transaction = self._transaction
1907
self._transaction = None
1908
transaction.finish()
1910
self.control_files.unlock()
1913
class RepositoryFormatPack(MetaDirRepositoryFormat):
1914
"""Format logic for pack structured repositories.
1916
This repository format has:
1917
- a list of packs in pack-names
1918
- packs in packs/NAME.pack
1919
- indices in indices/NAME.{iix,six,tix,rix}
1920
- knit deltas in the packs, knit indices mapped to the indices.
1921
- thunk objects to support the knits programming API.
1922
- a format marker of its own
1923
- an optional 'shared-storage' flag
1924
- an optional 'no-working-trees' flag
1928
# Set this attribute in derived classes to control the repository class
1929
# created by open and initialize.
1930
repository_class = None
1931
# Set this attribute in derived classes to control the
1932
# _commit_builder_class that the repository objects will have passed to
1933
# their constructor.
1934
_commit_builder_class = None
1935
# Set this attribute in derived clases to control the _serializer that the
1936
# repository objects will have passed to their constructor.
1939
def _get_control_store(self, repo_transport, control_files):
1940
"""Return the control store for this repository."""
1941
return VersionedFileStore(
1944
file_mode=control_files._file_mode,
1945
versionedfile_class=knit.KnitVersionedFile,
1946
versionedfile_kwargs={'factory': knit.KnitPlainFactory()},
1949
def _get_revision_store(self, repo_transport, control_files):
1950
"""See RepositoryFormat._get_revision_store()."""
1951
versioned_file_store = VersionedFileStore(
1953
file_mode=control_files._file_mode,
1956
versionedfile_class=knit.KnitVersionedFile,
1957
versionedfile_kwargs={'delta': False,
1958
'factory': knit.KnitPlainFactory(),
1962
return KnitRevisionStore(versioned_file_store)
1964
def _get_text_store(self, transport, control_files):
1965
"""See RepositoryFormat._get_text_store()."""
1966
return self._get_versioned_file_store('knits',
1969
versionedfile_class=knit.KnitVersionedFile,
1970
versionedfile_kwargs={
1971
'create_parent_dir': True,
1972
'delay_create': True,
1973
'dir_mode': control_files._dir_mode,
1977
def initialize(self, a_bzrdir, shared=False):
1978
"""Create a pack based repository.
1980
:param a_bzrdir: bzrdir to contain the new repository; must already
1982
:param shared: If true the repository will be initialized as a shared
1985
mutter('creating repository in %s.', a_bzrdir.transport.base)
1986
dirs = ['indices', 'obsolete_packs', 'packs', 'upload']
1987
builder = GraphIndexBuilder()
1988
files = [('pack-names', builder.finish())]
1989
utf8_files = [('format', self.get_format_string())]
1991
self._upload_blank_content(a_bzrdir, dirs, files, utf8_files, shared)
1992
return self.open(a_bzrdir=a_bzrdir, _found=True)
1994
def open(self, a_bzrdir, _found=False, _override_transport=None):
1995
"""See RepositoryFormat.open().
1997
:param _override_transport: INTERNAL USE ONLY. Allows opening the
1998
repository at a slightly different url
1999
than normal. I.e. during 'upgrade'.
2002
format = RepositoryFormat.find_format(a_bzrdir)
2003
assert format.__class__ == self.__class__
2004
if _override_transport is not None:
2005
repo_transport = _override_transport
2007
repo_transport = a_bzrdir.get_repository_transport(None)
2008
control_files = lockable_files.LockableFiles(repo_transport,
2009
'lock', lockdir.LockDir)
2010
text_store = self._get_text_store(repo_transport, control_files)
2011
control_store = self._get_control_store(repo_transport, control_files)
2012
_revision_store = self._get_revision_store(repo_transport, control_files)
2013
return self.repository_class(_format=self,
2015
control_files=control_files,
2016
_revision_store=_revision_store,
2017
control_store=control_store,
2018
text_store=text_store,
2019
_commit_builder_class=self._commit_builder_class,
2020
_serializer=self._serializer)
2023
class RepositoryFormatKnitPack1(RepositoryFormatPack):
2024
"""A no-subtrees parameterised Pack repository.
2026
This format was introduced in 0.92.
2029
repository_class = KnitPackRepository
2030
_commit_builder_class = PackCommitBuilder
2031
_serializer = xml5.serializer_v5
2033
def _get_matching_bzrdir(self):
2034
return bzrdir.format_registry.make_bzrdir('pack-0.92')
2036
def _ignore_setting_bzrdir(self, format):
2039
_matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
2041
def get_format_string(self):
2042
"""See RepositoryFormat.get_format_string()."""
2043
return "Bazaar pack repository format 1 (needs bzr 0.92)\n"
2045
def get_format_description(self):
2046
"""See RepositoryFormat.get_format_description()."""
2047
return "Packs containing knits without subtree support"
2049
def check_conversion_target(self, target_format):
2053
class RepositoryFormatKnitPack3(RepositoryFormatPack):
2054
"""A subtrees parameterised Pack repository.
2056
This repository format uses the xml7 serializer to get:
2057
- support for recording full info about the tree root
2058
- support for recording tree-references
2060
This format was introduced in 0.92.
2063
repository_class = KnitPackRepository
2064
_commit_builder_class = PackRootCommitBuilder
2065
rich_root_data = True
2066
supports_tree_reference = True
2067
_serializer = xml7.serializer_v7
2069
def _get_matching_bzrdir(self):
2070
return bzrdir.format_registry.make_bzrdir(
2071
'pack-0.92-subtree')
2073
def _ignore_setting_bzrdir(self, format):
2076
_matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
2078
def check_conversion_target(self, target_format):
2079
if not target_format.rich_root_data:
2080
raise errors.BadConversionTarget(
2081
'Does not support rich root data.', target_format)
2082
if not getattr(target_format, 'supports_tree_reference', False):
2083
raise errors.BadConversionTarget(
2084
'Does not support nested trees', target_format)
2086
def get_format_string(self):
2087
"""See RepositoryFormat.get_format_string()."""
2088
return "Bazaar pack repository format 1 with subtree support (needs bzr 0.92)\n"
2090
def get_format_description(self):
2091
"""See RepositoryFormat.get_format_description()."""
2092
return "Packs containing knits with subtree support\n"
2095
class RepositoryFormatKnitPack4(RepositoryFormatPack):
2096
"""A rich-root, no subtrees parameterised Pack repository.
2098
This repository format uses the xml6 serializer to get:
2099
- support for recording full info about the tree root
2101
This format was introduced in 1.0.
2104
repository_class = KnitPackRepository
2105
_commit_builder_class = PackRootCommitBuilder
2106
rich_root_data = True
2107
supports_tree_reference = False
2108
_serializer = xml6.serializer_v6
2110
def _get_matching_bzrdir(self):
2111
return bzrdir.format_registry.make_bzrdir(
2114
def _ignore_setting_bzrdir(self, format):
2117
_matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
2119
def check_conversion_target(self, target_format):
2120
if not target_format.rich_root_data:
2121
raise errors.BadConversionTarget(
2122
'Does not support rich root data.', target_format)
2124
def get_format_string(self):
2125
"""See RepositoryFormat.get_format_string()."""
2126
return ("Bazaar pack repository format 1 with rich root"
2127
" (needs bzr 1.0)\n")
2129
def get_format_description(self):
2130
"""See RepositoryFormat.get_format_description()."""
2131
return "Packs containing knits with rich root support\n"