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
54
from bzrlib.decorators import needs_read_lock, needs_write_lock
55
from bzrlib.repofmt.knitrepo import KnitRepository
56
from bzrlib.repository import (
59
MetaDirRepositoryFormat,
62
import bzrlib.revision as _mod_revision
63
from bzrlib.store.revision.knit import KnitRevisionStore
64
from bzrlib.store.versioned import VersionedFileStore
65
from bzrlib.trace import mutter, note, warning
68
class PackCommitBuilder(CommitBuilder):
69
"""A subclass of CommitBuilder to add texts with pack semantics.
71
Specifically this uses one knit object rather than one knit object per
72
added text, reducing memory and object pressure.
75
def _add_text_to_weave(self, file_id, new_lines, parents, nostore_sha):
76
return self.repository._pack_collection._add_text_to_weave(file_id,
77
self._new_revision_id, new_lines, parents, nostore_sha,
81
class PackRootCommitBuilder(RootCommitBuilder):
82
"""A subclass of RootCommitBuilder to add texts with pack semantics.
84
Specifically this uses one knit object rather than one knit object per
85
added text, reducing memory and object pressure.
88
def _add_text_to_weave(self, file_id, new_lines, parents, nostore_sha):
89
return self.repository._pack_collection._add_text_to_weave(file_id,
90
self._new_revision_id, new_lines, parents, nostore_sha,
95
"""An in memory proxy for a pack and its indices.
97
This is a base class that is not directly used, instead the classes
98
ExistingPack and NewPack are used.
101
def __init__(self, revision_index, inventory_index, text_index,
103
"""Create a pack instance.
105
:param revision_index: A GraphIndex for determining what revisions are
106
present in the Pack and accessing the locations of their texts.
107
:param inventory_index: A GraphIndex for determining what inventories are
108
present in the Pack and accessing the locations of their
110
:param text_index: A GraphIndex for determining what file texts
111
are present in the pack and accessing the locations of their
112
texts/deltas (via (fileid, revisionid) tuples).
113
:param revision_index: A GraphIndex for determining what signatures are
114
present in the Pack and accessing the locations of their texts.
116
self.revision_index = revision_index
117
self.inventory_index = inventory_index
118
self.text_index = text_index
119
self.signature_index = signature_index
121
def access_tuple(self):
122
"""Return a tuple (transport, name) for the pack content."""
123
return self.pack_transport, self.file_name()
126
"""Get the file name for the pack on disk."""
127
return self.name + '.pack'
129
def get_revision_count(self):
130
return self.revision_index.key_count()
132
def inventory_index_name(self, name):
133
"""The inv index is the name + .iix."""
134
return self.index_name('inventory', name)
136
def revision_index_name(self, name):
137
"""The revision index is the name + .rix."""
138
return self.index_name('revision', name)
140
def signature_index_name(self, name):
141
"""The signature index is the name + .six."""
142
return self.index_name('signature', name)
144
def text_index_name(self, name):
145
"""The text index is the name + .tix."""
146
return self.index_name('text', name)
149
class ExistingPack(Pack):
150
"""An in memory proxy for an existing .pack and its disk indices."""
152
def __init__(self, pack_transport, name, revision_index, inventory_index,
153
text_index, signature_index):
154
"""Create an ExistingPack object.
156
:param pack_transport: The transport where the pack file resides.
157
:param name: The name of the pack on disk in the pack_transport.
159
Pack.__init__(self, revision_index, inventory_index, text_index,
162
self.pack_transport = pack_transport
163
assert None not in (revision_index, inventory_index, text_index,
164
signature_index, name, pack_transport)
166
def __eq__(self, other):
167
return self.__dict__ == other.__dict__
169
def __ne__(self, other):
170
return not self.__eq__(other)
173
return "<bzrlib.repofmt.pack_repo.Pack object at 0x%x, %s, %s" % (
174
id(self), self.transport, self.name)
178
"""An in memory proxy for a pack which is being created."""
180
# A map of index 'type' to the file extension and position in the
182
index_definitions = {
183
'revision': ('.rix', 0),
184
'inventory': ('.iix', 1),
186
'signature': ('.six', 3),
189
def __init__(self, upload_transport, index_transport, pack_transport,
191
"""Create a NewPack instance.
193
:param upload_transport: A writable transport for the pack to be
194
incrementally uploaded to.
195
:param index_transport: A writable transport for the pack's indices to
196
be written to when the pack is finished.
197
:param pack_transport: A writable transport for the pack to be renamed
198
to when the upload is complete. This *must* be the same as
199
upload_transport.clone('../packs').
200
:param upload_suffix: An optional suffix to be given to any temporary
201
files created during the pack creation. e.g '.autopack'
203
# The relative locations of the packs are constrained, but all are
204
# passed in because the caller has them, so as to avoid object churn.
206
# Revisions: parents list, no text compression.
207
InMemoryGraphIndex(reference_lists=1),
208
# Inventory: We want to map compression only, but currently the
209
# knit code hasn't been updated enough to understand that, so we
210
# have a regular 2-list index giving parents and compression
212
InMemoryGraphIndex(reference_lists=2),
213
# Texts: compression and per file graph, for all fileids - so two
214
# reference lists and two elements in the key tuple.
215
InMemoryGraphIndex(reference_lists=2, key_elements=2),
216
# Signatures: Just blobs to store, no compression, no parents
218
InMemoryGraphIndex(reference_lists=0),
220
# where should the new pack be opened
221
self.upload_transport = upload_transport
222
# where are indices written out to
223
self.index_transport = index_transport
224
# where is the pack renamed to when it is finished?
225
self.pack_transport = pack_transport
226
# tracks the content written to the .pack file.
227
self._hash = md5.new()
228
# a four-tuple with the length in bytes of the indices, once the pack
229
# is finalised. (rev, inv, text, sigs)
230
self.index_sizes = None
231
# How much data to cache when writing packs. Note that this is not
232
# synchronised with reads, because it's not in the transport layer, so
233
# is not safe unless the client knows it won't be reading from the pack
235
self._cache_limit = 0
236
# the temporary pack file name.
237
self.random_name = rand_chars(20) + upload_suffix
238
# when was this pack started ?
239
self.start_time = time.time()
240
# open an output stream for the data added to the pack.
241
self.write_stream = self.upload_transport.open_write_stream(
243
if 'pack' in debug.debug_flags:
244
mutter('%s: create_pack: pack stream open: %s%s t+%6.3fs',
245
time.ctime(), self.upload_transport.base, self.random_name,
246
time.time() - self.start_time)
247
# A list of byte sequences to be written to the new pack, and the
248
# aggregate size of them. Stored as a list rather than separate
249
# variables so that the _write_data closure below can update them.
250
self._buffer = [[], 0]
251
# create a callable for adding data
253
# robertc says- this is a closure rather than a method on the object
254
# so that the variables are locals, and faster than accessing object
256
def _write_data(bytes, flush=False, _buffer=self._buffer,
257
_write=self.write_stream.write, _update=self._hash.update):
258
_buffer[0].append(bytes)
259
_buffer[1] += len(bytes)
261
if _buffer[1] > self._cache_limit or flush:
262
bytes = ''.join(_buffer[0])
266
# expose this on self, for the occasion when clients want to add data.
267
self._write_data = _write_data
268
# a pack writer object to serialise pack records.
269
self._writer = pack.ContainerWriter(self._write_data)
271
# what state is the pack in? (open, finished, aborted)
275
"""Cancel creating this pack."""
276
self._state = 'aborted'
277
self.write_stream.close()
278
# Remove the temporary pack file.
279
self.upload_transport.delete(self.random_name)
280
# The indices have no state on disk.
282
def access_tuple(self):
283
"""Return a tuple (transport, name) for the pack content."""
284
assert self._state in ('open', 'finished')
285
if self._state == 'finished':
286
return Pack.access_tuple(self)
288
return self.upload_transport, self.random_name
290
def data_inserted(self):
291
"""True if data has been added to this pack."""
292
return bool(self.get_revision_count() or
293
self.inventory_index.key_count() or
294
self.text_index.key_count() or
295
self.signature_index.key_count())
298
"""Finish the new pack.
301
- finalises the content
302
- assigns a name (the md5 of the content, currently)
303
- writes out the associated indices
304
- renames the pack into place.
305
- stores the index size tuple for the pack in the index_sizes
310
self._write_data('', flush=True)
311
self.name = self._hash.hexdigest()
313
# XXX: It'd be better to write them all to temporary names, then
314
# rename them all into place, so that the window when only some are
315
# visible is smaller. On the other hand none will be seen until
316
# they're in the names list.
317
self.index_sizes = [None, None, None, None]
318
self._write_index('revision', self.revision_index, 'revision')
319
self._write_index('inventory', self.inventory_index, 'inventory')
320
self._write_index('text', self.text_index, 'file texts')
321
self._write_index('signature', self.signature_index,
322
'revision signatures')
323
self.write_stream.close()
324
# Note that this will clobber an existing pack with the same name,
325
# without checking for hash collisions. While this is undesirable this
326
# is something that can be rectified in a subsequent release. One way
327
# to rectify it may be to leave the pack at the original name, writing
328
# its pack-names entry as something like 'HASH: index-sizes
329
# temporary-name'. Allocate that and check for collisions, if it is
330
# collision free then rename it into place. If clients know this scheme
331
# they can handle missing-file errors by:
332
# - try for HASH.pack
333
# - try for temporary-name
334
# - refresh the pack-list to see if the pack is now absent
335
self.upload_transport.rename(self.random_name,
336
'../packs/' + self.name + '.pack')
337
self._state = 'finished'
338
if 'pack' in debug.debug_flags:
339
# XXX: size might be interesting?
340
mutter('%s: create_pack: pack renamed into place: %s%s->%s%s t+%6.3fs',
341
time.ctime(), self.upload_transport.base, self.random_name,
342
self.pack_transport, self.name,
343
time.time() - self.start_time)
345
def index_name(self, index_type, name):
346
"""Get the disk name of an index type for pack name 'name'."""
347
return name + NewPack.index_definitions[index_type][0]
349
def index_offset(self, index_type):
350
"""Get the position in a index_size array for a given index type."""
351
return NewPack.index_definitions[index_type][1]
353
def _replace_index_with_readonly(self, index_type):
354
setattr(self, index_type + '_index',
355
GraphIndex(self.index_transport,
356
self.index_name(index_type, self.name),
357
self.index_sizes[self.index_offset(index_type)]))
359
def set_write_cache_size(self, size):
360
self._cache_limit = size
362
def _write_index(self, index_type, index, label):
363
"""Write out an index.
365
:param index_type: The type of index to write - e.g. 'revision'.
366
:param index: The index object to serialise.
367
:param label: What label to give the index e.g. 'revision'.
369
index_name = self.index_name(index_type, self.name)
370
self.index_sizes[self.index_offset(index_type)] = \
371
self.index_transport.put_file(index_name, index.finish())
372
if 'pack' in debug.debug_flags:
373
# XXX: size might be interesting?
374
mutter('%s: create_pack: wrote %s index: %s%s t+%6.3fs',
375
time.ctime(), label, self.upload_transport.base,
376
self.random_name, time.time() - self.start_time)
377
# Replace the writable index on this object with a readonly,
378
# presently unloaded index. We should alter
379
# the index layer to make its finish() error if add_node is
380
# subsequently used. RBC
381
self._replace_index_with_readonly(index_type)
384
class AggregateIndex(object):
385
"""An aggregated index for the RepositoryPackCollection.
387
AggregateIndex is reponsible for managing the PackAccess object,
388
Index-To-Pack mapping, and all indices list for a specific type of index
389
such as 'revision index'.
391
A CombinedIndex provides an index on a single key space built up
392
from several on-disk indices. The AggregateIndex builds on this
393
to provide a knit access layer, and allows having up to one writable
394
index within the collection.
396
# XXX: Probably 'can be written to' could/should be separated from 'acts
397
# like a knit index' -- mbp 20071024
400
"""Create an AggregateIndex."""
401
self.index_to_pack = {}
402
self.combined_index = CombinedGraphIndex([])
403
self.knit_access = _PackAccess(self.index_to_pack)
405
def replace_indices(self, index_to_pack, indices):
406
"""Replace the current mappings with fresh ones.
408
This should probably not be used eventually, rather incremental add and
409
removal of indices. It has been added during refactoring of existing
412
:param index_to_pack: A mapping from index objects to
413
(transport, name) tuples for the pack file data.
414
:param indices: A list of indices.
416
# refresh the revision pack map dict without replacing the instance.
417
self.index_to_pack.clear()
418
self.index_to_pack.update(index_to_pack)
419
# XXX: API break - clearly a 'replace' method would be good?
420
self.combined_index._indices[:] = indices
421
# the current add nodes callback for the current writable index if
423
self.add_callback = None
425
def add_index(self, index, pack):
426
"""Add index to the aggregate, which is an index for Pack pack.
428
Future searches on the aggregate index will seach this new index
429
before all previously inserted indices.
431
:param index: An Index for the pack.
432
:param pack: A Pack instance.
434
# expose it to the index map
435
self.index_to_pack[index] = pack.access_tuple()
436
# put it at the front of the linear index list
437
self.combined_index.insert_index(0, index)
439
def add_writable_index(self, index, pack):
440
"""Add an index which is able to have data added to it.
442
There can be at most one writable index at any time. Any
443
modifications made to the knit are put into this index.
445
:param index: An index from the pack parameter.
446
:param pack: A Pack instance.
448
assert self.add_callback is None, \
449
"%s already has a writable index through %s" % \
450
(self, self.add_callback)
451
# allow writing: queue writes to a new index
452
self.add_index(index, pack)
453
# Updates the index to packs mapping as a side effect,
454
self.knit_access.set_writer(pack._writer, index, pack.access_tuple())
455
self.add_callback = index.add_nodes
458
"""Reset all the aggregate data to nothing."""
459
self.knit_access.set_writer(None, None, (None, None))
460
self.index_to_pack.clear()
461
del self.combined_index._indices[:]
462
self.add_callback = None
464
def remove_index(self, index, pack):
465
"""Remove index from the indices used to answer queries.
467
:param index: An index from the pack parameter.
468
:param pack: A Pack instance.
470
del self.index_to_pack[index]
471
self.combined_index._indices.remove(index)
472
if (self.add_callback is not None and
473
getattr(index, 'add_nodes', None) == self.add_callback):
474
self.add_callback = None
475
self.knit_access.set_writer(None, None, (None, None))
478
class RepositoryPackCollection(object):
479
"""Management of packs within a repository."""
481
def __init__(self, repo, transport, index_transport, upload_transport,
483
"""Create a new RepositoryPackCollection.
485
:param transport: Addresses the repository base directory
486
(typically .bzr/repository/).
487
:param index_transport: Addresses the directory containing indices.
488
:param upload_transport: Addresses the directory into which packs are written
489
while they're being created.
490
:param pack_transport: Addresses the directory of existing complete packs.
493
self.transport = transport
494
self._index_transport = index_transport
495
self._upload_transport = upload_transport
496
self._pack_transport = pack_transport
497
self._suffix_offsets = {'.rix': 0, '.iix': 1, '.tix': 2, '.six': 3}
500
self._packs_by_name = {}
501
# the previous pack-names content
502
self._packs_at_load = None
503
# when a pack is being created by this object, the state of that pack.
504
self._new_pack = None
505
# aggregated revision index data
506
self.revision_index = AggregateIndex()
507
self.inventory_index = AggregateIndex()
508
self.text_index = AggregateIndex()
509
self.signature_index = AggregateIndex()
511
def add_pack_to_memory(self, pack):
512
"""Make a Pack object available to the repository to satisfy queries.
514
:param pack: A Pack object.
516
assert pack.name not in self._packs_by_name
517
self.packs.append(pack)
518
self._packs_by_name[pack.name] = pack
519
self.revision_index.add_index(pack.revision_index, pack)
520
self.inventory_index.add_index(pack.inventory_index, pack)
521
self.text_index.add_index(pack.text_index, pack)
522
self.signature_index.add_index(pack.signature_index, pack)
524
def _add_text_to_weave(self, file_id, revision_id, new_lines, parents,
525
nostore_sha, random_revid):
526
file_id_index = GraphIndexPrefixAdapter(
527
self.text_index.combined_index,
529
add_nodes_callback=self.text_index.add_callback)
530
self.repo._text_knit._index._graph_index = file_id_index
531
self.repo._text_knit._index._add_callback = file_id_index.add_nodes
532
return self.repo._text_knit.add_lines_with_ghosts(
533
revision_id, parents, new_lines, nostore_sha=nostore_sha,
534
random_id=random_revid, check_content=False)[0:2]
537
"""Return a list of all the Pack objects this repository has.
539
Note that an in-progress pack being created is not returned.
541
:return: A list of Pack objects for all the packs in the repository.
544
for name in self.names():
545
result.append(self.get_pack_by_name(name))
549
"""Pack the pack collection incrementally.
551
This will not attempt global reorganisation or recompression,
552
rather it will just ensure that the total number of packs does
553
not grow without bound. It uses the _max_pack_count method to
554
determine if autopacking is needed, and the pack_distribution
555
method to determine the number of revisions in each pack.
557
If autopacking takes place then the packs name collection will have
558
been flushed to disk - packing requires updating the name collection
559
in synchronisation with certain steps. Otherwise the names collection
562
:return: True if packing took place.
564
# XXX: Should not be needed when the management of indices is sane.
565
total_revisions = self.revision_index.combined_index.key_count()
566
total_packs = len(self._names)
567
if self._max_pack_count(total_revisions) >= total_packs:
569
# XXX: the following may want to be a class, to pack with a given
571
mutter('Auto-packing repository %s, which has %d pack files, '
572
'containing %d revisions into %d packs.', self, total_packs,
573
total_revisions, self._max_pack_count(total_revisions))
574
# determine which packs need changing
575
pack_distribution = self.pack_distribution(total_revisions)
577
for pack in self.all_packs():
578
revision_count = pack.get_revision_count()
579
if revision_count == 0:
580
# revision less packs are not generated by normal operation,
581
# only by operations like sign-my-commits, and thus will not
582
# tend to grow rapdily or without bound like commit containing
583
# packs do - leave them alone as packing them really should
584
# group their data with the relevant commit, and that may
585
# involve rewriting ancient history - which autopack tries to
586
# avoid. Alternatively we could not group the data but treat
587
# each of these as having a single revision, and thus add
588
# one revision for each to the total revision count, to get
589
# a matching distribution.
591
existing_packs.append((revision_count, pack))
592
pack_operations = self.plan_autopack_combinations(
593
existing_packs, pack_distribution)
594
self._execute_pack_operations(pack_operations)
597
def create_pack_from_packs(self, packs, suffix, revision_ids=None):
598
"""Create a new pack by reading data from other packs.
600
This does little more than a bulk copy of data. One key difference
601
is that data with the same item key across multiple packs is elided
602
from the output. The new pack is written into the current pack store
603
along with its indices, and the name added to the pack names. The
604
source packs are not altered and are not required to be in the current
607
:param packs: An iterable of Packs to combine.
608
:param revision_ids: Either None, to copy all data, or a list
609
of revision_ids to limit the copied data to the data they
611
:return: A Pack object, or None if nothing was copied.
613
# open a pack - using the same name as the last temporary file
614
# - which has already been flushed, so its safe.
615
# XXX: - duplicate code warning with start_write_group; fix before
616
# considering 'done'.
617
if self._new_pack is not None:
618
raise errors.BzrError('call to create_pack_from_packs while '
619
'another pack is being written.')
620
if revision_ids is not None:
621
if len(revision_ids) == 0:
622
# silly fetch request.
625
revision_ids = frozenset(revision_ids)
626
pb = ui.ui_factory.nested_progress_bar()
628
return self._create_pack_from_packs(packs, suffix, revision_ids,
633
def _create_pack_from_packs(self, packs, suffix, revision_ids, pb):
634
pb.update("Opening pack", 0, 5)
635
revision_ids = frozenset(revision_ids)
636
new_pack = NewPack(self._upload_transport, self._index_transport,
637
self._pack_transport, upload_suffix=suffix)
638
# buffer data - we won't be reading-back during the pack creation and
639
# this makes a significant difference on sftp pushes.
640
new_pack.set_write_cache_size(1024*1024)
641
if 'pack' in debug.debug_flags:
642
plain_pack_list = ['%s%s' % (a_pack.pack_transport.base, a_pack.name)
644
if revision_ids is not None:
645
rev_count = len(revision_ids)
648
mutter('%s: create_pack: creating pack from source packs: '
649
'%s%s %s revisions wanted %s t=0',
650
time.ctime(), self._upload_transport.base, new_pack.random_name,
651
plain_pack_list, rev_count)
654
revision_keys = [(revision_id,) for revision_id in revision_ids]
658
# select revision keys
659
revision_index_map = self._packs_list_to_pack_map_and_index_list(
660
packs, 'revision_index')[0]
661
revision_nodes = self._index_contents(revision_index_map, revision_keys)
662
# copy revision keys and adjust values
663
pb.update("Copying revision texts.", 1)
664
list(self._copy_nodes_graph(revision_nodes, revision_index_map,
665
new_pack._writer, new_pack.revision_index))
666
if 'pack' in debug.debug_flags:
667
mutter('%s: create_pack: revisions copied: %s%s %d items t+%6.3fs',
668
time.ctime(), self._upload_transport.base, new_pack.random_name,
669
new_pack.revision_index.key_count(),
670
time.time() - new_pack.start_time)
671
# select inventory keys
672
inv_keys = revision_keys # currently the same keyspace, and note that
673
# querying for keys here could introduce a bug where an inventory item
674
# is missed, so do not change it to query separately without cross
675
# checking like the text key check below.
676
inventory_index_map = self._packs_list_to_pack_map_and_index_list(
677
packs, 'inventory_index')[0]
678
inv_nodes = self._index_contents(inventory_index_map, inv_keys)
679
# copy inventory keys and adjust values
680
# XXX: Should be a helper function to allow different inv representation
682
pb.update("Copying inventory texts.", 2)
683
inv_lines = self._copy_nodes_graph(inv_nodes, inventory_index_map,
684
new_pack._writer, new_pack.inventory_index, output_lines=True)
686
fileid_revisions = self.repo._find_file_ids_from_xml_inventory_lines(
687
inv_lines, revision_ids)
689
for fileid, file_revids in fileid_revisions.iteritems():
691
[(fileid, file_revid) for file_revid in file_revids])
693
# eat the iterator to cause it to execute.
696
if 'pack' in debug.debug_flags:
697
mutter('%s: create_pack: inventories copied: %s%s %d items t+%6.3fs',
698
time.ctime(), self._upload_transport.base, new_pack.random_name,
699
new_pack.inventory_index.key_count(),
700
time.time() - new_pack.start_time)
702
text_index_map = self._packs_list_to_pack_map_and_index_list(
703
packs, 'text_index')[0]
704
text_nodes = self._index_contents(text_index_map, text_filter)
705
if text_filter is not None:
706
# We could return the keys copied as part of the return value from
707
# _copy_nodes_graph but this doesn't work all that well with the
708
# need to get line output too, so we check separately, and as we're
709
# going to buffer everything anyway, we check beforehand, which
710
# saves reading knit data over the wire when we know there are
712
text_nodes = set(text_nodes)
713
present_text_keys = set(_node[1] for _node in text_nodes)
714
missing_text_keys = set(text_filter) - present_text_keys
715
if missing_text_keys:
716
# TODO: raise a specific error that can handle many missing
718
a_missing_key = missing_text_keys.pop()
719
raise errors.RevisionNotPresent(a_missing_key[1],
721
# copy text keys and adjust values
722
pb.update("Copying content texts.", 3)
723
list(self._copy_nodes_graph(text_nodes, text_index_map,
724
new_pack._writer, new_pack.text_index))
725
if 'pack' in debug.debug_flags:
726
mutter('%s: create_pack: file texts copied: %s%s %d items t+%6.3fs',
727
time.ctime(), self._upload_transport.base, new_pack.random_name,
728
new_pack.text_index.key_count(),
729
time.time() - new_pack.start_time)
730
# select signature keys
731
signature_filter = revision_keys # same keyspace
732
signature_index_map = self._packs_list_to_pack_map_and_index_list(
733
packs, 'signature_index')[0]
734
signature_nodes = self._index_contents(signature_index_map,
736
# copy signature keys and adjust values
737
pb.update("Copying signature texts.", 4)
738
self._copy_nodes(signature_nodes, signature_index_map, new_pack._writer,
739
new_pack.signature_index)
740
if 'pack' in debug.debug_flags:
741
mutter('%s: create_pack: revision signatures copied: %s%s %d items t+%6.3fs',
742
time.ctime(), self._upload_transport.base, new_pack.random_name,
743
new_pack.signature_index.key_count(),
744
time.time() - new_pack.start_time)
745
if not new_pack.data_inserted():
748
pb.update("Finishing pack.", 5)
750
self.allocate(new_pack)
753
def _execute_pack_operations(self, pack_operations):
754
"""Execute a series of pack operations.
756
:param pack_operations: A list of [revision_count, packs_to_combine].
759
for revision_count, packs in pack_operations:
760
# we may have no-ops from the setup logic
763
# have a progress bar?
764
self.create_pack_from_packs(packs, '.autopack')
766
self._remove_pack_from_memory(pack)
767
# record the newly available packs and stop advertising the old
769
self._save_pack_names()
770
# Move the old packs out of the way now they are no longer referenced.
771
for revision_count, packs in pack_operations:
772
self._obsolete_packs(packs)
774
def lock_names(self):
775
"""Acquire the mutex around the pack-names index.
777
This cannot be used in the middle of a read-only transaction on the
780
self.repo.control_files.lock_write()
783
"""Pack the pack collection totally."""
785
total_packs = len(self._names)
788
total_revisions = self.revision_index.combined_index.key_count()
789
# XXX: the following may want to be a class, to pack with a given
791
mutter('Packing repository %s, which has %d pack files, '
792
'containing %d revisions into 1 packs.', self, total_packs,
794
# determine which packs need changing
795
pack_distribution = [1]
796
pack_operations = [[0, []]]
797
for pack in self.all_packs():
798
revision_count = pack.get_revision_count()
799
pack_operations[-1][0] += revision_count
800
pack_operations[-1][1].append(pack)
801
self._execute_pack_operations(pack_operations)
803
def plan_autopack_combinations(self, existing_packs, pack_distribution):
804
"""Plan a pack operation.
806
:param existing_packs: The packs to pack. (A list of (revcount, Pack)
808
:param pack_distribution: A list with the number of revisions desired
811
if len(existing_packs) <= len(pack_distribution):
813
existing_packs.sort(reverse=True)
814
pack_operations = [[0, []]]
815
# plan out what packs to keep, and what to reorganise
816
while len(existing_packs):
817
# take the largest pack, and if its less than the head of the
818
# distribution chart we will include its contents in the new pack for
819
# that position. If its larger, we remove its size from the
821
next_pack_rev_count, next_pack = existing_packs.pop(0)
822
if next_pack_rev_count >= pack_distribution[0]:
823
# this is already packed 'better' than this, so we can
824
# not waste time packing it.
825
while next_pack_rev_count > 0:
826
next_pack_rev_count -= pack_distribution[0]
827
if next_pack_rev_count >= 0:
829
del pack_distribution[0]
831
# didn't use that entire bucket up
832
pack_distribution[0] = -next_pack_rev_count
834
# add the revisions we're going to add to the next output pack
835
pack_operations[-1][0] += next_pack_rev_count
836
# allocate this pack to the next pack sub operation
837
pack_operations[-1][1].append(next_pack)
838
if pack_operations[-1][0] >= pack_distribution[0]:
839
# this pack is used up, shift left.
840
del pack_distribution[0]
841
pack_operations.append([0, []])
843
return pack_operations
845
def _copy_nodes(self, nodes, index_map, writer, write_index):
846
# plan a readv on each source pack:
848
nodes = sorted(nodes)
849
# how to map this into knit.py - or knit.py into this?
850
# we don't want the typical knit logic, we want grouping by pack
851
# at this point - perhaps a helper library for the following code
852
# duplication points?
854
for index, key, value in nodes:
855
if index not in request_groups:
856
request_groups[index] = []
857
request_groups[index].append((key, value))
858
for index, items in request_groups.iteritems():
859
pack_readv_requests = []
860
for key, value in items:
861
# ---- KnitGraphIndex.get_position
862
bits = value[1:].split(' ')
863
offset, length = int(bits[0]), int(bits[1])
864
pack_readv_requests.append((offset, length, (key, value[0])))
865
# linear scan up the pack
866
pack_readv_requests.sort()
868
transport, path = index_map[index]
869
reader = pack.make_readv_reader(transport, path,
870
[offset[0:2] for offset in pack_readv_requests])
871
for (names, read_func), (_1, _2, (key, eol_flag)) in \
872
izip(reader.iter_records(), pack_readv_requests):
873
raw_data = read_func(None)
874
pos, size = writer.add_bytes_record(raw_data, names)
875
write_index.add_node(key, eol_flag + "%d %d" % (pos, size))
877
def _copy_nodes_graph(self, nodes, index_map, writer, write_index,
879
"""Copy knit nodes between packs.
881
:param output_lines: Return lines present in the copied data as
884
pb = ui.ui_factory.nested_progress_bar()
886
return self._do_copy_nodes_graph(nodes, index_map, writer,
887
write_index, output_lines, pb)
891
def _do_copy_nodes_graph(self, nodes, index_map, writer, write_index,
893
# for record verification
894
knit_data = _KnitData(None)
895
# for line extraction when requested (inventories only)
897
factory = knit.KnitPlainFactory()
898
# plan a readv on each source pack:
900
nodes = sorted(nodes)
901
# how to map this into knit.py - or knit.py into this?
902
# we don't want the typical knit logic, we want grouping by pack
903
# at this point - perhaps a helper library for the following code
904
# duplication points?
907
pb.update("Copied record", record_index, len(nodes))
908
for index, key, value, references in nodes:
909
if index not in request_groups:
910
request_groups[index] = []
911
request_groups[index].append((key, value, references))
912
for index, items in request_groups.iteritems():
913
pack_readv_requests = []
914
for key, value, references in items:
915
# ---- KnitGraphIndex.get_position
916
bits = value[1:].split(' ')
917
offset, length = int(bits[0]), int(bits[1])
918
pack_readv_requests.append((offset, length, (key, value[0], references)))
919
# linear scan up the pack
920
pack_readv_requests.sort()
922
transport, path = index_map[index]
923
reader = pack.make_readv_reader(transport, path,
924
[offset[0:2] for offset in pack_readv_requests])
925
for (names, read_func), (_1, _2, (key, eol_flag, references)) in \
926
izip(reader.iter_records(), pack_readv_requests):
927
raw_data = read_func(None)
929
# read the entire thing
930
content, _ = knit_data._parse_record(key[-1], raw_data)
931
if len(references[-1]) == 0:
932
line_iterator = factory.get_fulltext_content(content)
934
line_iterator = factory.get_linedelta_content(content)
935
for line in line_iterator:
938
# check the header only
939
df, _ = knit_data._parse_record_header(key[-1], raw_data)
941
pos, size = writer.add_bytes_record(raw_data, names)
942
write_index.add_node(key, eol_flag + "%d %d" % (pos, size), references)
943
pb.update("Copied record", record_index)
946
def ensure_loaded(self):
947
# NB: if you see an assertion error here, its probably access against
948
# an unlocked repo. Naughty.
949
assert self.repo.is_locked()
950
if self._names is None:
952
self._packs_at_load = set()
953
for index, key, value in self._iter_disk_pack_index():
955
self._names[name] = self._parse_index_sizes(value)
956
self._packs_at_load.add((key, value))
957
# populate all the metadata.
960
def _parse_index_sizes(self, value):
961
"""Parse a string of index sizes."""
962
return tuple([int(digits) for digits in value.split(' ')])
964
def get_pack_by_name(self, name):
965
"""Get a Pack object by name.
967
:param name: The name of the pack - e.g. '123456'
968
:return: A Pack object.
971
return self._packs_by_name[name]
973
rev_index = self._make_index(name, '.rix')
974
inv_index = self._make_index(name, '.iix')
975
txt_index = self._make_index(name, '.tix')
976
sig_index = self._make_index(name, '.six')
977
result = ExistingPack(self._pack_transport, name, rev_index,
978
inv_index, txt_index, sig_index)
979
self.add_pack_to_memory(result)
982
def allocate(self, a_new_pack):
983
"""Allocate name in the list of packs.
985
:param a_new_pack: A NewPack instance to be added to the collection of
986
packs for this repository.
989
if a_new_pack.name in self._names:
990
# a collision with the packs we know about (not the only possible
991
# collision, see NewPack.finish() for some discussion). Remove our
992
# prior reference to it.
993
self._remove_pack_from_memory(a_new_pack)
994
self._names[a_new_pack.name] = tuple(a_new_pack.index_sizes)
995
self.add_pack_to_memory(a_new_pack)
997
def _iter_disk_pack_index(self):
998
"""Iterate over the contents of the pack-names index.
1000
This is used when loading the list from disk, and before writing to
1001
detect updates from others during our write operation.
1002
:return: An iterator of the index contents.
1004
return GraphIndex(self.transport, 'pack-names', None
1005
).iter_all_entries()
1007
def _make_index(self, name, suffix):
1008
size_offset = self._suffix_offsets[suffix]
1009
index_name = name + suffix
1010
index_size = self._names[name][size_offset]
1012
self._index_transport, index_name, index_size)
1014
def _max_pack_count(self, total_revisions):
1015
"""Return the maximum number of packs to use for total revisions.
1017
:param total_revisions: The total number of revisions in the
1020
if not total_revisions:
1022
digits = str(total_revisions)
1024
for digit in digits:
1025
result += int(digit)
1029
"""Provide an order to the underlying names."""
1030
return sorted(self._names.keys())
1032
def _obsolete_packs(self, packs):
1033
"""Move a number of packs which have been obsoleted out of the way.
1035
Each pack and its associated indices are moved out of the way.
1037
Note: for correctness this function should only be called after a new
1038
pack names index has been written without these pack names, and with
1039
the names of packs that contain the data previously available via these
1042
:param packs: The packs to obsolete.
1043
:param return: None.
1046
pack.pack_transport.rename(pack.file_name(),
1047
'../obsolete_packs/' + pack.file_name())
1048
# TODO: Probably needs to know all possible indices for this pack
1049
# - or maybe list the directory and move all indices matching this
1050
# name whether we recognize it or not?
1051
for suffix in ('.iix', '.six', '.tix', '.rix'):
1052
self._index_transport.rename(pack.name + suffix,
1053
'../obsolete_packs/' + pack.name + suffix)
1055
def pack_distribution(self, total_revisions):
1056
"""Generate a list of the number of revisions to put in each pack.
1058
:param total_revisions: The total number of revisions in the
1061
if total_revisions == 0:
1063
digits = reversed(str(total_revisions))
1065
for exponent, count in enumerate(digits):
1066
size = 10 ** exponent
1067
for pos in range(int(count)):
1069
return list(reversed(result))
1071
def _pack_tuple(self, name):
1072
"""Return a tuple with the transport and file name for a pack name."""
1073
return self._pack_transport, name + '.pack'
1075
def _remove_pack_from_memory(self, pack):
1076
"""Remove pack from the packs accessed by this repository.
1078
Only affects memory state, until self._save_pack_names() is invoked.
1080
self._names.pop(pack.name)
1081
self._packs_by_name.pop(pack.name)
1082
self._remove_pack_indices(pack)
1084
def _remove_pack_indices(self, pack):
1085
"""Remove the indices for pack from the aggregated indices."""
1086
self.revision_index.remove_index(pack.revision_index, pack)
1087
self.inventory_index.remove_index(pack.inventory_index, pack)
1088
self.text_index.remove_index(pack.text_index, pack)
1089
self.signature_index.remove_index(pack.signature_index, pack)
1092
"""Clear all cached data."""
1093
# cached revision data
1094
self.repo._revision_knit = None
1095
self.revision_index.clear()
1096
# cached signature data
1097
self.repo._signature_knit = None
1098
self.signature_index.clear()
1099
# cached file text data
1100
self.text_index.clear()
1101
self.repo._text_knit = None
1102
# cached inventory data
1103
self.inventory_index.clear()
1104
# remove the open pack
1105
self._new_pack = None
1106
# information about packs.
1109
self._packs_by_name = {}
1110
self._packs_at_load = None
1112
def _make_index_map(self, index_suffix):
1113
"""Return information on existing indices.
1115
:param suffix: Index suffix added to pack name.
1117
:returns: (pack_map, indices) where indices is a list of GraphIndex
1118
objects, and pack_map is a mapping from those objects to the
1119
pack tuple they describe.
1121
# TODO: stop using this; it creates new indices unnecessarily.
1122
self.ensure_loaded()
1123
suffix_map = {'.rix': 'revision_index',
1124
'.six': 'signature_index',
1125
'.iix': 'inventory_index',
1126
'.tix': 'text_index',
1128
return self._packs_list_to_pack_map_and_index_list(self.all_packs(),
1129
suffix_map[index_suffix])
1131
def _packs_list_to_pack_map_and_index_list(self, packs, index_attribute):
1132
"""Convert a list of packs to an index pack map and index list.
1134
:param packs: The packs list to process.
1135
:param index_attribute: The attribute that the desired index is found
1137
:return: A tuple (map, list) where map contains the dict from
1138
index:pack_tuple, and lsit contains the indices in the same order
1144
index = getattr(pack, index_attribute)
1145
indices.append(index)
1146
pack_map[index] = (pack.pack_transport, pack.file_name())
1147
return pack_map, indices
1149
def _index_contents(self, pack_map, key_filter=None):
1150
"""Get an iterable of the index contents from a pack_map.
1152
:param pack_map: A map from indices to pack details.
1153
:param key_filter: An optional filter to limit the
1156
indices = [index for index in pack_map.iterkeys()]
1157
all_index = CombinedGraphIndex(indices)
1158
if key_filter is None:
1159
return all_index.iter_all_entries()
1161
return all_index.iter_entries(key_filter)
1163
def _unlock_names(self):
1164
"""Release the mutex around the pack-names index."""
1165
self.repo.control_files.unlock()
1167
def _save_pack_names(self):
1168
"""Save the list of packs.
1170
This will take out the mutex around the pack names list for the
1171
duration of the method call. If concurrent updates have been made, a
1172
three-way merge between the current list and the current in memory list
1177
builder = GraphIndexBuilder()
1178
# load the disk nodes across
1180
for index, key, value in self._iter_disk_pack_index():
1181
disk_nodes.add((key, value))
1182
# do a two-way diff against our original content
1183
current_nodes = set()
1184
for name, sizes in self._names.iteritems():
1186
((name, ), ' '.join(str(size) for size in sizes)))
1187
deleted_nodes = self._packs_at_load - current_nodes
1188
new_nodes = current_nodes - self._packs_at_load
1189
disk_nodes.difference_update(deleted_nodes)
1190
disk_nodes.update(new_nodes)
1191
# TODO: handle same-name, index-size-changes here -
1192
# e.g. use the value from disk, not ours, *unless* we're the one
1194
for key, value in disk_nodes:
1195
builder.add_node(key, value)
1196
self.transport.put_file('pack-names', builder.finish())
1197
# move the baseline forward
1198
self._packs_at_load = disk_nodes
1200
self._unlock_names()
1201
# synchronise the memory packs list with what we just wrote:
1202
new_names = dict(disk_nodes)
1203
# drop no longer present nodes
1204
for pack in self.all_packs():
1205
if (pack.name,) not in new_names:
1206
self._remove_pack_from_memory(pack)
1207
# add new nodes/refresh existing ones
1208
for key, value in disk_nodes:
1210
sizes = self._parse_index_sizes(value)
1211
if name in self._names:
1213
if sizes != self._names[name]:
1214
# the pack for name has had its indices replaced - rare but
1215
# important to handle. XXX: probably can never happen today
1216
# because the three-way merge code above does not handle it
1217
# - you may end up adding the same key twice to the new
1218
# disk index because the set values are the same, unless
1219
# the only index shows up as deleted by the set difference
1220
# - which it may. Until there is a specific test for this,
1221
# assume its broken. RBC 20071017.
1222
self._remove_pack_from_memory(self.get_pack_by_name(name))
1223
self._names[name] = sizes
1224
self.get_pack_by_name(name)
1227
self._names[name] = sizes
1228
self.get_pack_by_name(name)
1230
def _start_write_group(self):
1231
# Do not permit preparation for writing if we're not in a 'write lock'.
1232
if not self.repo.is_write_locked():
1233
raise errors.NotWriteLocked(self)
1234
self._new_pack = NewPack(self._upload_transport, self._index_transport,
1235
self._pack_transport, upload_suffix='.pack')
1236
# allow writing: queue writes to a new index
1237
self.revision_index.add_writable_index(self._new_pack.revision_index,
1239
self.inventory_index.add_writable_index(self._new_pack.inventory_index,
1241
self.text_index.add_writable_index(self._new_pack.text_index,
1243
self.signature_index.add_writable_index(self._new_pack.signature_index,
1246
# reused revision and signature knits may need updating
1248
# "Hysterical raisins. client code in bzrlib grabs those knits outside
1249
# of write groups and then mutates it inside the write group."
1250
if self.repo._revision_knit is not None:
1251
self.repo._revision_knit._index._add_callback = \
1252
self.revision_index.add_callback
1253
if self.repo._signature_knit is not None:
1254
self.repo._signature_knit._index._add_callback = \
1255
self.signature_index.add_callback
1256
# create a reused knit object for text addition in commit.
1257
self.repo._text_knit = self.repo.weave_store.get_weave_or_empty(
1260
def _abort_write_group(self):
1261
# FIXME: just drop the transient index.
1262
# forget what names there are
1263
self._new_pack.abort()
1264
self._remove_pack_indices(self._new_pack)
1265
self._new_pack = None
1266
self.repo._text_knit = None
1268
def _commit_write_group(self):
1269
self._remove_pack_indices(self._new_pack)
1270
if self._new_pack.data_inserted():
1271
# get all the data to disk and read to use
1272
self._new_pack.finish()
1273
self.allocate(self._new_pack)
1274
self._new_pack = None
1275
if not self.autopack():
1276
# when autopack takes no steps, the names list is still
1278
self._save_pack_names()
1280
self._new_pack.abort()
1281
self.repo._text_knit = None
1284
class KnitPackRevisionStore(KnitRevisionStore):
1285
"""An object to adapt access from RevisionStore's to use KnitPacks.
1287
This class works by replacing the original RevisionStore.
1288
We need to do this because the KnitPackRevisionStore is less
1289
isolated in its layering - it uses services from the repo.
1292
def __init__(self, repo, transport, revisionstore):
1293
"""Create a KnitPackRevisionStore on repo with revisionstore.
1295
This will store its state in the Repository, use the
1296
indices to provide a KnitGraphIndex,
1297
and at the end of transactions write new indices.
1299
KnitRevisionStore.__init__(self, revisionstore.versioned_file_store)
1301
self._serializer = revisionstore._serializer
1302
self.transport = transport
1304
def get_revision_file(self, transaction):
1305
"""Get the revision versioned file object."""
1306
if getattr(self.repo, '_revision_knit', None) is not None:
1307
return self.repo._revision_knit
1308
self.repo._pack_collection.ensure_loaded()
1309
add_callback = self.repo._pack_collection.revision_index.add_callback
1310
# setup knit specific objects
1311
knit_index = KnitGraphIndex(
1312
self.repo._pack_collection.revision_index.combined_index,
1313
add_callback=add_callback)
1314
self.repo._revision_knit = knit.KnitVersionedFile(
1315
'revisions', self.transport.clone('..'),
1316
self.repo.control_files._file_mode,
1317
create=False, access_mode=self.repo._access_mode(),
1318
index=knit_index, delta=False, factory=knit.KnitPlainFactory(),
1319
access_method=self.repo._pack_collection.revision_index.knit_access)
1320
return self.repo._revision_knit
1322
def get_signature_file(self, transaction):
1323
"""Get the signature versioned file object."""
1324
if getattr(self.repo, '_signature_knit', None) is not None:
1325
return self.repo._signature_knit
1326
self.repo._pack_collection.ensure_loaded()
1327
add_callback = self.repo._pack_collection.signature_index.add_callback
1328
# setup knit specific objects
1329
knit_index = KnitGraphIndex(
1330
self.repo._pack_collection.signature_index.combined_index,
1331
add_callback=add_callback, parents=False)
1332
self.repo._signature_knit = knit.KnitVersionedFile(
1333
'signatures', self.transport.clone('..'),
1334
self.repo.control_files._file_mode,
1335
create=False, access_mode=self.repo._access_mode(),
1336
index=knit_index, delta=False, factory=knit.KnitPlainFactory(),
1337
access_method=self.repo._pack_collection.signature_index.knit_access)
1338
return self.repo._signature_knit
1341
class KnitPackTextStore(VersionedFileStore):
1342
"""Presents a TextStore abstraction on top of packs.
1344
This class works by replacing the original VersionedFileStore.
1345
We need to do this because the KnitPackRevisionStore is less
1346
isolated in its layering - it uses services from the repo and shares them
1347
with all the data written in a single write group.
1350
def __init__(self, repo, transport, weavestore):
1351
"""Create a KnitPackTextStore on repo with weavestore.
1353
This will store its state in the Repository, use the
1354
indices FileNames to provide a KnitGraphIndex,
1355
and at the end of transactions write new indices.
1357
# don't call base class constructor - it's not suitable.
1358
# no transient data stored in the transaction
1360
self._precious = False
1362
self.transport = transport
1363
self.weavestore = weavestore
1364
# XXX for check() which isn't updated yet
1365
self._transport = weavestore._transport
1367
def get_weave_or_empty(self, file_id, transaction):
1368
"""Get a 'Knit' backed by the .tix indices.
1370
The transaction parameter is ignored.
1372
self.repo._pack_collection.ensure_loaded()
1373
add_callback = self.repo._pack_collection.text_index.add_callback
1374
# setup knit specific objects
1375
file_id_index = GraphIndexPrefixAdapter(
1376
self.repo._pack_collection.text_index.combined_index,
1377
(file_id, ), 1, add_nodes_callback=add_callback)
1378
knit_index = KnitGraphIndex(file_id_index,
1379
add_callback=file_id_index.add_nodes,
1380
deltas=True, parents=True)
1381
return knit.KnitVersionedFile('text:' + file_id,
1382
self.transport.clone('..'),
1385
access_method=self.repo._pack_collection.text_index.knit_access,
1386
factory=knit.KnitPlainFactory())
1388
get_weave = get_weave_or_empty
1391
"""Generate a list of the fileids inserted, for use by check."""
1392
self.repo._pack_collection.ensure_loaded()
1394
for index, key, value, refs in \
1395
self.repo._pack_collection.text_index.combined_index.iter_all_entries():
1400
class InventoryKnitThunk(object):
1401
"""An object to manage thunking get_inventory_weave to pack based knits."""
1403
def __init__(self, repo, transport):
1404
"""Create an InventoryKnitThunk for repo at transport.
1406
This will store its state in the Repository, use the
1407
indices FileNames to provide a KnitGraphIndex,
1408
and at the end of transactions write a new index..
1411
self.transport = transport
1413
def get_weave(self):
1414
"""Get a 'Knit' that contains inventory data."""
1415
self.repo._pack_collection.ensure_loaded()
1416
add_callback = self.repo._pack_collection.inventory_index.add_callback
1417
# setup knit specific objects
1418
knit_index = KnitGraphIndex(
1419
self.repo._pack_collection.inventory_index.combined_index,
1420
add_callback=add_callback, deltas=True, parents=True)
1421
return knit.KnitVersionedFile(
1422
'inventory', self.transport.clone('..'),
1423
self.repo.control_files._file_mode,
1424
create=False, access_mode=self.repo._access_mode(),
1425
index=knit_index, delta=True, factory=knit.KnitPlainFactory(),
1426
access_method=self.repo._pack_collection.inventory_index.knit_access)
1429
class KnitPackRepository(KnitRepository):
1430
"""Experimental graph-knit using repository."""
1432
def __init__(self, _format, a_bzrdir, control_files, _revision_store,
1433
control_store, text_store, _commit_builder_class, _serializer):
1434
KnitRepository.__init__(self, _format, a_bzrdir, control_files,
1435
_revision_store, control_store, text_store, _commit_builder_class,
1437
index_transport = control_files._transport.clone('indices')
1438
self._pack_collection = RepositoryPackCollection(self, control_files._transport,
1440
control_files._transport.clone('upload'),
1441
control_files._transport.clone('packs'))
1442
self._revision_store = KnitPackRevisionStore(self, index_transport, self._revision_store)
1443
self.weave_store = KnitPackTextStore(self, index_transport, self.weave_store)
1444
self._inv_thunk = InventoryKnitThunk(self, index_transport)
1445
# True when the repository object is 'write locked' (as opposed to the
1446
# physical lock only taken out around changes to the pack-names list.)
1447
# Another way to represent this would be a decorator around the control
1448
# files object that presents logical locks as physical ones - if this
1449
# gets ugly consider that alternative design. RBC 20071011
1450
self._write_lock_count = 0
1451
self._transaction = None
1453
self._reconcile_does_inventory_gc = False
1454
self._reconcile_fixes_text_parents = False
1456
def _abort_write_group(self):
1457
self._pack_collection._abort_write_group()
1459
def _access_mode(self):
1460
"""Return 'w' or 'r' for depending on whether a write lock is active.
1462
This method is a helper for the Knit-thunking support objects.
1464
if self.is_write_locked():
1468
def get_parents(self, revision_ids):
1469
"""See StackedParentsProvider.get_parents.
1471
This implementation accesses the combined revision index to provide
1474
self._pack_collection.ensure_loaded()
1475
index = self._pack_collection.revision_index.combined_index
1477
for revision_id in revision_ids:
1478
if revision_id != _mod_revision.NULL_REVISION:
1479
search_keys.add((revision_id,))
1480
found_parents = {_mod_revision.NULL_REVISION:[]}
1481
for index, key, value, refs in index.iter_entries(search_keys):
1484
parents = (_mod_revision.NULL_REVISION,)
1486
parents = tuple(parent[0] for parent in parents)
1487
found_parents[key[0]] = parents
1489
for revision_id in revision_ids:
1491
result.append(found_parents[revision_id])
1496
def _make_parents_provider(self):
1499
def _refresh_data(self):
1500
if self._write_lock_count == 1 or self.control_files._lock_count == 1:
1501
# forget what names there are
1502
self._pack_collection.reset()
1503
# XXX: Better to do an in-memory merge when acquiring a new lock -
1504
# factor out code from _save_pack_names.
1506
def _start_write_group(self):
1507
self._pack_collection._start_write_group()
1509
def _commit_write_group(self):
1510
return self._pack_collection._commit_write_group()
1512
def get_inventory_weave(self):
1513
return self._inv_thunk.get_weave()
1515
def get_transaction(self):
1516
if self._write_lock_count:
1517
return self._transaction
1519
return self.control_files.get_transaction()
1521
def is_locked(self):
1522
return self._write_lock_count or self.control_files.is_locked()
1524
def is_write_locked(self):
1525
return self._write_lock_count
1527
def lock_write(self, token=None):
1528
if not self._write_lock_count and self.is_locked():
1529
raise errors.ReadOnlyError(self)
1530
self._write_lock_count += 1
1531
if self._write_lock_count == 1:
1532
from bzrlib import transactions
1533
self._transaction = transactions.WriteTransaction()
1534
self._refresh_data()
1536
def lock_read(self):
1537
if self._write_lock_count:
1538
self._write_lock_count += 1
1540
self.control_files.lock_read()
1541
self._refresh_data()
1543
def leave_lock_in_place(self):
1544
# not supported - raise an error
1545
raise NotImplementedError(self.leave_lock_in_place)
1547
def dont_leave_lock_in_place(self):
1548
# not supported - raise an error
1549
raise NotImplementedError(self.dont_leave_lock_in_place)
1553
"""Compress the data within the repository.
1555
This will pack all the data to a single pack. In future it may
1556
recompress deltas or do other such expensive operations.
1558
self._pack_collection.pack()
1561
def reconcile(self, other=None, thorough=False):
1562
"""Reconcile this repository."""
1563
from bzrlib.reconcile import PackReconciler
1564
reconciler = PackReconciler(self, thorough=thorough)
1565
reconciler.reconcile()
1569
if self._write_lock_count == 1 and self._write_group is not None:
1570
self.abort_write_group()
1571
self._transaction = None
1572
self._write_lock_count = 0
1573
raise errors.BzrError(
1574
'Must end write group before releasing write lock on %s'
1576
if self._write_lock_count:
1577
self._write_lock_count -= 1
1578
if not self._write_lock_count:
1579
transaction = self._transaction
1580
self._transaction = None
1581
transaction.finish()
1583
self.control_files.unlock()
1586
class RepositoryFormatPack(MetaDirRepositoryFormat):
1587
"""Format logic for pack structured repositories.
1589
This repository format has:
1590
- a list of packs in pack-names
1591
- packs in packs/NAME.pack
1592
- indices in indices/NAME.{iix,six,tix,rix}
1593
- knit deltas in the packs, knit indices mapped to the indices.
1594
- thunk objects to support the knits programming API.
1595
- a format marker of its own
1596
- an optional 'shared-storage' flag
1597
- an optional 'no-working-trees' flag
1601
# Set this attribute in derived classes to control the repository class
1602
# created by open and initialize.
1603
repository_class = None
1604
# Set this attribute in derived classes to control the
1605
# _commit_builder_class that the repository objects will have passed to
1606
# their constructor.
1607
_commit_builder_class = None
1608
# Set this attribute in derived clases to control the _serializer that the
1609
# repository objects will have passed to their constructor.
1612
def _get_control_store(self, repo_transport, control_files):
1613
"""Return the control store for this repository."""
1614
return VersionedFileStore(
1617
file_mode=control_files._file_mode,
1618
versionedfile_class=knit.KnitVersionedFile,
1619
versionedfile_kwargs={'factory': knit.KnitPlainFactory()},
1622
def _get_revision_store(self, repo_transport, control_files):
1623
"""See RepositoryFormat._get_revision_store()."""
1624
versioned_file_store = VersionedFileStore(
1626
file_mode=control_files._file_mode,
1629
versionedfile_class=knit.KnitVersionedFile,
1630
versionedfile_kwargs={'delta': False,
1631
'factory': knit.KnitPlainFactory(),
1635
return KnitRevisionStore(versioned_file_store)
1637
def _get_text_store(self, transport, control_files):
1638
"""See RepositoryFormat._get_text_store()."""
1639
return self._get_versioned_file_store('knits',
1642
versionedfile_class=knit.KnitVersionedFile,
1643
versionedfile_kwargs={
1644
'create_parent_dir': True,
1645
'delay_create': True,
1646
'dir_mode': control_files._dir_mode,
1650
def initialize(self, a_bzrdir, shared=False):
1651
"""Create a pack based repository.
1653
:param a_bzrdir: bzrdir to contain the new repository; must already
1655
:param shared: If true the repository will be initialized as a shared
1658
mutter('creating repository in %s.', a_bzrdir.transport.base)
1659
dirs = ['indices', 'obsolete_packs', 'packs', 'upload']
1660
builder = GraphIndexBuilder()
1661
files = [('pack-names', builder.finish())]
1662
utf8_files = [('format', self.get_format_string())]
1664
self._upload_blank_content(a_bzrdir, dirs, files, utf8_files, shared)
1665
return self.open(a_bzrdir=a_bzrdir, _found=True)
1667
def open(self, a_bzrdir, _found=False, _override_transport=None):
1668
"""See RepositoryFormat.open().
1670
:param _override_transport: INTERNAL USE ONLY. Allows opening the
1671
repository at a slightly different url
1672
than normal. I.e. during 'upgrade'.
1675
format = RepositoryFormat.find_format(a_bzrdir)
1676
assert format.__class__ == self.__class__
1677
if _override_transport is not None:
1678
repo_transport = _override_transport
1680
repo_transport = a_bzrdir.get_repository_transport(None)
1681
control_files = lockable_files.LockableFiles(repo_transport,
1682
'lock', lockdir.LockDir)
1683
text_store = self._get_text_store(repo_transport, control_files)
1684
control_store = self._get_control_store(repo_transport, control_files)
1685
_revision_store = self._get_revision_store(repo_transport, control_files)
1686
return self.repository_class(_format=self,
1688
control_files=control_files,
1689
_revision_store=_revision_store,
1690
control_store=control_store,
1691
text_store=text_store,
1692
_commit_builder_class=self._commit_builder_class,
1693
_serializer=self._serializer)
1696
class RepositoryFormatKnitPack1(RepositoryFormatPack):
1697
"""A no-subtrees parameterised Pack repository.
1699
This format was introduced in 0.92.
1702
repository_class = KnitPackRepository
1703
_commit_builder_class = PackCommitBuilder
1704
_serializer = xml5.serializer_v5
1706
def _get_matching_bzrdir(self):
1707
return bzrdir.format_registry.make_bzrdir('knitpack-experimental')
1709
def _ignore_setting_bzrdir(self, format):
1712
_matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
1714
def get_format_string(self):
1715
"""See RepositoryFormat.get_format_string()."""
1716
return "Bazaar pack repository format 1 (needs bzr 0.92)\n"
1718
def get_format_description(self):
1719
"""See RepositoryFormat.get_format_description()."""
1720
return "Packs containing knits without subtree support"
1722
def check_conversion_target(self, target_format):
1726
class RepositoryFormatKnitPack3(RepositoryFormatPack):
1727
"""A subtrees parameterised Pack repository.
1729
This repository format uses the xml7 serializer to get:
1730
- support for recording full info about the tree root
1731
- support for recording tree-references
1733
This format was introduced in 0.92.
1736
repository_class = KnitPackRepository
1737
_commit_builder_class = PackRootCommitBuilder
1738
rich_root_data = True
1739
supports_tree_reference = True
1740
_serializer = xml7.serializer_v7
1742
def _get_matching_bzrdir(self):
1743
return bzrdir.format_registry.make_bzrdir(
1744
'knitpack-subtree-experimental')
1746
def _ignore_setting_bzrdir(self, format):
1749
_matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
1751
def check_conversion_target(self, target_format):
1752
if not target_format.rich_root_data:
1753
raise errors.BadConversionTarget(
1754
'Does not support rich root data.', target_format)
1755
if not getattr(target_format, 'supports_tree_reference', False):
1756
raise errors.BadConversionTarget(
1757
'Does not support nested trees', target_format)
1759
def get_format_string(self):
1760
"""See RepositoryFormat.get_format_string()."""
1761
return "Bazaar pack repository format 1 with subtree support (needs bzr 0.92)\n"
1763
def get_format_description(self):
1764
"""See RepositoryFormat.get_format_description()."""
1765
return "Packs containing knits with subtree support\n"