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.index import (
34
GraphIndexPrefixAdapter,
36
from bzrlib.knit import KnitGraphIndex, _PackAccess, _KnitData
37
from bzrlib.osutils import rand_chars
38
from bzrlib.pack import ContainerWriter
39
from bzrlib.store import revision
55
from bzrlib.decorators import needs_read_lock, needs_write_lock
56
from bzrlib.repofmt.knitrepo import KnitRepository
57
from bzrlib.repository import (
60
MetaDirRepositoryFormat,
63
import bzrlib.revision as _mod_revision
64
from bzrlib.store.revision.knit import KnitRevisionStore
65
from bzrlib.store.versioned import VersionedFileStore
66
from bzrlib.trace import mutter, note, warning
69
class PackCommitBuilder(CommitBuilder):
70
"""A subclass of CommitBuilder to add texts with pack semantics.
72
Specifically this uses one knit object rather than one knit object per
73
added text, reducing memory and object pressure.
76
def _add_text_to_weave(self, file_id, new_lines, parents, nostore_sha):
77
return self.repository._pack_collection._add_text_to_weave(file_id,
78
self._new_revision_id, new_lines, parents, nostore_sha,
82
class PackRootCommitBuilder(RootCommitBuilder):
83
"""A subclass of RootCommitBuilder to add texts with pack semantics.
85
Specifically this uses one knit object rather than one knit object per
86
added text, reducing memory and object pressure.
89
def _add_text_to_weave(self, file_id, new_lines, parents, nostore_sha):
90
return self.repository._pack_collection._add_text_to_weave(file_id,
91
self._new_revision_id, new_lines, parents, nostore_sha,
96
"""An in memory proxy for a pack and its indices.
98
This is a base class that is not directly used, instead the classes
99
ExistingPack and NewPack are used.
102
def __init__(self, revision_index, inventory_index, text_index,
104
"""Create a pack instance.
106
:param revision_index: A GraphIndex for determining what revisions are
107
present in the Pack and accessing the locations of their texts.
108
:param inventory_index: A GraphIndex for determining what inventories are
109
present in the Pack and accessing the locations of their
111
:param text_index: A GraphIndex for determining what file texts
112
are present in the pack and accessing the locations of their
113
texts/deltas (via (fileid, revisionid) tuples).
114
:param revision_index: A GraphIndex for determining what signatures are
115
present in the Pack and accessing the locations of their texts.
117
self.revision_index = revision_index
118
self.inventory_index = inventory_index
119
self.text_index = text_index
120
self.signature_index = signature_index
122
def access_tuple(self):
123
"""Return a tuple (transport, name) for the pack content."""
124
return self.pack_transport, self.file_name()
127
"""Get the file name for the pack on disk."""
128
return self.name + '.pack'
130
def get_revision_count(self):
131
return self.revision_index.key_count()
133
def inventory_index_name(self, name):
134
"""The inv index is the name + .iix."""
135
return self.index_name('inventory', name)
137
def revision_index_name(self, name):
138
"""The revision index is the name + .rix."""
139
return self.index_name('revision', name)
141
def signature_index_name(self, name):
142
"""The signature index is the name + .six."""
143
return self.index_name('signature', name)
145
def text_index_name(self, name):
146
"""The text index is the name + .tix."""
147
return self.index_name('text', name)
150
class ExistingPack(Pack):
151
"""An in memory proxy for an existing .pack and its disk indices."""
153
def __init__(self, pack_transport, name, revision_index, inventory_index,
154
text_index, signature_index):
155
"""Create an ExistingPack object.
157
:param pack_transport: The transport where the pack file resides.
158
:param name: The name of the pack on disk in the pack_transport.
160
Pack.__init__(self, revision_index, inventory_index, text_index,
163
self.pack_transport = pack_transport
164
assert None not in (revision_index, inventory_index, text_index,
165
signature_index, name, pack_transport)
167
def __eq__(self, other):
168
return self.__dict__ == other.__dict__
170
def __ne__(self, other):
171
return not self.__eq__(other)
174
return "<bzrlib.repofmt.pack_repo.Pack object at 0x%x, %s, %s" % (
175
id(self), self.transport, self.name)
179
"""An in memory proxy for a pack which is being created."""
181
# A map of index 'type' to the file extension and position in the
183
index_definitions = {
184
'revision': ('.rix', 0),
185
'inventory': ('.iix', 1),
187
'signature': ('.six', 3),
190
def __init__(self, upload_transport, index_transport, pack_transport,
191
upload_suffix='', file_mode=None):
192
"""Create a NewPack instance.
194
:param upload_transport: A writable transport for the pack to be
195
incrementally uploaded to.
196
:param index_transport: A writable transport for the pack's indices to
197
be written to when the pack is finished.
198
:param pack_transport: A writable transport for the pack to be renamed
199
to when the upload is complete. This *must* be the same as
200
upload_transport.clone('../packs').
201
:param upload_suffix: An optional suffix to be given to any temporary
202
files created during the pack creation. e.g '.autopack'
203
:param file_mode: An optional file mode to create the new files with.
205
# The relative locations of the packs are constrained, but all are
206
# passed in because the caller has them, so as to avoid object churn.
208
# Revisions: parents list, no text compression.
209
InMemoryGraphIndex(reference_lists=1),
210
# Inventory: We want to map compression only, but currently the
211
# knit code hasn't been updated enough to understand that, so we
212
# have a regular 2-list index giving parents and compression
214
InMemoryGraphIndex(reference_lists=2),
215
# Texts: compression and per file graph, for all fileids - so two
216
# reference lists and two elements in the key tuple.
217
InMemoryGraphIndex(reference_lists=2, key_elements=2),
218
# Signatures: Just blobs to store, no compression, no parents
220
InMemoryGraphIndex(reference_lists=0),
222
# where should the new pack be opened
223
self.upload_transport = upload_transport
224
# where are indices written out to
225
self.index_transport = index_transport
226
# where is the pack renamed to when it is finished?
227
self.pack_transport = pack_transport
228
# What file mode to upload the pack and indices with.
229
self._file_mode = file_mode
230
# tracks the content written to the .pack file.
231
self._hash = md5.new()
232
# a four-tuple with the length in bytes of the indices, once the pack
233
# is finalised. (rev, inv, text, sigs)
234
self.index_sizes = None
235
# How much data to cache when writing packs. Note that this is not
236
# synchronised with reads, because it's not in the transport layer, so
237
# is not safe unless the client knows it won't be reading from the pack
239
self._cache_limit = 0
240
# the temporary pack file name.
241
self.random_name = rand_chars(20) + upload_suffix
242
# when was this pack started ?
243
self.start_time = time.time()
244
# open an output stream for the data added to the pack.
245
self.write_stream = self.upload_transport.open_write_stream(
246
self.random_name, mode=self._file_mode)
247
if 'pack' in debug.debug_flags:
248
mutter('%s: create_pack: pack stream open: %s%s t+%6.3fs',
249
time.ctime(), self.upload_transport.base, self.random_name,
250
time.time() - self.start_time)
251
# A list of byte sequences to be written to the new pack, and the
252
# aggregate size of them. Stored as a list rather than separate
253
# variables so that the _write_data closure below can update them.
254
self._buffer = [[], 0]
255
# create a callable for adding data
257
# robertc says- this is a closure rather than a method on the object
258
# so that the variables are locals, and faster than accessing object
260
def _write_data(bytes, flush=False, _buffer=self._buffer,
261
_write=self.write_stream.write, _update=self._hash.update):
262
_buffer[0].append(bytes)
263
_buffer[1] += len(bytes)
265
if _buffer[1] > self._cache_limit or flush:
266
bytes = ''.join(_buffer[0])
270
# expose this on self, for the occasion when clients want to add data.
271
self._write_data = _write_data
272
# a pack writer object to serialise pack records.
273
self._writer = pack.ContainerWriter(self._write_data)
275
# what state is the pack in? (open, finished, aborted)
279
"""Cancel creating this pack."""
280
self._state = 'aborted'
281
self.write_stream.close()
282
# Remove the temporary pack file.
283
self.upload_transport.delete(self.random_name)
284
# The indices have no state on disk.
286
def access_tuple(self):
287
"""Return a tuple (transport, name) for the pack content."""
288
assert self._state in ('open', 'finished')
289
if self._state == 'finished':
290
return Pack.access_tuple(self)
292
return self.upload_transport, self.random_name
294
def data_inserted(self):
295
"""True if data has been added to this pack."""
296
return bool(self.get_revision_count() or
297
self.inventory_index.key_count() or
298
self.text_index.key_count() or
299
self.signature_index.key_count())
302
"""Finish the new pack.
305
- finalises the content
306
- assigns a name (the md5 of the content, currently)
307
- writes out the associated indices
308
- renames the pack into place.
309
- stores the index size tuple for the pack in the index_sizes
314
self._write_data('', flush=True)
315
self.name = self._hash.hexdigest()
317
# XXX: It'd be better to write them all to temporary names, then
318
# rename them all into place, so that the window when only some are
319
# visible is smaller. On the other hand none will be seen until
320
# they're in the names list.
321
self.index_sizes = [None, None, None, None]
322
self._write_index('revision', self.revision_index, 'revision')
323
self._write_index('inventory', self.inventory_index, 'inventory')
324
self._write_index('text', self.text_index, 'file texts')
325
self._write_index('signature', self.signature_index,
326
'revision signatures')
327
self.write_stream.close()
328
# Note that this will clobber an existing pack with the same name,
329
# without checking for hash collisions. While this is undesirable this
330
# is something that can be rectified in a subsequent release. One way
331
# to rectify it may be to leave the pack at the original name, writing
332
# its pack-names entry as something like 'HASH: index-sizes
333
# temporary-name'. Allocate that and check for collisions, if it is
334
# collision free then rename it into place. If clients know this scheme
335
# they can handle missing-file errors by:
336
# - try for HASH.pack
337
# - try for temporary-name
338
# - refresh the pack-list to see if the pack is now absent
339
self.upload_transport.rename(self.random_name,
340
'../packs/' + self.name + '.pack')
341
self._state = 'finished'
342
if 'pack' in debug.debug_flags:
343
# XXX: size might be interesting?
344
mutter('%s: create_pack: pack renamed into place: %s%s->%s%s t+%6.3fs',
345
time.ctime(), self.upload_transport.base, self.random_name,
346
self.pack_transport, self.name,
347
time.time() - self.start_time)
349
def index_name(self, index_type, name):
350
"""Get the disk name of an index type for pack name 'name'."""
351
return name + NewPack.index_definitions[index_type][0]
353
def index_offset(self, index_type):
354
"""Get the position in a index_size array for a given index type."""
355
return NewPack.index_definitions[index_type][1]
357
def _replace_index_with_readonly(self, index_type):
358
setattr(self, index_type + '_index',
359
GraphIndex(self.index_transport,
360
self.index_name(index_type, self.name),
361
self.index_sizes[self.index_offset(index_type)]))
363
def set_write_cache_size(self, size):
364
self._cache_limit = size
366
def _write_index(self, index_type, index, label):
367
"""Write out an index.
369
:param index_type: The type of index to write - e.g. 'revision'.
370
:param index: The index object to serialise.
371
:param label: What label to give the index e.g. 'revision'.
373
index_name = self.index_name(index_type, self.name)
374
self.index_sizes[self.index_offset(index_type)] = \
375
self.index_transport.put_file(index_name, index.finish(),
376
mode=self._file_mode)
377
if 'pack' in debug.debug_flags:
378
# XXX: size might be interesting?
379
mutter('%s: create_pack: wrote %s index: %s%s t+%6.3fs',
380
time.ctime(), label, self.upload_transport.base,
381
self.random_name, time.time() - self.start_time)
382
# Replace the writable index on this object with a readonly,
383
# presently unloaded index. We should alter
384
# the index layer to make its finish() error if add_node is
385
# subsequently used. RBC
386
self._replace_index_with_readonly(index_type)
389
class AggregateIndex(object):
390
"""An aggregated index for the RepositoryPackCollection.
392
AggregateIndex is reponsible for managing the PackAccess object,
393
Index-To-Pack mapping, and all indices list for a specific type of index
394
such as 'revision index'.
396
A CombinedIndex provides an index on a single key space built up
397
from several on-disk indices. The AggregateIndex builds on this
398
to provide a knit access layer, and allows having up to one writable
399
index within the collection.
401
# XXX: Probably 'can be written to' could/should be separated from 'acts
402
# like a knit index' -- mbp 20071024
405
"""Create an AggregateIndex."""
406
self.index_to_pack = {}
407
self.combined_index = CombinedGraphIndex([])
408
self.knit_access = _PackAccess(self.index_to_pack)
410
def replace_indices(self, index_to_pack, indices):
411
"""Replace the current mappings with fresh ones.
413
This should probably not be used eventually, rather incremental add and
414
removal of indices. It has been added during refactoring of existing
417
:param index_to_pack: A mapping from index objects to
418
(transport, name) tuples for the pack file data.
419
:param indices: A list of indices.
421
# refresh the revision pack map dict without replacing the instance.
422
self.index_to_pack.clear()
423
self.index_to_pack.update(index_to_pack)
424
# XXX: API break - clearly a 'replace' method would be good?
425
self.combined_index._indices[:] = indices
426
# the current add nodes callback for the current writable index if
428
self.add_callback = None
430
def add_index(self, index, pack):
431
"""Add index to the aggregate, which is an index for Pack pack.
433
Future searches on the aggregate index will seach this new index
434
before all previously inserted indices.
436
:param index: An Index for the pack.
437
:param pack: A Pack instance.
439
# expose it to the index map
440
self.index_to_pack[index] = pack.access_tuple()
441
# put it at the front of the linear index list
442
self.combined_index.insert_index(0, index)
444
def add_writable_index(self, index, pack):
445
"""Add an index which is able to have data added to it.
447
There can be at most one writable index at any time. Any
448
modifications made to the knit are put into this index.
450
:param index: An index from the pack parameter.
451
:param pack: A Pack instance.
453
assert self.add_callback is None, \
454
"%s already has a writable index through %s" % \
455
(self, self.add_callback)
456
# allow writing: queue writes to a new index
457
self.add_index(index, pack)
458
# Updates the index to packs mapping as a side effect,
459
self.knit_access.set_writer(pack._writer, index, pack.access_tuple())
460
self.add_callback = index.add_nodes
463
"""Reset all the aggregate data to nothing."""
464
self.knit_access.set_writer(None, None, (None, None))
465
self.index_to_pack.clear()
466
del self.combined_index._indices[:]
467
self.add_callback = None
469
def remove_index(self, index, pack):
470
"""Remove index from the indices used to answer queries.
472
:param index: An index from the pack parameter.
473
:param pack: A Pack instance.
475
del self.index_to_pack[index]
476
self.combined_index._indices.remove(index)
477
if (self.add_callback is not None and
478
getattr(index, 'add_nodes', None) == self.add_callback):
479
self.add_callback = None
480
self.knit_access.set_writer(None, None, (None, None))
483
class Packer(object):
484
"""Create a pack from packs."""
486
def __init__(self, pack_collection, packs, suffix, revision_ids=None):
489
:param pack_collection: A RepositoryPackCollection object where the
490
new pack is being written to.
491
:param packs: The packs to combine.
492
:param suffix: The suffix to use on the temporary files for the pack.
493
:param revision_ids: Revision ids to limit the pack to.
497
self.revision_ids = revision_ids
498
self._pack_collection = pack_collection
500
def pack(self, pb=None):
501
"""Create a new pack by reading data from other packs.
503
This does little more than a bulk copy of data. One key difference
504
is that data with the same item key across multiple packs is elided
505
from the output. The new pack is written into the current pack store
506
along with its indices, and the name added to the pack names. The
507
source packs are not altered and are not required to be in the current
510
:param pb: An optional progress bar to use. A nested bar is created if
512
:return: A Pack object, or None if nothing was copied.
514
# open a pack - using the same name as the last temporary file
515
# - which has already been flushed, so its safe.
516
# XXX: - duplicate code warning with start_write_group; fix before
517
# considering 'done'.
518
if self._pack_collection._new_pack is not None:
519
raise errors.BzrError('call to create_pack_from_packs while '
520
'another pack is being written.')
521
if self.revision_ids is not None:
522
if len(self.revision_ids) == 0:
523
# silly fetch request.
526
self.revision_ids = frozenset(self.revision_ids)
528
self.pb = ui.ui_factory.nested_progress_bar()
532
return self._create_pack_from_packs()
538
"""Open a pack for the pack we are creating."""
539
return NewPack(self._pack_collection._upload_transport,
540
self._pack_collection._index_transport,
541
self._pack_collection._pack_transport, upload_suffix=self.suffix,
542
file_mode=self._pack_collection.repo.control_files._file_mode)
544
def _create_pack_from_packs(self):
545
self.pb.update("Opening pack", 0, 5)
546
new_pack = self.open_pack()
547
# buffer data - we won't be reading-back during the pack creation and
548
# this makes a significant difference on sftp pushes.
549
new_pack.set_write_cache_size(1024*1024)
550
if 'pack' in debug.debug_flags:
551
plain_pack_list = ['%s%s' % (a_pack.pack_transport.base, a_pack.name)
552
for a_pack in self.packs]
553
if self.revision_ids is not None:
554
rev_count = len(self.revision_ids)
557
mutter('%s: create_pack: creating pack from source packs: '
558
'%s%s %s revisions wanted %s t=0',
559
time.ctime(), self._pack_collection._upload_transport.base, new_pack.random_name,
560
plain_pack_list, rev_count)
562
if self.revision_ids:
563
revision_keys = [(revision_id,) for revision_id in self.revision_ids]
567
# select revision keys
568
revision_index_map = self._pack_collection._packs_list_to_pack_map_and_index_list(
569
self.packs, 'revision_index')[0]
570
revision_nodes = self._pack_collection._index_contents(revision_index_map, revision_keys)
571
# copy revision keys and adjust values
572
self.pb.update("Copying revision texts", 1)
573
list(self._copy_nodes_graph(revision_nodes, revision_index_map,
574
new_pack._writer, new_pack.revision_index))
575
if 'pack' in debug.debug_flags:
576
mutter('%s: create_pack: revisions copied: %s%s %d items t+%6.3fs',
577
time.ctime(), self._pack_collection._upload_transport.base, new_pack.random_name,
578
new_pack.revision_index.key_count(),
579
time.time() - new_pack.start_time)
580
# select inventory keys
581
inv_keys = revision_keys # currently the same keyspace, and note that
582
# querying for keys here could introduce a bug where an inventory item
583
# is missed, so do not change it to query separately without cross
584
# checking like the text key check below.
585
inventory_index_map = self._pack_collection._packs_list_to_pack_map_and_index_list(
586
self.packs, 'inventory_index')[0]
587
inv_nodes = self._pack_collection._index_contents(inventory_index_map, inv_keys)
588
# copy inventory keys and adjust values
589
# XXX: Should be a helper function to allow different inv representation
591
self.pb.update("Copying inventory texts", 2)
592
inv_lines = self._copy_nodes_graph(inv_nodes, inventory_index_map,
593
new_pack._writer, new_pack.inventory_index, output_lines=True)
594
if self.revision_ids:
595
fileid_revisions = self._pack_collection.repo._find_file_ids_from_xml_inventory_lines(
596
inv_lines, self.revision_ids)
598
for fileid, file_revids in fileid_revisions.iteritems():
600
[(fileid, file_revid) for file_revid in file_revids])
602
# eat the iterator to cause it to execute.
605
if 'pack' in debug.debug_flags:
606
mutter('%s: create_pack: inventories copied: %s%s %d items t+%6.3fs',
607
time.ctime(), self._pack_collection._upload_transport.base, new_pack.random_name,
608
new_pack.inventory_index.key_count(),
609
time.time() - new_pack.start_time)
611
text_index_map = self._pack_collection._packs_list_to_pack_map_and_index_list(
612
self.packs, 'text_index')[0]
613
text_nodes = self._pack_collection._index_contents(text_index_map, text_filter)
614
if text_filter is not None:
615
# We could return the keys copied as part of the return value from
616
# _copy_nodes_graph but this doesn't work all that well with the
617
# need to get line output too, so we check separately, and as we're
618
# going to buffer everything anyway, we check beforehand, which
619
# saves reading knit data over the wire when we know there are
621
text_nodes = set(text_nodes)
622
present_text_keys = set(_node[1] for _node in text_nodes)
623
missing_text_keys = set(text_filter) - present_text_keys
624
if missing_text_keys:
625
# TODO: raise a specific error that can handle many missing
627
a_missing_key = missing_text_keys.pop()
628
raise errors.RevisionNotPresent(a_missing_key[1],
630
# copy text keys and adjust values
631
self.pb.update("Copying content texts", 3)
632
list(self._copy_nodes_graph(text_nodes, text_index_map,
633
new_pack._writer, new_pack.text_index))
634
if 'pack' in debug.debug_flags:
635
mutter('%s: create_pack: file texts copied: %s%s %d items t+%6.3fs',
636
time.ctime(), self._pack_collection._upload_transport.base, new_pack.random_name,
637
new_pack.text_index.key_count(),
638
time.time() - new_pack.start_time)
639
# select signature keys
640
signature_filter = revision_keys # same keyspace
641
signature_index_map = self._pack_collection._packs_list_to_pack_map_and_index_list(
642
self.packs, 'signature_index')[0]
643
signature_nodes = self._pack_collection._index_contents(signature_index_map,
645
# copy signature keys and adjust values
646
self.pb.update("Copying signature texts", 4)
647
self._copy_nodes(signature_nodes, signature_index_map, new_pack._writer,
648
new_pack.signature_index)
649
if 'pack' in debug.debug_flags:
650
mutter('%s: create_pack: revision signatures copied: %s%s %d items t+%6.3fs',
651
time.ctime(), self._pack_collection._upload_transport.base, new_pack.random_name,
652
new_pack.signature_index.key_count(),
653
time.time() - new_pack.start_time)
654
if not new_pack.data_inserted():
657
self.pb.update("Finishing pack", 5)
659
self._pack_collection.allocate(new_pack)
662
def _copy_nodes(self, nodes, index_map, writer, write_index):
663
"""Copy knit nodes between packs with no graph references."""
664
pb = ui.ui_factory.nested_progress_bar()
666
return self._do_copy_nodes(nodes, index_map, writer,
671
def _do_copy_nodes(self, nodes, index_map, writer, write_index, pb):
672
# for record verification
673
knit_data = _KnitData(None)
674
# plan a readv on each source pack:
676
nodes = sorted(nodes)
677
# how to map this into knit.py - or knit.py into this?
678
# we don't want the typical knit logic, we want grouping by pack
679
# at this point - perhaps a helper library for the following code
680
# duplication points?
682
for index, key, value in nodes:
683
if index not in request_groups:
684
request_groups[index] = []
685
request_groups[index].append((key, value))
687
pb.update("Copied record", record_index, len(nodes))
688
for index, items in request_groups.iteritems():
689
pack_readv_requests = []
690
for key, value in items:
691
# ---- KnitGraphIndex.get_position
692
bits = value[1:].split(' ')
693
offset, length = int(bits[0]), int(bits[1])
694
pack_readv_requests.append((offset, length, (key, value[0])))
695
# linear scan up the pack
696
pack_readv_requests.sort()
698
transport, path = index_map[index]
699
reader = pack.make_readv_reader(transport, path,
700
[offset[0:2] for offset in pack_readv_requests])
701
for (names, read_func), (_1, _2, (key, eol_flag)) in \
702
izip(reader.iter_records(), pack_readv_requests):
703
raw_data = read_func(None)
704
# check the header only
705
df, _ = knit_data._parse_record_header(key[-1], raw_data)
707
pos, size = writer.add_bytes_record(raw_data, names)
708
write_index.add_node(key, eol_flag + "%d %d" % (pos, size))
709
pb.update("Copied record", record_index)
712
def _copy_nodes_graph(self, nodes, index_map, writer, write_index,
714
"""Copy knit nodes between packs.
716
:param output_lines: Return lines present in the copied data as
717
an iterator of line,version_id.
719
pb = ui.ui_factory.nested_progress_bar()
721
return self._do_copy_nodes_graph(nodes, index_map, writer,
722
write_index, output_lines, pb)
726
def _do_copy_nodes_graph(self, nodes, index_map, writer, write_index,
728
# for record verification
729
knit_data = _KnitData(None)
730
# for line extraction when requested (inventories only)
732
factory = knit.KnitPlainFactory()
733
# plan a readv on each source pack:
735
nodes = sorted(nodes)
736
# how to map this into knit.py - or knit.py into this?
737
# we don't want the typical knit logic, we want grouping by pack
738
# at this point - perhaps a helper library for the following code
739
# duplication points?
742
pb.update("Copied record", record_index, len(nodes))
743
for index, key, value, references in nodes:
744
if index not in request_groups:
745
request_groups[index] = []
746
request_groups[index].append((key, value, references))
747
for index, items in request_groups.iteritems():
748
pack_readv_requests = []
749
for key, value, references in items:
750
# ---- KnitGraphIndex.get_position
751
bits = value[1:].split(' ')
752
offset, length = int(bits[0]), int(bits[1])
753
pack_readv_requests.append((offset, length, (key, value[0], references)))
754
# linear scan up the pack
755
pack_readv_requests.sort()
757
transport, path = index_map[index]
758
reader = pack.make_readv_reader(transport, path,
759
[offset[0:2] for offset in pack_readv_requests])
760
for (names, read_func), (_1, _2, (key, eol_flag, references)) in \
761
izip(reader.iter_records(), pack_readv_requests):
762
raw_data = read_func(None)
765
# read the entire thing
766
content, _ = knit_data._parse_record(version_id, raw_data)
767
if len(references[-1]) == 0:
768
line_iterator = factory.get_fulltext_content(content)
770
line_iterator = factory.get_linedelta_content(content)
771
for line in line_iterator:
772
yield line, version_id
774
# check the header only
775
df, _ = knit_data._parse_record_header(version_id, raw_data)
777
pos, size = writer.add_bytes_record(raw_data, names)
778
write_index.add_node(key, eol_flag + "%d %d" % (pos, size), references)
779
pb.update("Copied record", record_index)
783
class ReconcilePacker(Packer):
784
"""A packer which regenerates indices etc as it copies.
786
This is used by ``bzr reconcile`` to cause parent text pointers to be
791
class RepositoryPackCollection(object):
792
"""Management of packs within a repository."""
794
def __init__(self, repo, transport, index_transport, upload_transport,
796
"""Create a new RepositoryPackCollection.
798
:param transport: Addresses the repository base directory
799
(typically .bzr/repository/).
800
:param index_transport: Addresses the directory containing indices.
801
:param upload_transport: Addresses the directory into which packs are written
802
while they're being created.
803
:param pack_transport: Addresses the directory of existing complete packs.
806
self.transport = transport
807
self._index_transport = index_transport
808
self._upload_transport = upload_transport
809
self._pack_transport = pack_transport
810
self._suffix_offsets = {'.rix': 0, '.iix': 1, '.tix': 2, '.six': 3}
813
self._packs_by_name = {}
814
# the previous pack-names content
815
self._packs_at_load = None
816
# when a pack is being created by this object, the state of that pack.
817
self._new_pack = None
818
# aggregated revision index data
819
self.revision_index = AggregateIndex()
820
self.inventory_index = AggregateIndex()
821
self.text_index = AggregateIndex()
822
self.signature_index = AggregateIndex()
824
def add_pack_to_memory(self, pack):
825
"""Make a Pack object available to the repository to satisfy queries.
827
:param pack: A Pack object.
829
assert pack.name not in self._packs_by_name
830
self.packs.append(pack)
831
self._packs_by_name[pack.name] = pack
832
self.revision_index.add_index(pack.revision_index, pack)
833
self.inventory_index.add_index(pack.inventory_index, pack)
834
self.text_index.add_index(pack.text_index, pack)
835
self.signature_index.add_index(pack.signature_index, pack)
837
def _add_text_to_weave(self, file_id, revision_id, new_lines, parents,
838
nostore_sha, random_revid):
839
file_id_index = GraphIndexPrefixAdapter(
840
self.text_index.combined_index,
842
add_nodes_callback=self.text_index.add_callback)
843
self.repo._text_knit._index._graph_index = file_id_index
844
self.repo._text_knit._index._add_callback = file_id_index.add_nodes
845
return self.repo._text_knit.add_lines_with_ghosts(
846
revision_id, parents, new_lines, nostore_sha=nostore_sha,
847
random_id=random_revid, check_content=False)[0:2]
850
"""Return a list of all the Pack objects this repository has.
852
Note that an in-progress pack being created is not returned.
854
:return: A list of Pack objects for all the packs in the repository.
857
for name in self.names():
858
result.append(self.get_pack_by_name(name))
862
"""Pack the pack collection incrementally.
864
This will not attempt global reorganisation or recompression,
865
rather it will just ensure that the total number of packs does
866
not grow without bound. It uses the _max_pack_count method to
867
determine if autopacking is needed, and the pack_distribution
868
method to determine the number of revisions in each pack.
870
If autopacking takes place then the packs name collection will have
871
been flushed to disk - packing requires updating the name collection
872
in synchronisation with certain steps. Otherwise the names collection
875
:return: True if packing took place.
877
# XXX: Should not be needed when the management of indices is sane.
878
total_revisions = self.revision_index.combined_index.key_count()
879
total_packs = len(self._names)
880
if self._max_pack_count(total_revisions) >= total_packs:
882
# XXX: the following may want to be a class, to pack with a given
884
mutter('Auto-packing repository %s, which has %d pack files, '
885
'containing %d revisions into %d packs.', self, total_packs,
886
total_revisions, self._max_pack_count(total_revisions))
887
# determine which packs need changing
888
pack_distribution = self.pack_distribution(total_revisions)
890
for pack in self.all_packs():
891
revision_count = pack.get_revision_count()
892
if revision_count == 0:
893
# revision less packs are not generated by normal operation,
894
# only by operations like sign-my-commits, and thus will not
895
# tend to grow rapdily or without bound like commit containing
896
# packs do - leave them alone as packing them really should
897
# group their data with the relevant commit, and that may
898
# involve rewriting ancient history - which autopack tries to
899
# avoid. Alternatively we could not group the data but treat
900
# each of these as having a single revision, and thus add
901
# one revision for each to the total revision count, to get
902
# a matching distribution.
904
existing_packs.append((revision_count, pack))
905
pack_operations = self.plan_autopack_combinations(
906
existing_packs, pack_distribution)
907
self._execute_pack_operations(pack_operations)
910
def _execute_pack_operations(self, pack_operations):
911
"""Execute a series of pack operations.
913
:param pack_operations: A list of [revision_count, packs_to_combine].
916
for revision_count, packs in pack_operations:
917
# we may have no-ops from the setup logic
920
Packer(self, packs, '.autopack').pack()
922
self._remove_pack_from_memory(pack)
923
# record the newly available packs and stop advertising the old
925
self._save_pack_names(clear_obsolete_packs=True)
926
# Move the old packs out of the way now they are no longer referenced.
927
for revision_count, packs in pack_operations:
928
self._obsolete_packs(packs)
930
def lock_names(self):
931
"""Acquire the mutex around the pack-names index.
933
This cannot be used in the middle of a read-only transaction on the
936
self.repo.control_files.lock_write()
939
"""Pack the pack collection totally."""
941
total_packs = len(self._names)
944
total_revisions = self.revision_index.combined_index.key_count()
945
# XXX: the following may want to be a class, to pack with a given
947
mutter('Packing repository %s, which has %d pack files, '
948
'containing %d revisions into 1 packs.', self, total_packs,
950
# determine which packs need changing
951
pack_distribution = [1]
952
pack_operations = [[0, []]]
953
for pack in self.all_packs():
954
revision_count = pack.get_revision_count()
955
pack_operations[-1][0] += revision_count
956
pack_operations[-1][1].append(pack)
957
self._execute_pack_operations(pack_operations)
959
def plan_autopack_combinations(self, existing_packs, pack_distribution):
960
"""Plan a pack operation.
962
:param existing_packs: The packs to pack. (A list of (revcount, Pack)
964
:param pack_distribution: A list with the number of revisions desired
967
if len(existing_packs) <= len(pack_distribution):
969
existing_packs.sort(reverse=True)
970
pack_operations = [[0, []]]
971
# plan out what packs to keep, and what to reorganise
972
while len(existing_packs):
973
# take the largest pack, and if its less than the head of the
974
# distribution chart we will include its contents in the new pack for
975
# that position. If its larger, we remove its size from the
977
next_pack_rev_count, next_pack = existing_packs.pop(0)
978
if next_pack_rev_count >= pack_distribution[0]:
979
# this is already packed 'better' than this, so we can
980
# not waste time packing it.
981
while next_pack_rev_count > 0:
982
next_pack_rev_count -= pack_distribution[0]
983
if next_pack_rev_count >= 0:
985
del pack_distribution[0]
987
# didn't use that entire bucket up
988
pack_distribution[0] = -next_pack_rev_count
990
# add the revisions we're going to add to the next output pack
991
pack_operations[-1][0] += next_pack_rev_count
992
# allocate this pack to the next pack sub operation
993
pack_operations[-1][1].append(next_pack)
994
if pack_operations[-1][0] >= pack_distribution[0]:
995
# this pack is used up, shift left.
996
del pack_distribution[0]
997
pack_operations.append([0, []])
999
return pack_operations
1001
def ensure_loaded(self):
1002
# NB: if you see an assertion error here, its probably access against
1003
# an unlocked repo. Naughty.
1004
assert self.repo.is_locked()
1005
if self._names is None:
1007
self._packs_at_load = set()
1008
for index, key, value in self._iter_disk_pack_index():
1010
self._names[name] = self._parse_index_sizes(value)
1011
self._packs_at_load.add((key, value))
1012
# populate all the metadata.
1015
def _parse_index_sizes(self, value):
1016
"""Parse a string of index sizes."""
1017
return tuple([int(digits) for digits in value.split(' ')])
1019
def get_pack_by_name(self, name):
1020
"""Get a Pack object by name.
1022
:param name: The name of the pack - e.g. '123456'
1023
:return: A Pack object.
1026
return self._packs_by_name[name]
1028
rev_index = self._make_index(name, '.rix')
1029
inv_index = self._make_index(name, '.iix')
1030
txt_index = self._make_index(name, '.tix')
1031
sig_index = self._make_index(name, '.six')
1032
result = ExistingPack(self._pack_transport, name, rev_index,
1033
inv_index, txt_index, sig_index)
1034
self.add_pack_to_memory(result)
1037
def allocate(self, a_new_pack):
1038
"""Allocate name in the list of packs.
1040
:param a_new_pack: A NewPack instance to be added to the collection of
1041
packs for this repository.
1043
self.ensure_loaded()
1044
if a_new_pack.name in self._names:
1045
# a collision with the packs we know about (not the only possible
1046
# collision, see NewPack.finish() for some discussion). Remove our
1047
# prior reference to it.
1048
self._remove_pack_from_memory(a_new_pack)
1049
self._names[a_new_pack.name] = tuple(a_new_pack.index_sizes)
1050
self.add_pack_to_memory(a_new_pack)
1052
def _iter_disk_pack_index(self):
1053
"""Iterate over the contents of the pack-names index.
1055
This is used when loading the list from disk, and before writing to
1056
detect updates from others during our write operation.
1057
:return: An iterator of the index contents.
1059
return GraphIndex(self.transport, 'pack-names', None
1060
).iter_all_entries()
1062
def _make_index(self, name, suffix):
1063
size_offset = self._suffix_offsets[suffix]
1064
index_name = name + suffix
1065
index_size = self._names[name][size_offset]
1067
self._index_transport, index_name, index_size)
1069
def _max_pack_count(self, total_revisions):
1070
"""Return the maximum number of packs to use for total revisions.
1072
:param total_revisions: The total number of revisions in the
1075
if not total_revisions:
1077
digits = str(total_revisions)
1079
for digit in digits:
1080
result += int(digit)
1084
"""Provide an order to the underlying names."""
1085
return sorted(self._names.keys())
1087
def _obsolete_packs(self, packs):
1088
"""Move a number of packs which have been obsoleted out of the way.
1090
Each pack and its associated indices are moved out of the way.
1092
Note: for correctness this function should only be called after a new
1093
pack names index has been written without these pack names, and with
1094
the names of packs that contain the data previously available via these
1097
:param packs: The packs to obsolete.
1098
:param return: None.
1101
pack.pack_transport.rename(pack.file_name(),
1102
'../obsolete_packs/' + pack.file_name())
1103
# TODO: Probably needs to know all possible indices for this pack
1104
# - or maybe list the directory and move all indices matching this
1105
# name whether we recognize it or not?
1106
for suffix in ('.iix', '.six', '.tix', '.rix'):
1107
self._index_transport.rename(pack.name + suffix,
1108
'../obsolete_packs/' + pack.name + suffix)
1110
def pack_distribution(self, total_revisions):
1111
"""Generate a list of the number of revisions to put in each pack.
1113
:param total_revisions: The total number of revisions in the
1116
if total_revisions == 0:
1118
digits = reversed(str(total_revisions))
1120
for exponent, count in enumerate(digits):
1121
size = 10 ** exponent
1122
for pos in range(int(count)):
1124
return list(reversed(result))
1126
def _pack_tuple(self, name):
1127
"""Return a tuple with the transport and file name for a pack name."""
1128
return self._pack_transport, name + '.pack'
1130
def _remove_pack_from_memory(self, pack):
1131
"""Remove pack from the packs accessed by this repository.
1133
Only affects memory state, until self._save_pack_names() is invoked.
1135
self._names.pop(pack.name)
1136
self._packs_by_name.pop(pack.name)
1137
self._remove_pack_indices(pack)
1139
def _remove_pack_indices(self, pack):
1140
"""Remove the indices for pack from the aggregated indices."""
1141
self.revision_index.remove_index(pack.revision_index, pack)
1142
self.inventory_index.remove_index(pack.inventory_index, pack)
1143
self.text_index.remove_index(pack.text_index, pack)
1144
self.signature_index.remove_index(pack.signature_index, pack)
1147
"""Clear all cached data."""
1148
# cached revision data
1149
self.repo._revision_knit = None
1150
self.revision_index.clear()
1151
# cached signature data
1152
self.repo._signature_knit = None
1153
self.signature_index.clear()
1154
# cached file text data
1155
self.text_index.clear()
1156
self.repo._text_knit = None
1157
# cached inventory data
1158
self.inventory_index.clear()
1159
# remove the open pack
1160
self._new_pack = None
1161
# information about packs.
1164
self._packs_by_name = {}
1165
self._packs_at_load = None
1167
def _make_index_map(self, index_suffix):
1168
"""Return information on existing indices.
1170
:param suffix: Index suffix added to pack name.
1172
:returns: (pack_map, indices) where indices is a list of GraphIndex
1173
objects, and pack_map is a mapping from those objects to the
1174
pack tuple they describe.
1176
# TODO: stop using this; it creates new indices unnecessarily.
1177
self.ensure_loaded()
1178
suffix_map = {'.rix': 'revision_index',
1179
'.six': 'signature_index',
1180
'.iix': 'inventory_index',
1181
'.tix': 'text_index',
1183
return self._packs_list_to_pack_map_and_index_list(self.all_packs(),
1184
suffix_map[index_suffix])
1186
def _packs_list_to_pack_map_and_index_list(self, packs, index_attribute):
1187
"""Convert a list of packs to an index pack map and index list.
1189
:param packs: The packs list to process.
1190
:param index_attribute: The attribute that the desired index is found
1192
:return: A tuple (map, list) where map contains the dict from
1193
index:pack_tuple, and lsit contains the indices in the same order
1199
index = getattr(pack, index_attribute)
1200
indices.append(index)
1201
pack_map[index] = (pack.pack_transport, pack.file_name())
1202
return pack_map, indices
1204
def _index_contents(self, pack_map, key_filter=None):
1205
"""Get an iterable of the index contents from a pack_map.
1207
:param pack_map: A map from indices to pack details.
1208
:param key_filter: An optional filter to limit the
1211
indices = [index for index in pack_map.iterkeys()]
1212
all_index = CombinedGraphIndex(indices)
1213
if key_filter is None:
1214
return all_index.iter_all_entries()
1216
return all_index.iter_entries(key_filter)
1218
def _unlock_names(self):
1219
"""Release the mutex around the pack-names index."""
1220
self.repo.control_files.unlock()
1222
def _save_pack_names(self, clear_obsolete_packs=False):
1223
"""Save the list of packs.
1225
This will take out the mutex around the pack names list for the
1226
duration of the method call. If concurrent updates have been made, a
1227
three-way merge between the current list and the current in memory list
1230
:param clear_obsolete_packs: If True, clear out the contents of the
1231
obsolete_packs directory.
1235
builder = GraphIndexBuilder()
1236
# load the disk nodes across
1238
for index, key, value in self._iter_disk_pack_index():
1239
disk_nodes.add((key, value))
1240
# do a two-way diff against our original content
1241
current_nodes = set()
1242
for name, sizes in self._names.iteritems():
1244
((name, ), ' '.join(str(size) for size in sizes)))
1245
deleted_nodes = self._packs_at_load - current_nodes
1246
new_nodes = current_nodes - self._packs_at_load
1247
disk_nodes.difference_update(deleted_nodes)
1248
disk_nodes.update(new_nodes)
1249
# TODO: handle same-name, index-size-changes here -
1250
# e.g. use the value from disk, not ours, *unless* we're the one
1252
for key, value in disk_nodes:
1253
builder.add_node(key, value)
1254
self.transport.put_file('pack-names', builder.finish(),
1255
mode=self.repo.control_files._file_mode)
1256
# move the baseline forward
1257
self._packs_at_load = disk_nodes
1258
# now clear out the obsolete packs directory
1259
if clear_obsolete_packs:
1260
self.transport.clone('obsolete_packs').delete_multi(
1261
self.transport.list_dir('obsolete_packs'))
1263
self._unlock_names()
1264
# synchronise the memory packs list with what we just wrote:
1265
new_names = dict(disk_nodes)
1266
# drop no longer present nodes
1267
for pack in self.all_packs():
1268
if (pack.name,) not in new_names:
1269
self._remove_pack_from_memory(pack)
1270
# add new nodes/refresh existing ones
1271
for key, value in disk_nodes:
1273
sizes = self._parse_index_sizes(value)
1274
if name in self._names:
1276
if sizes != self._names[name]:
1277
# the pack for name has had its indices replaced - rare but
1278
# important to handle. XXX: probably can never happen today
1279
# because the three-way merge code above does not handle it
1280
# - you may end up adding the same key twice to the new
1281
# disk index because the set values are the same, unless
1282
# the only index shows up as deleted by the set difference
1283
# - which it may. Until there is a specific test for this,
1284
# assume its broken. RBC 20071017.
1285
self._remove_pack_from_memory(self.get_pack_by_name(name))
1286
self._names[name] = sizes
1287
self.get_pack_by_name(name)
1290
self._names[name] = sizes
1291
self.get_pack_by_name(name)
1293
def _start_write_group(self):
1294
# Do not permit preparation for writing if we're not in a 'write lock'.
1295
if not self.repo.is_write_locked():
1296
raise errors.NotWriteLocked(self)
1297
self._new_pack = NewPack(self._upload_transport, self._index_transport,
1298
self._pack_transport, upload_suffix='.pack',
1299
file_mode=self.repo.control_files._file_mode)
1300
# allow writing: queue writes to a new index
1301
self.revision_index.add_writable_index(self._new_pack.revision_index,
1303
self.inventory_index.add_writable_index(self._new_pack.inventory_index,
1305
self.text_index.add_writable_index(self._new_pack.text_index,
1307
self.signature_index.add_writable_index(self._new_pack.signature_index,
1310
# reused revision and signature knits may need updating
1312
# "Hysterical raisins. client code in bzrlib grabs those knits outside
1313
# of write groups and then mutates it inside the write group."
1314
if self.repo._revision_knit is not None:
1315
self.repo._revision_knit._index._add_callback = \
1316
self.revision_index.add_callback
1317
if self.repo._signature_knit is not None:
1318
self.repo._signature_knit._index._add_callback = \
1319
self.signature_index.add_callback
1320
# create a reused knit object for text addition in commit.
1321
self.repo._text_knit = self.repo.weave_store.get_weave_or_empty(
1324
def _abort_write_group(self):
1325
# FIXME: just drop the transient index.
1326
# forget what names there are
1327
self._new_pack.abort()
1328
self._remove_pack_indices(self._new_pack)
1329
self._new_pack = None
1330
self.repo._text_knit = None
1332
def _commit_write_group(self):
1333
self._remove_pack_indices(self._new_pack)
1334
if self._new_pack.data_inserted():
1335
# get all the data to disk and read to use
1336
self._new_pack.finish()
1337
self.allocate(self._new_pack)
1338
self._new_pack = None
1339
if not self.autopack():
1340
# when autopack takes no steps, the names list is still
1342
self._save_pack_names()
1344
self._new_pack.abort()
1345
self._new_pack = None
1346
self.repo._text_knit = None
1349
class KnitPackRevisionStore(KnitRevisionStore):
1350
"""An object to adapt access from RevisionStore's to use KnitPacks.
1352
This class works by replacing the original RevisionStore.
1353
We need to do this because the KnitPackRevisionStore is less
1354
isolated in its layering - it uses services from the repo.
1357
def __init__(self, repo, transport, revisionstore):
1358
"""Create a KnitPackRevisionStore on repo with revisionstore.
1360
This will store its state in the Repository, use the
1361
indices to provide a KnitGraphIndex,
1362
and at the end of transactions write new indices.
1364
KnitRevisionStore.__init__(self, revisionstore.versioned_file_store)
1366
self._serializer = revisionstore._serializer
1367
self.transport = transport
1369
def get_revision_file(self, transaction):
1370
"""Get the revision versioned file object."""
1371
if getattr(self.repo, '_revision_knit', None) is not None:
1372
return self.repo._revision_knit
1373
self.repo._pack_collection.ensure_loaded()
1374
add_callback = self.repo._pack_collection.revision_index.add_callback
1375
# setup knit specific objects
1376
knit_index = KnitGraphIndex(
1377
self.repo._pack_collection.revision_index.combined_index,
1378
add_callback=add_callback)
1379
self.repo._revision_knit = knit.KnitVersionedFile(
1380
'revisions', self.transport.clone('..'),
1381
self.repo.control_files._file_mode,
1382
create=False, access_mode=self.repo._access_mode(),
1383
index=knit_index, delta=False, factory=knit.KnitPlainFactory(),
1384
access_method=self.repo._pack_collection.revision_index.knit_access)
1385
return self.repo._revision_knit
1387
def get_signature_file(self, transaction):
1388
"""Get the signature versioned file object."""
1389
if getattr(self.repo, '_signature_knit', None) is not None:
1390
return self.repo._signature_knit
1391
self.repo._pack_collection.ensure_loaded()
1392
add_callback = self.repo._pack_collection.signature_index.add_callback
1393
# setup knit specific objects
1394
knit_index = KnitGraphIndex(
1395
self.repo._pack_collection.signature_index.combined_index,
1396
add_callback=add_callback, parents=False)
1397
self.repo._signature_knit = knit.KnitVersionedFile(
1398
'signatures', self.transport.clone('..'),
1399
self.repo.control_files._file_mode,
1400
create=False, access_mode=self.repo._access_mode(),
1401
index=knit_index, delta=False, factory=knit.KnitPlainFactory(),
1402
access_method=self.repo._pack_collection.signature_index.knit_access)
1403
return self.repo._signature_knit
1406
class KnitPackTextStore(VersionedFileStore):
1407
"""Presents a TextStore abstraction on top of packs.
1409
This class works by replacing the original VersionedFileStore.
1410
We need to do this because the KnitPackRevisionStore is less
1411
isolated in its layering - it uses services from the repo and shares them
1412
with all the data written in a single write group.
1415
def __init__(self, repo, transport, weavestore):
1416
"""Create a KnitPackTextStore on repo with weavestore.
1418
This will store its state in the Repository, use the
1419
indices FileNames to provide a KnitGraphIndex,
1420
and at the end of transactions write new indices.
1422
# don't call base class constructor - it's not suitable.
1423
# no transient data stored in the transaction
1425
self._precious = False
1427
self.transport = transport
1428
self.weavestore = weavestore
1429
# XXX for check() which isn't updated yet
1430
self._transport = weavestore._transport
1432
def get_weave_or_empty(self, file_id, transaction):
1433
"""Get a 'Knit' backed by the .tix indices.
1435
The transaction parameter is ignored.
1437
self.repo._pack_collection.ensure_loaded()
1438
add_callback = self.repo._pack_collection.text_index.add_callback
1439
# setup knit specific objects
1440
file_id_index = GraphIndexPrefixAdapter(
1441
self.repo._pack_collection.text_index.combined_index,
1442
(file_id, ), 1, add_nodes_callback=add_callback)
1443
knit_index = KnitGraphIndex(file_id_index,
1444
add_callback=file_id_index.add_nodes,
1445
deltas=True, parents=True)
1446
return knit.KnitVersionedFile('text:' + file_id,
1447
self.transport.clone('..'),
1450
access_method=self.repo._pack_collection.text_index.knit_access,
1451
factory=knit.KnitPlainFactory())
1453
get_weave = get_weave_or_empty
1456
"""Generate a list of the fileids inserted, for use by check."""
1457
self.repo._pack_collection.ensure_loaded()
1459
for index, key, value, refs in \
1460
self.repo._pack_collection.text_index.combined_index.iter_all_entries():
1465
class InventoryKnitThunk(object):
1466
"""An object to manage thunking get_inventory_weave to pack based knits."""
1468
def __init__(self, repo, transport):
1469
"""Create an InventoryKnitThunk for repo at transport.
1471
This will store its state in the Repository, use the
1472
indices FileNames to provide a KnitGraphIndex,
1473
and at the end of transactions write a new index..
1476
self.transport = transport
1478
def get_weave(self):
1479
"""Get a 'Knit' that contains inventory data."""
1480
self.repo._pack_collection.ensure_loaded()
1481
add_callback = self.repo._pack_collection.inventory_index.add_callback
1482
# setup knit specific objects
1483
knit_index = KnitGraphIndex(
1484
self.repo._pack_collection.inventory_index.combined_index,
1485
add_callback=add_callback, deltas=True, parents=True)
1486
return knit.KnitVersionedFile(
1487
'inventory', self.transport.clone('..'),
1488
self.repo.control_files._file_mode,
1489
create=False, access_mode=self.repo._access_mode(),
1490
index=knit_index, delta=True, factory=knit.KnitPlainFactory(),
1491
access_method=self.repo._pack_collection.inventory_index.knit_access)
1494
class KnitPackRepository(KnitRepository):
1495
"""Experimental graph-knit using repository."""
1497
def __init__(self, _format, a_bzrdir, control_files, _revision_store,
1498
control_store, text_store, _commit_builder_class, _serializer):
1499
KnitRepository.__init__(self, _format, a_bzrdir, control_files,
1500
_revision_store, control_store, text_store, _commit_builder_class,
1502
index_transport = control_files._transport.clone('indices')
1503
self._pack_collection = RepositoryPackCollection(self, control_files._transport,
1505
control_files._transport.clone('upload'),
1506
control_files._transport.clone('packs'))
1507
self._revision_store = KnitPackRevisionStore(self, index_transport, self._revision_store)
1508
self.weave_store = KnitPackTextStore(self, index_transport, self.weave_store)
1509
self._inv_thunk = InventoryKnitThunk(self, index_transport)
1510
# True when the repository object is 'write locked' (as opposed to the
1511
# physical lock only taken out around changes to the pack-names list.)
1512
# Another way to represent this would be a decorator around the control
1513
# files object that presents logical locks as physical ones - if this
1514
# gets ugly consider that alternative design. RBC 20071011
1515
self._write_lock_count = 0
1516
self._transaction = None
1518
self._reconcile_does_inventory_gc = True
1519
self._reconcile_fixes_text_parents = False
1520
self._reconcile_backsup_inventory = False
1522
def _abort_write_group(self):
1523
self._pack_collection._abort_write_group()
1525
def _access_mode(self):
1526
"""Return 'w' or 'r' for depending on whether a write lock is active.
1528
This method is a helper for the Knit-thunking support objects.
1530
if self.is_write_locked():
1534
def _find_inconsistent_revision_parents(self):
1535
"""Find revisions with incorrectly cached parents.
1537
:returns: an iterator yielding tuples of (revison-id, parents-in-index,
1538
parents-in-revision).
1540
assert self.is_locked()
1541
pb = ui.ui_factory.nested_progress_bar()
1544
revision_nodes = self._pack_collection.revision_index \
1545
.combined_index.iter_all_entries()
1546
index_positions = []
1547
# Get the cached index values for all revisions, and also the location
1548
# in each index of the revision text so we can perform linear IO.
1549
for index, key, value, refs in revision_nodes:
1550
pos, length = value[1:].split(' ')
1551
index_positions.append((index, int(pos), key[0],
1552
tuple(parent[0] for parent in refs[0])))
1553
pb.update("Reading revision index.", 0, 0)
1554
index_positions.sort()
1555
batch_count = len(index_positions) / 1000 + 1
1556
pb.update("Checking cached revision graph.", 0, batch_count)
1557
for offset in xrange(batch_count):
1558
pb.update("Checking cached revision graph.", offset)
1559
to_query = index_positions[offset * 1000:(offset + 1) * 1000]
1562
rev_ids = [item[2] for item in to_query]
1563
revs = self.get_revisions(rev_ids)
1564
for revision, item in zip(revs, to_query):
1565
index_parents = item[3]
1566
rev_parents = tuple(revision.parent_ids)
1567
if index_parents != rev_parents:
1568
result.append((revision.revision_id, index_parents, rev_parents))
1573
def get_parents(self, revision_ids):
1574
"""See StackedParentsProvider.get_parents.
1576
This implementation accesses the combined revision index to provide
1579
self._pack_collection.ensure_loaded()
1580
index = self._pack_collection.revision_index.combined_index
1582
for revision_id in revision_ids:
1583
if revision_id != _mod_revision.NULL_REVISION:
1584
search_keys.add((revision_id,))
1585
found_parents = {_mod_revision.NULL_REVISION:[]}
1586
for index, key, value, refs in index.iter_entries(search_keys):
1589
parents = (_mod_revision.NULL_REVISION,)
1591
parents = tuple(parent[0] for parent in parents)
1592
found_parents[key[0]] = parents
1594
for revision_id in revision_ids:
1596
result.append(found_parents[revision_id])
1601
def _make_parents_provider(self):
1604
def _refresh_data(self):
1605
if self._write_lock_count == 1 or (
1606
self.control_files._lock_count == 1 and
1607
self.control_files._lock_mode == 'r'):
1608
# forget what names there are
1609
self._pack_collection.reset()
1610
# XXX: Better to do an in-memory merge when acquiring a new lock -
1611
# factor out code from _save_pack_names.
1612
self._pack_collection.ensure_loaded()
1614
def _start_write_group(self):
1615
self._pack_collection._start_write_group()
1617
def _commit_write_group(self):
1618
return self._pack_collection._commit_write_group()
1620
def get_inventory_weave(self):
1621
return self._inv_thunk.get_weave()
1623
def get_transaction(self):
1624
if self._write_lock_count:
1625
return self._transaction
1627
return self.control_files.get_transaction()
1629
def is_locked(self):
1630
return self._write_lock_count or self.control_files.is_locked()
1632
def is_write_locked(self):
1633
return self._write_lock_count
1635
def lock_write(self, token=None):
1636
if not self._write_lock_count and self.is_locked():
1637
raise errors.ReadOnlyError(self)
1638
self._write_lock_count += 1
1639
if self._write_lock_count == 1:
1640
from bzrlib import transactions
1641
self._transaction = transactions.WriteTransaction()
1642
self._refresh_data()
1644
def lock_read(self):
1645
if self._write_lock_count:
1646
self._write_lock_count += 1
1648
self.control_files.lock_read()
1649
self._refresh_data()
1651
def leave_lock_in_place(self):
1652
# not supported - raise an error
1653
raise NotImplementedError(self.leave_lock_in_place)
1655
def dont_leave_lock_in_place(self):
1656
# not supported - raise an error
1657
raise NotImplementedError(self.dont_leave_lock_in_place)
1661
"""Compress the data within the repository.
1663
This will pack all the data to a single pack. In future it may
1664
recompress deltas or do other such expensive operations.
1666
self._pack_collection.pack()
1669
def reconcile(self, other=None, thorough=False):
1670
"""Reconcile this repository."""
1671
from bzrlib.reconcile import PackReconciler
1672
reconciler = PackReconciler(self, thorough=thorough)
1673
reconciler.reconcile()
1677
if self._write_lock_count == 1 and self._write_group is not None:
1678
self.abort_write_group()
1679
self._transaction = None
1680
self._write_lock_count = 0
1681
raise errors.BzrError(
1682
'Must end write group before releasing write lock on %s'
1684
if self._write_lock_count:
1685
self._write_lock_count -= 1
1686
if not self._write_lock_count:
1687
transaction = self._transaction
1688
self._transaction = None
1689
transaction.finish()
1691
self.control_files.unlock()
1694
class RepositoryFormatPack(MetaDirRepositoryFormat):
1695
"""Format logic for pack structured repositories.
1697
This repository format has:
1698
- a list of packs in pack-names
1699
- packs in packs/NAME.pack
1700
- indices in indices/NAME.{iix,six,tix,rix}
1701
- knit deltas in the packs, knit indices mapped to the indices.
1702
- thunk objects to support the knits programming API.
1703
- a format marker of its own
1704
- an optional 'shared-storage' flag
1705
- an optional 'no-working-trees' flag
1709
# Set this attribute in derived classes to control the repository class
1710
# created by open and initialize.
1711
repository_class = None
1712
# Set this attribute in derived classes to control the
1713
# _commit_builder_class that the repository objects will have passed to
1714
# their constructor.
1715
_commit_builder_class = None
1716
# Set this attribute in derived clases to control the _serializer that the
1717
# repository objects will have passed to their constructor.
1720
def _get_control_store(self, repo_transport, control_files):
1721
"""Return the control store for this repository."""
1722
return VersionedFileStore(
1725
file_mode=control_files._file_mode,
1726
versionedfile_class=knit.KnitVersionedFile,
1727
versionedfile_kwargs={'factory': knit.KnitPlainFactory()},
1730
def _get_revision_store(self, repo_transport, control_files):
1731
"""See RepositoryFormat._get_revision_store()."""
1732
versioned_file_store = VersionedFileStore(
1734
file_mode=control_files._file_mode,
1737
versionedfile_class=knit.KnitVersionedFile,
1738
versionedfile_kwargs={'delta': False,
1739
'factory': knit.KnitPlainFactory(),
1743
return KnitRevisionStore(versioned_file_store)
1745
def _get_text_store(self, transport, control_files):
1746
"""See RepositoryFormat._get_text_store()."""
1747
return self._get_versioned_file_store('knits',
1750
versionedfile_class=knit.KnitVersionedFile,
1751
versionedfile_kwargs={
1752
'create_parent_dir': True,
1753
'delay_create': True,
1754
'dir_mode': control_files._dir_mode,
1758
def initialize(self, a_bzrdir, shared=False):
1759
"""Create a pack based repository.
1761
:param a_bzrdir: bzrdir to contain the new repository; must already
1763
:param shared: If true the repository will be initialized as a shared
1766
mutter('creating repository in %s.', a_bzrdir.transport.base)
1767
dirs = ['indices', 'obsolete_packs', 'packs', 'upload']
1768
builder = GraphIndexBuilder()
1769
files = [('pack-names', builder.finish())]
1770
utf8_files = [('format', self.get_format_string())]
1772
self._upload_blank_content(a_bzrdir, dirs, files, utf8_files, shared)
1773
return self.open(a_bzrdir=a_bzrdir, _found=True)
1775
def open(self, a_bzrdir, _found=False, _override_transport=None):
1776
"""See RepositoryFormat.open().
1778
:param _override_transport: INTERNAL USE ONLY. Allows opening the
1779
repository at a slightly different url
1780
than normal. I.e. during 'upgrade'.
1783
format = RepositoryFormat.find_format(a_bzrdir)
1784
assert format.__class__ == self.__class__
1785
if _override_transport is not None:
1786
repo_transport = _override_transport
1788
repo_transport = a_bzrdir.get_repository_transport(None)
1789
control_files = lockable_files.LockableFiles(repo_transport,
1790
'lock', lockdir.LockDir)
1791
text_store = self._get_text_store(repo_transport, control_files)
1792
control_store = self._get_control_store(repo_transport, control_files)
1793
_revision_store = self._get_revision_store(repo_transport, control_files)
1794
return self.repository_class(_format=self,
1796
control_files=control_files,
1797
_revision_store=_revision_store,
1798
control_store=control_store,
1799
text_store=text_store,
1800
_commit_builder_class=self._commit_builder_class,
1801
_serializer=self._serializer)
1804
class RepositoryFormatKnitPack1(RepositoryFormatPack):
1805
"""A no-subtrees parameterised Pack repository.
1807
This format was introduced in 0.92.
1810
repository_class = KnitPackRepository
1811
_commit_builder_class = PackCommitBuilder
1812
_serializer = xml5.serializer_v5
1814
def _get_matching_bzrdir(self):
1815
return bzrdir.format_registry.make_bzrdir('pack-0.92')
1817
def _ignore_setting_bzrdir(self, format):
1820
_matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
1822
def get_format_string(self):
1823
"""See RepositoryFormat.get_format_string()."""
1824
return "Bazaar pack repository format 1 (needs bzr 0.92)\n"
1826
def get_format_description(self):
1827
"""See RepositoryFormat.get_format_description()."""
1828
return "Packs containing knits without subtree support"
1830
def check_conversion_target(self, target_format):
1834
class RepositoryFormatKnitPack3(RepositoryFormatPack):
1835
"""A subtrees parameterised Pack repository.
1837
This repository format uses the xml7 serializer to get:
1838
- support for recording full info about the tree root
1839
- support for recording tree-references
1841
This format was introduced in 0.92.
1844
repository_class = KnitPackRepository
1845
_commit_builder_class = PackRootCommitBuilder
1846
rich_root_data = True
1847
supports_tree_reference = True
1848
_serializer = xml7.serializer_v7
1850
def _get_matching_bzrdir(self):
1851
return bzrdir.format_registry.make_bzrdir(
1852
'pack-0.92-subtree')
1854
def _ignore_setting_bzrdir(self, format):
1857
_matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
1859
def check_conversion_target(self, target_format):
1860
if not target_format.rich_root_data:
1861
raise errors.BadConversionTarget(
1862
'Does not support rich root data.', target_format)
1863
if not getattr(target_format, 'supports_tree_reference', False):
1864
raise errors.BadConversionTarget(
1865
'Does not support nested trees', target_format)
1867
def get_format_string(self):
1868
"""See RepositoryFormat.get_format_string()."""
1869
return "Bazaar pack repository format 1 with subtree support (needs bzr 0.92)\n"
1871
def get_format_description(self):
1872
"""See RepositoryFormat.get_format_description()."""
1873
return "Packs containing knits with subtree support\n"
1876
class RepositoryFormatKnitPack4(RepositoryFormatPack):
1877
"""A rich-root, no subtrees parameterised Pack repository.
1879
This repository format uses the xml6 serializer to get:
1880
- support for recording full info about the tree root
1882
This format was introduced in 1.0.
1885
repository_class = KnitPackRepository
1886
_commit_builder_class = PackRootCommitBuilder
1887
rich_root_data = True
1888
supports_tree_reference = False
1889
_serializer = xml6.serializer_v6
1891
def _get_matching_bzrdir(self):
1892
return bzrdir.format_registry.make_bzrdir(
1895
def _ignore_setting_bzrdir(self, format):
1898
_matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
1900
def check_conversion_target(self, target_format):
1901
if not target_format.rich_root_data:
1902
raise errors.BadConversionTarget(
1903
'Does not support rich root data.', target_format)
1905
def get_format_string(self):
1906
"""See RepositoryFormat.get_format_string()."""
1907
return ("Bazaar pack repository format 1 with rich root"
1908
" (needs bzr 1.0)\n")
1910
def get_format_description(self):
1911
"""See RepositoryFormat.get_format_description()."""
1912
return "Packs containing knits with rich root support\n"