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
new_pack = NewPack(self._upload_transport, self._index_transport,
636
self._pack_transport, upload_suffix=suffix)
637
# buffer data - we won't be reading-back during the pack creation and
638
# this makes a significant difference on sftp pushes.
639
new_pack.set_write_cache_size(1024*1024)
640
if 'pack' in debug.debug_flags:
641
plain_pack_list = ['%s%s' % (a_pack.pack_transport.base, a_pack.name)
643
if revision_ids is not None:
644
rev_count = len(revision_ids)
647
mutter('%s: create_pack: creating pack from source packs: '
648
'%s%s %s revisions wanted %s t=0',
649
time.ctime(), self._upload_transport.base, new_pack.random_name,
650
plain_pack_list, rev_count)
653
revision_keys = [(revision_id,) for revision_id in revision_ids]
657
# select revision keys
658
revision_index_map = self._packs_list_to_pack_map_and_index_list(
659
packs, 'revision_index')[0]
660
revision_nodes = self._index_contents(revision_index_map, revision_keys)
661
# copy revision keys and adjust values
662
pb.update("Copying revision texts", 1)
663
list(self._copy_nodes_graph(revision_nodes, revision_index_map,
664
new_pack._writer, new_pack.revision_index))
665
if 'pack' in debug.debug_flags:
666
mutter('%s: create_pack: revisions copied: %s%s %d items t+%6.3fs',
667
time.ctime(), self._upload_transport.base, new_pack.random_name,
668
new_pack.revision_index.key_count(),
669
time.time() - new_pack.start_time)
670
# select inventory keys
671
inv_keys = revision_keys # currently the same keyspace, and note that
672
# querying for keys here could introduce a bug where an inventory item
673
# is missed, so do not change it to query separately without cross
674
# checking like the text key check below.
675
inventory_index_map = self._packs_list_to_pack_map_and_index_list(
676
packs, 'inventory_index')[0]
677
inv_nodes = self._index_contents(inventory_index_map, inv_keys)
678
# copy inventory keys and adjust values
679
# XXX: Should be a helper function to allow different inv representation
681
pb.update("Copying inventory texts", 2)
682
inv_lines = self._copy_nodes_graph(inv_nodes, inventory_index_map,
683
new_pack._writer, new_pack.inventory_index, output_lines=True)
685
fileid_revisions = self.repo._find_file_ids_from_xml_inventory_lines(
686
inv_lines, revision_ids)
688
for fileid, file_revids in fileid_revisions.iteritems():
690
[(fileid, file_revid) for file_revid in file_revids])
692
# eat the iterator to cause it to execute.
695
if 'pack' in debug.debug_flags:
696
mutter('%s: create_pack: inventories copied: %s%s %d items t+%6.3fs',
697
time.ctime(), self._upload_transport.base, new_pack.random_name,
698
new_pack.inventory_index.key_count(),
699
time.time() - new_pack.start_time)
701
text_index_map = self._packs_list_to_pack_map_and_index_list(
702
packs, 'text_index')[0]
703
text_nodes = self._index_contents(text_index_map, text_filter)
704
if text_filter is not None:
705
# We could return the keys copied as part of the return value from
706
# _copy_nodes_graph but this doesn't work all that well with the
707
# need to get line output too, so we check separately, and as we're
708
# going to buffer everything anyway, we check beforehand, which
709
# saves reading knit data over the wire when we know there are
711
text_nodes = set(text_nodes)
712
present_text_keys = set(_node[1] for _node in text_nodes)
713
missing_text_keys = set(text_filter) - present_text_keys
714
if missing_text_keys:
715
# TODO: raise a specific error that can handle many missing
717
a_missing_key = missing_text_keys.pop()
718
raise errors.RevisionNotPresent(a_missing_key[1],
720
# copy text keys and adjust values
721
pb.update("Copying content texts", 3)
722
list(self._copy_nodes_graph(text_nodes, text_index_map,
723
new_pack._writer, new_pack.text_index))
724
if 'pack' in debug.debug_flags:
725
mutter('%s: create_pack: file texts copied: %s%s %d items t+%6.3fs',
726
time.ctime(), self._upload_transport.base, new_pack.random_name,
727
new_pack.text_index.key_count(),
728
time.time() - new_pack.start_time)
729
# select signature keys
730
signature_filter = revision_keys # same keyspace
731
signature_index_map = self._packs_list_to_pack_map_and_index_list(
732
packs, 'signature_index')[0]
733
signature_nodes = self._index_contents(signature_index_map,
735
# copy signature keys and adjust values
736
pb.update("Copying signature texts", 4)
737
self._copy_nodes(signature_nodes, signature_index_map, new_pack._writer,
738
new_pack.signature_index)
739
if 'pack' in debug.debug_flags:
740
mutter('%s: create_pack: revision signatures copied: %s%s %d items t+%6.3fs',
741
time.ctime(), self._upload_transport.base, new_pack.random_name,
742
new_pack.signature_index.key_count(),
743
time.time() - new_pack.start_time)
744
if not new_pack.data_inserted():
747
pb.update("Finishing pack", 5)
749
self.allocate(new_pack)
752
def _execute_pack_operations(self, pack_operations):
753
"""Execute a series of pack operations.
755
:param pack_operations: A list of [revision_count, packs_to_combine].
758
for revision_count, packs in pack_operations:
759
# we may have no-ops from the setup logic
762
# have a progress bar?
763
self.create_pack_from_packs(packs, '.autopack')
765
self._remove_pack_from_memory(pack)
766
# record the newly available packs and stop advertising the old
768
self._save_pack_names()
769
# Move the old packs out of the way now they are no longer referenced.
770
for revision_count, packs in pack_operations:
771
self._obsolete_packs(packs)
773
def lock_names(self):
774
"""Acquire the mutex around the pack-names index.
776
This cannot be used in the middle of a read-only transaction on the
779
self.repo.control_files.lock_write()
782
"""Pack the pack collection totally."""
784
total_packs = len(self._names)
787
total_revisions = self.revision_index.combined_index.key_count()
788
# XXX: the following may want to be a class, to pack with a given
790
mutter('Packing repository %s, which has %d pack files, '
791
'containing %d revisions into 1 packs.', self, total_packs,
793
# determine which packs need changing
794
pack_distribution = [1]
795
pack_operations = [[0, []]]
796
for pack in self.all_packs():
797
revision_count = pack.get_revision_count()
798
pack_operations[-1][0] += revision_count
799
pack_operations[-1][1].append(pack)
800
self._execute_pack_operations(pack_operations)
802
def plan_autopack_combinations(self, existing_packs, pack_distribution):
803
"""Plan a pack operation.
805
:param existing_packs: The packs to pack. (A list of (revcount, Pack)
807
:param pack_distribution: A list with the number of revisions desired
810
if len(existing_packs) <= len(pack_distribution):
812
existing_packs.sort(reverse=True)
813
pack_operations = [[0, []]]
814
# plan out what packs to keep, and what to reorganise
815
while len(existing_packs):
816
# take the largest pack, and if its less than the head of the
817
# distribution chart we will include its contents in the new pack for
818
# that position. If its larger, we remove its size from the
820
next_pack_rev_count, next_pack = existing_packs.pop(0)
821
if next_pack_rev_count >= pack_distribution[0]:
822
# this is already packed 'better' than this, so we can
823
# not waste time packing it.
824
while next_pack_rev_count > 0:
825
next_pack_rev_count -= pack_distribution[0]
826
if next_pack_rev_count >= 0:
828
del pack_distribution[0]
830
# didn't use that entire bucket up
831
pack_distribution[0] = -next_pack_rev_count
833
# add the revisions we're going to add to the next output pack
834
pack_operations[-1][0] += next_pack_rev_count
835
# allocate this pack to the next pack sub operation
836
pack_operations[-1][1].append(next_pack)
837
if pack_operations[-1][0] >= pack_distribution[0]:
838
# this pack is used up, shift left.
839
del pack_distribution[0]
840
pack_operations.append([0, []])
842
return pack_operations
844
def _copy_nodes(self, nodes, index_map, writer, write_index):
845
"""Copy knit nodes between packs with no graph references."""
846
pb = ui.ui_factory.nested_progress_bar()
848
return self._do_copy_nodes(nodes, index_map, writer,
853
def _do_copy_nodes(self, nodes, index_map, writer, write_index, pb):
854
# for record verification
855
knit_data = _KnitData(None)
856
# plan a readv on each source pack:
858
nodes = sorted(nodes)
859
# how to map this into knit.py - or knit.py into this?
860
# we don't want the typical knit logic, we want grouping by pack
861
# at this point - perhaps a helper library for the following code
862
# duplication points?
864
for index, key, value in nodes:
865
if index not in request_groups:
866
request_groups[index] = []
867
request_groups[index].append((key, value))
869
pb.update("Copied record", record_index, len(nodes))
870
for index, items in request_groups.iteritems():
871
pack_readv_requests = []
872
for key, value in items:
873
# ---- KnitGraphIndex.get_position
874
bits = value[1:].split(' ')
875
offset, length = int(bits[0]), int(bits[1])
876
pack_readv_requests.append((offset, length, (key, value[0])))
877
# linear scan up the pack
878
pack_readv_requests.sort()
880
transport, path = index_map[index]
881
reader = pack.make_readv_reader(transport, path,
882
[offset[0:2] for offset in pack_readv_requests])
883
for (names, read_func), (_1, _2, (key, eol_flag)) in \
884
izip(reader.iter_records(), pack_readv_requests):
885
raw_data = read_func(None)
886
# check the header only
887
df, _ = knit_data._parse_record_header(key[-1], raw_data)
889
pos, size = writer.add_bytes_record(raw_data, names)
890
write_index.add_node(key, eol_flag + "%d %d" % (pos, size))
891
pb.update("Copied record", record_index)
894
def _copy_nodes_graph(self, nodes, index_map, writer, write_index,
896
"""Copy knit nodes between packs.
898
:param output_lines: Return lines present in the copied data as
901
pb = ui.ui_factory.nested_progress_bar()
903
return self._do_copy_nodes_graph(nodes, index_map, writer,
904
write_index, output_lines, pb)
908
def _do_copy_nodes_graph(self, nodes, index_map, writer, write_index,
910
# for record verification
911
knit_data = _KnitData(None)
912
# for line extraction when requested (inventories only)
914
factory = knit.KnitPlainFactory()
915
# plan a readv on each source pack:
917
nodes = sorted(nodes)
918
# how to map this into knit.py - or knit.py into this?
919
# we don't want the typical knit logic, we want grouping by pack
920
# at this point - perhaps a helper library for the following code
921
# duplication points?
924
pb.update("Copied record", record_index, len(nodes))
925
for index, key, value, references in nodes:
926
if index not in request_groups:
927
request_groups[index] = []
928
request_groups[index].append((key, value, references))
929
for index, items in request_groups.iteritems():
930
pack_readv_requests = []
931
for key, value, references in items:
932
# ---- KnitGraphIndex.get_position
933
bits = value[1:].split(' ')
934
offset, length = int(bits[0]), int(bits[1])
935
pack_readv_requests.append((offset, length, (key, value[0], references)))
936
# linear scan up the pack
937
pack_readv_requests.sort()
939
transport, path = index_map[index]
940
reader = pack.make_readv_reader(transport, path,
941
[offset[0:2] for offset in pack_readv_requests])
942
for (names, read_func), (_1, _2, (key, eol_flag, references)) in \
943
izip(reader.iter_records(), pack_readv_requests):
944
raw_data = read_func(None)
946
# read the entire thing
947
content, _ = knit_data._parse_record(key[-1], raw_data)
948
if len(references[-1]) == 0:
949
line_iterator = factory.get_fulltext_content(content)
951
line_iterator = factory.get_linedelta_content(content)
952
for line in line_iterator:
955
# check the header only
956
df, _ = knit_data._parse_record_header(key[-1], raw_data)
958
pos, size = writer.add_bytes_record(raw_data, names)
959
write_index.add_node(key, eol_flag + "%d %d" % (pos, size), references)
960
pb.update("Copied record", record_index)
963
def ensure_loaded(self):
964
# NB: if you see an assertion error here, its probably access against
965
# an unlocked repo. Naughty.
966
assert self.repo.is_locked()
967
if self._names is None:
969
self._packs_at_load = set()
970
for index, key, value in self._iter_disk_pack_index():
972
self._names[name] = self._parse_index_sizes(value)
973
self._packs_at_load.add((key, value))
974
# populate all the metadata.
977
def _parse_index_sizes(self, value):
978
"""Parse a string of index sizes."""
979
return tuple([int(digits) for digits in value.split(' ')])
981
def get_pack_by_name(self, name):
982
"""Get a Pack object by name.
984
:param name: The name of the pack - e.g. '123456'
985
:return: A Pack object.
988
return self._packs_by_name[name]
990
rev_index = self._make_index(name, '.rix')
991
inv_index = self._make_index(name, '.iix')
992
txt_index = self._make_index(name, '.tix')
993
sig_index = self._make_index(name, '.six')
994
result = ExistingPack(self._pack_transport, name, rev_index,
995
inv_index, txt_index, sig_index)
996
self.add_pack_to_memory(result)
999
def allocate(self, a_new_pack):
1000
"""Allocate name in the list of packs.
1002
:param a_new_pack: A NewPack instance to be added to the collection of
1003
packs for this repository.
1005
self.ensure_loaded()
1006
if a_new_pack.name in self._names:
1007
# a collision with the packs we know about (not the only possible
1008
# collision, see NewPack.finish() for some discussion). Remove our
1009
# prior reference to it.
1010
self._remove_pack_from_memory(a_new_pack)
1011
self._names[a_new_pack.name] = tuple(a_new_pack.index_sizes)
1012
self.add_pack_to_memory(a_new_pack)
1014
def _iter_disk_pack_index(self):
1015
"""Iterate over the contents of the pack-names index.
1017
This is used when loading the list from disk, and before writing to
1018
detect updates from others during our write operation.
1019
:return: An iterator of the index contents.
1021
return GraphIndex(self.transport, 'pack-names', None
1022
).iter_all_entries()
1024
def _make_index(self, name, suffix):
1025
size_offset = self._suffix_offsets[suffix]
1026
index_name = name + suffix
1027
index_size = self._names[name][size_offset]
1029
self._index_transport, index_name, index_size)
1031
def _max_pack_count(self, total_revisions):
1032
"""Return the maximum number of packs to use for total revisions.
1034
:param total_revisions: The total number of revisions in the
1037
if not total_revisions:
1039
digits = str(total_revisions)
1041
for digit in digits:
1042
result += int(digit)
1046
"""Provide an order to the underlying names."""
1047
return sorted(self._names.keys())
1049
def _obsolete_packs(self, packs):
1050
"""Move a number of packs which have been obsoleted out of the way.
1052
Each pack and its associated indices are moved out of the way.
1054
Note: for correctness this function should only be called after a new
1055
pack names index has been written without these pack names, and with
1056
the names of packs that contain the data previously available via these
1059
:param packs: The packs to obsolete.
1060
:param return: None.
1063
pack.pack_transport.rename(pack.file_name(),
1064
'../obsolete_packs/' + pack.file_name())
1065
# TODO: Probably needs to know all possible indices for this pack
1066
# - or maybe list the directory and move all indices matching this
1067
# name whether we recognize it or not?
1068
for suffix in ('.iix', '.six', '.tix', '.rix'):
1069
self._index_transport.rename(pack.name + suffix,
1070
'../obsolete_packs/' + pack.name + suffix)
1072
def pack_distribution(self, total_revisions):
1073
"""Generate a list of the number of revisions to put in each pack.
1075
:param total_revisions: The total number of revisions in the
1078
if total_revisions == 0:
1080
digits = reversed(str(total_revisions))
1082
for exponent, count in enumerate(digits):
1083
size = 10 ** exponent
1084
for pos in range(int(count)):
1086
return list(reversed(result))
1088
def _pack_tuple(self, name):
1089
"""Return a tuple with the transport and file name for a pack name."""
1090
return self._pack_transport, name + '.pack'
1092
def _remove_pack_from_memory(self, pack):
1093
"""Remove pack from the packs accessed by this repository.
1095
Only affects memory state, until self._save_pack_names() is invoked.
1097
self._names.pop(pack.name)
1098
self._packs_by_name.pop(pack.name)
1099
self._remove_pack_indices(pack)
1101
def _remove_pack_indices(self, pack):
1102
"""Remove the indices for pack from the aggregated indices."""
1103
self.revision_index.remove_index(pack.revision_index, pack)
1104
self.inventory_index.remove_index(pack.inventory_index, pack)
1105
self.text_index.remove_index(pack.text_index, pack)
1106
self.signature_index.remove_index(pack.signature_index, pack)
1109
"""Clear all cached data."""
1110
# cached revision data
1111
self.repo._revision_knit = None
1112
self.revision_index.clear()
1113
# cached signature data
1114
self.repo._signature_knit = None
1115
self.signature_index.clear()
1116
# cached file text data
1117
self.text_index.clear()
1118
self.repo._text_knit = None
1119
# cached inventory data
1120
self.inventory_index.clear()
1121
# remove the open pack
1122
self._new_pack = None
1123
# information about packs.
1126
self._packs_by_name = {}
1127
self._packs_at_load = None
1129
def _make_index_map(self, index_suffix):
1130
"""Return information on existing indices.
1132
:param suffix: Index suffix added to pack name.
1134
:returns: (pack_map, indices) where indices is a list of GraphIndex
1135
objects, and pack_map is a mapping from those objects to the
1136
pack tuple they describe.
1138
# TODO: stop using this; it creates new indices unnecessarily.
1139
self.ensure_loaded()
1140
suffix_map = {'.rix': 'revision_index',
1141
'.six': 'signature_index',
1142
'.iix': 'inventory_index',
1143
'.tix': 'text_index',
1145
return self._packs_list_to_pack_map_and_index_list(self.all_packs(),
1146
suffix_map[index_suffix])
1148
def _packs_list_to_pack_map_and_index_list(self, packs, index_attribute):
1149
"""Convert a list of packs to an index pack map and index list.
1151
:param packs: The packs list to process.
1152
:param index_attribute: The attribute that the desired index is found
1154
:return: A tuple (map, list) where map contains the dict from
1155
index:pack_tuple, and lsit contains the indices in the same order
1161
index = getattr(pack, index_attribute)
1162
indices.append(index)
1163
pack_map[index] = (pack.pack_transport, pack.file_name())
1164
return pack_map, indices
1166
def _index_contents(self, pack_map, key_filter=None):
1167
"""Get an iterable of the index contents from a pack_map.
1169
:param pack_map: A map from indices to pack details.
1170
:param key_filter: An optional filter to limit the
1173
indices = [index for index in pack_map.iterkeys()]
1174
all_index = CombinedGraphIndex(indices)
1175
if key_filter is None:
1176
return all_index.iter_all_entries()
1178
return all_index.iter_entries(key_filter)
1180
def _unlock_names(self):
1181
"""Release the mutex around the pack-names index."""
1182
self.repo.control_files.unlock()
1184
def _save_pack_names(self):
1185
"""Save the list of packs.
1187
This will take out the mutex around the pack names list for the
1188
duration of the method call. If concurrent updates have been made, a
1189
three-way merge between the current list and the current in memory list
1194
builder = GraphIndexBuilder()
1195
# load the disk nodes across
1197
for index, key, value in self._iter_disk_pack_index():
1198
disk_nodes.add((key, value))
1199
# do a two-way diff against our original content
1200
current_nodes = set()
1201
for name, sizes in self._names.iteritems():
1203
((name, ), ' '.join(str(size) for size in sizes)))
1204
deleted_nodes = self._packs_at_load - current_nodes
1205
new_nodes = current_nodes - self._packs_at_load
1206
disk_nodes.difference_update(deleted_nodes)
1207
disk_nodes.update(new_nodes)
1208
# TODO: handle same-name, index-size-changes here -
1209
# e.g. use the value from disk, not ours, *unless* we're the one
1211
for key, value in disk_nodes:
1212
builder.add_node(key, value)
1213
self.transport.put_file('pack-names', builder.finish())
1214
# move the baseline forward
1215
self._packs_at_load = disk_nodes
1217
self._unlock_names()
1218
# synchronise the memory packs list with what we just wrote:
1219
new_names = dict(disk_nodes)
1220
# drop no longer present nodes
1221
for pack in self.all_packs():
1222
if (pack.name,) not in new_names:
1223
self._remove_pack_from_memory(pack)
1224
# add new nodes/refresh existing ones
1225
for key, value in disk_nodes:
1227
sizes = self._parse_index_sizes(value)
1228
if name in self._names:
1230
if sizes != self._names[name]:
1231
# the pack for name has had its indices replaced - rare but
1232
# important to handle. XXX: probably can never happen today
1233
# because the three-way merge code above does not handle it
1234
# - you may end up adding the same key twice to the new
1235
# disk index because the set values are the same, unless
1236
# the only index shows up as deleted by the set difference
1237
# - which it may. Until there is a specific test for this,
1238
# assume its broken. RBC 20071017.
1239
self._remove_pack_from_memory(self.get_pack_by_name(name))
1240
self._names[name] = sizes
1241
self.get_pack_by_name(name)
1244
self._names[name] = sizes
1245
self.get_pack_by_name(name)
1247
def _start_write_group(self):
1248
# Do not permit preparation for writing if we're not in a 'write lock'.
1249
if not self.repo.is_write_locked():
1250
raise errors.NotWriteLocked(self)
1251
self._new_pack = NewPack(self._upload_transport, self._index_transport,
1252
self._pack_transport, upload_suffix='.pack')
1253
# allow writing: queue writes to a new index
1254
self.revision_index.add_writable_index(self._new_pack.revision_index,
1256
self.inventory_index.add_writable_index(self._new_pack.inventory_index,
1258
self.text_index.add_writable_index(self._new_pack.text_index,
1260
self.signature_index.add_writable_index(self._new_pack.signature_index,
1263
# reused revision and signature knits may need updating
1265
# "Hysterical raisins. client code in bzrlib grabs those knits outside
1266
# of write groups and then mutates it inside the write group."
1267
if self.repo._revision_knit is not None:
1268
self.repo._revision_knit._index._add_callback = \
1269
self.revision_index.add_callback
1270
if self.repo._signature_knit is not None:
1271
self.repo._signature_knit._index._add_callback = \
1272
self.signature_index.add_callback
1273
# create a reused knit object for text addition in commit.
1274
self.repo._text_knit = self.repo.weave_store.get_weave_or_empty(
1277
def _abort_write_group(self):
1278
# FIXME: just drop the transient index.
1279
# forget what names there are
1280
self._new_pack.abort()
1281
self._remove_pack_indices(self._new_pack)
1282
self._new_pack = None
1283
self.repo._text_knit = None
1285
def _commit_write_group(self):
1286
self._remove_pack_indices(self._new_pack)
1287
if self._new_pack.data_inserted():
1288
# get all the data to disk and read to use
1289
self._new_pack.finish()
1290
self.allocate(self._new_pack)
1291
self._new_pack = None
1292
if not self.autopack():
1293
# when autopack takes no steps, the names list is still
1295
self._save_pack_names()
1297
self._new_pack.abort()
1298
self.repo._text_knit = None
1301
class KnitPackRevisionStore(KnitRevisionStore):
1302
"""An object to adapt access from RevisionStore's to use KnitPacks.
1304
This class works by replacing the original RevisionStore.
1305
We need to do this because the KnitPackRevisionStore is less
1306
isolated in its layering - it uses services from the repo.
1309
def __init__(self, repo, transport, revisionstore):
1310
"""Create a KnitPackRevisionStore on repo with revisionstore.
1312
This will store its state in the Repository, use the
1313
indices to provide a KnitGraphIndex,
1314
and at the end of transactions write new indices.
1316
KnitRevisionStore.__init__(self, revisionstore.versioned_file_store)
1318
self._serializer = revisionstore._serializer
1319
self.transport = transport
1321
def get_revision_file(self, transaction):
1322
"""Get the revision versioned file object."""
1323
if getattr(self.repo, '_revision_knit', None) is not None:
1324
return self.repo._revision_knit
1325
self.repo._pack_collection.ensure_loaded()
1326
add_callback = self.repo._pack_collection.revision_index.add_callback
1327
# setup knit specific objects
1328
knit_index = KnitGraphIndex(
1329
self.repo._pack_collection.revision_index.combined_index,
1330
add_callback=add_callback)
1331
self.repo._revision_knit = knit.KnitVersionedFile(
1332
'revisions', self.transport.clone('..'),
1333
self.repo.control_files._file_mode,
1334
create=False, access_mode=self.repo._access_mode(),
1335
index=knit_index, delta=False, factory=knit.KnitPlainFactory(),
1336
access_method=self.repo._pack_collection.revision_index.knit_access)
1337
return self.repo._revision_knit
1339
def get_signature_file(self, transaction):
1340
"""Get the signature versioned file object."""
1341
if getattr(self.repo, '_signature_knit', None) is not None:
1342
return self.repo._signature_knit
1343
self.repo._pack_collection.ensure_loaded()
1344
add_callback = self.repo._pack_collection.signature_index.add_callback
1345
# setup knit specific objects
1346
knit_index = KnitGraphIndex(
1347
self.repo._pack_collection.signature_index.combined_index,
1348
add_callback=add_callback, parents=False)
1349
self.repo._signature_knit = knit.KnitVersionedFile(
1350
'signatures', self.transport.clone('..'),
1351
self.repo.control_files._file_mode,
1352
create=False, access_mode=self.repo._access_mode(),
1353
index=knit_index, delta=False, factory=knit.KnitPlainFactory(),
1354
access_method=self.repo._pack_collection.signature_index.knit_access)
1355
return self.repo._signature_knit
1358
class KnitPackTextStore(VersionedFileStore):
1359
"""Presents a TextStore abstraction on top of packs.
1361
This class works by replacing the original VersionedFileStore.
1362
We need to do this because the KnitPackRevisionStore is less
1363
isolated in its layering - it uses services from the repo and shares them
1364
with all the data written in a single write group.
1367
def __init__(self, repo, transport, weavestore):
1368
"""Create a KnitPackTextStore on repo with weavestore.
1370
This will store its state in the Repository, use the
1371
indices FileNames to provide a KnitGraphIndex,
1372
and at the end of transactions write new indices.
1374
# don't call base class constructor - it's not suitable.
1375
# no transient data stored in the transaction
1377
self._precious = False
1379
self.transport = transport
1380
self.weavestore = weavestore
1381
# XXX for check() which isn't updated yet
1382
self._transport = weavestore._transport
1384
def get_weave_or_empty(self, file_id, transaction):
1385
"""Get a 'Knit' backed by the .tix indices.
1387
The transaction parameter is ignored.
1389
self.repo._pack_collection.ensure_loaded()
1390
add_callback = self.repo._pack_collection.text_index.add_callback
1391
# setup knit specific objects
1392
file_id_index = GraphIndexPrefixAdapter(
1393
self.repo._pack_collection.text_index.combined_index,
1394
(file_id, ), 1, add_nodes_callback=add_callback)
1395
knit_index = KnitGraphIndex(file_id_index,
1396
add_callback=file_id_index.add_nodes,
1397
deltas=True, parents=True)
1398
return knit.KnitVersionedFile('text:' + file_id,
1399
self.transport.clone('..'),
1402
access_method=self.repo._pack_collection.text_index.knit_access,
1403
factory=knit.KnitPlainFactory())
1405
get_weave = get_weave_or_empty
1408
"""Generate a list of the fileids inserted, for use by check."""
1409
self.repo._pack_collection.ensure_loaded()
1411
for index, key, value, refs in \
1412
self.repo._pack_collection.text_index.combined_index.iter_all_entries():
1417
class InventoryKnitThunk(object):
1418
"""An object to manage thunking get_inventory_weave to pack based knits."""
1420
def __init__(self, repo, transport):
1421
"""Create an InventoryKnitThunk for repo at transport.
1423
This will store its state in the Repository, use the
1424
indices FileNames to provide a KnitGraphIndex,
1425
and at the end of transactions write a new index..
1428
self.transport = transport
1430
def get_weave(self):
1431
"""Get a 'Knit' that contains inventory data."""
1432
self.repo._pack_collection.ensure_loaded()
1433
add_callback = self.repo._pack_collection.inventory_index.add_callback
1434
# setup knit specific objects
1435
knit_index = KnitGraphIndex(
1436
self.repo._pack_collection.inventory_index.combined_index,
1437
add_callback=add_callback, deltas=True, parents=True)
1438
return knit.KnitVersionedFile(
1439
'inventory', self.transport.clone('..'),
1440
self.repo.control_files._file_mode,
1441
create=False, access_mode=self.repo._access_mode(),
1442
index=knit_index, delta=True, factory=knit.KnitPlainFactory(),
1443
access_method=self.repo._pack_collection.inventory_index.knit_access)
1446
class KnitPackRepository(KnitRepository):
1447
"""Experimental graph-knit using repository."""
1449
def __init__(self, _format, a_bzrdir, control_files, _revision_store,
1450
control_store, text_store, _commit_builder_class, _serializer):
1451
KnitRepository.__init__(self, _format, a_bzrdir, control_files,
1452
_revision_store, control_store, text_store, _commit_builder_class,
1454
index_transport = control_files._transport.clone('indices')
1455
self._pack_collection = RepositoryPackCollection(self, control_files._transport,
1457
control_files._transport.clone('upload'),
1458
control_files._transport.clone('packs'))
1459
self._revision_store = KnitPackRevisionStore(self, index_transport, self._revision_store)
1460
self.weave_store = KnitPackTextStore(self, index_transport, self.weave_store)
1461
self._inv_thunk = InventoryKnitThunk(self, index_transport)
1462
# True when the repository object is 'write locked' (as opposed to the
1463
# physical lock only taken out around changes to the pack-names list.)
1464
# Another way to represent this would be a decorator around the control
1465
# files object that presents logical locks as physical ones - if this
1466
# gets ugly consider that alternative design. RBC 20071011
1467
self._write_lock_count = 0
1468
self._transaction = None
1470
self._reconcile_does_inventory_gc = False
1471
self._reconcile_fixes_text_parents = False
1473
def _abort_write_group(self):
1474
self._pack_collection._abort_write_group()
1476
def _access_mode(self):
1477
"""Return 'w' or 'r' for depending on whether a write lock is active.
1479
This method is a helper for the Knit-thunking support objects.
1481
if self.is_write_locked():
1485
def get_parents(self, revision_ids):
1486
"""See StackedParentsProvider.get_parents.
1488
This implementation accesses the combined revision index to provide
1491
self._pack_collection.ensure_loaded()
1492
index = self._pack_collection.revision_index.combined_index
1494
for revision_id in revision_ids:
1495
if revision_id != _mod_revision.NULL_REVISION:
1496
search_keys.add((revision_id,))
1497
found_parents = {_mod_revision.NULL_REVISION:[]}
1498
for index, key, value, refs in index.iter_entries(search_keys):
1501
parents = (_mod_revision.NULL_REVISION,)
1503
parents = tuple(parent[0] for parent in parents)
1504
found_parents[key[0]] = parents
1506
for revision_id in revision_ids:
1508
result.append(found_parents[revision_id])
1513
def _make_parents_provider(self):
1516
def _refresh_data(self):
1517
if self._write_lock_count == 1 or self.control_files._lock_count == 1:
1518
# forget what names there are
1519
self._pack_collection.reset()
1520
# XXX: Better to do an in-memory merge when acquiring a new lock -
1521
# factor out code from _save_pack_names.
1523
def _start_write_group(self):
1524
self._pack_collection._start_write_group()
1526
def _commit_write_group(self):
1527
return self._pack_collection._commit_write_group()
1529
def get_inventory_weave(self):
1530
return self._inv_thunk.get_weave()
1532
def get_transaction(self):
1533
if self._write_lock_count:
1534
return self._transaction
1536
return self.control_files.get_transaction()
1538
def is_locked(self):
1539
return self._write_lock_count or self.control_files.is_locked()
1541
def is_write_locked(self):
1542
return self._write_lock_count
1544
def lock_write(self, token=None):
1545
if not self._write_lock_count and self.is_locked():
1546
raise errors.ReadOnlyError(self)
1547
self._write_lock_count += 1
1548
if self._write_lock_count == 1:
1549
from bzrlib import transactions
1550
self._transaction = transactions.WriteTransaction()
1551
self._refresh_data()
1553
def lock_read(self):
1554
if self._write_lock_count:
1555
self._write_lock_count += 1
1557
self.control_files.lock_read()
1558
self._refresh_data()
1560
def leave_lock_in_place(self):
1561
# not supported - raise an error
1562
raise NotImplementedError(self.leave_lock_in_place)
1564
def dont_leave_lock_in_place(self):
1565
# not supported - raise an error
1566
raise NotImplementedError(self.dont_leave_lock_in_place)
1570
"""Compress the data within the repository.
1572
This will pack all the data to a single pack. In future it may
1573
recompress deltas or do other such expensive operations.
1575
self._pack_collection.pack()
1578
def reconcile(self, other=None, thorough=False):
1579
"""Reconcile this repository."""
1580
from bzrlib.reconcile import PackReconciler
1581
reconciler = PackReconciler(self, thorough=thorough)
1582
reconciler.reconcile()
1586
if self._write_lock_count == 1 and self._write_group is not None:
1587
self.abort_write_group()
1588
self._transaction = None
1589
self._write_lock_count = 0
1590
raise errors.BzrError(
1591
'Must end write group before releasing write lock on %s'
1593
if self._write_lock_count:
1594
self._write_lock_count -= 1
1595
if not self._write_lock_count:
1596
transaction = self._transaction
1597
self._transaction = None
1598
transaction.finish()
1600
self.control_files.unlock()
1603
class RepositoryFormatPack(MetaDirRepositoryFormat):
1604
"""Format logic for pack structured repositories.
1606
This repository format has:
1607
- a list of packs in pack-names
1608
- packs in packs/NAME.pack
1609
- indices in indices/NAME.{iix,six,tix,rix}
1610
- knit deltas in the packs, knit indices mapped to the indices.
1611
- thunk objects to support the knits programming API.
1612
- a format marker of its own
1613
- an optional 'shared-storage' flag
1614
- an optional 'no-working-trees' flag
1618
# Set this attribute in derived classes to control the repository class
1619
# created by open and initialize.
1620
repository_class = None
1621
# Set this attribute in derived classes to control the
1622
# _commit_builder_class that the repository objects will have passed to
1623
# their constructor.
1624
_commit_builder_class = None
1625
# Set this attribute in derived clases to control the _serializer that the
1626
# repository objects will have passed to their constructor.
1629
def _get_control_store(self, repo_transport, control_files):
1630
"""Return the control store for this repository."""
1631
return VersionedFileStore(
1634
file_mode=control_files._file_mode,
1635
versionedfile_class=knit.KnitVersionedFile,
1636
versionedfile_kwargs={'factory': knit.KnitPlainFactory()},
1639
def _get_revision_store(self, repo_transport, control_files):
1640
"""See RepositoryFormat._get_revision_store()."""
1641
versioned_file_store = VersionedFileStore(
1643
file_mode=control_files._file_mode,
1646
versionedfile_class=knit.KnitVersionedFile,
1647
versionedfile_kwargs={'delta': False,
1648
'factory': knit.KnitPlainFactory(),
1652
return KnitRevisionStore(versioned_file_store)
1654
def _get_text_store(self, transport, control_files):
1655
"""See RepositoryFormat._get_text_store()."""
1656
return self._get_versioned_file_store('knits',
1659
versionedfile_class=knit.KnitVersionedFile,
1660
versionedfile_kwargs={
1661
'create_parent_dir': True,
1662
'delay_create': True,
1663
'dir_mode': control_files._dir_mode,
1667
def initialize(self, a_bzrdir, shared=False):
1668
"""Create a pack based repository.
1670
:param a_bzrdir: bzrdir to contain the new repository; must already
1672
:param shared: If true the repository will be initialized as a shared
1675
mutter('creating repository in %s.', a_bzrdir.transport.base)
1676
dirs = ['indices', 'obsolete_packs', 'packs', 'upload']
1677
builder = GraphIndexBuilder()
1678
files = [('pack-names', builder.finish())]
1679
utf8_files = [('format', self.get_format_string())]
1681
self._upload_blank_content(a_bzrdir, dirs, files, utf8_files, shared)
1682
return self.open(a_bzrdir=a_bzrdir, _found=True)
1684
def open(self, a_bzrdir, _found=False, _override_transport=None):
1685
"""See RepositoryFormat.open().
1687
:param _override_transport: INTERNAL USE ONLY. Allows opening the
1688
repository at a slightly different url
1689
than normal. I.e. during 'upgrade'.
1692
format = RepositoryFormat.find_format(a_bzrdir)
1693
assert format.__class__ == self.__class__
1694
if _override_transport is not None:
1695
repo_transport = _override_transport
1697
repo_transport = a_bzrdir.get_repository_transport(None)
1698
control_files = lockable_files.LockableFiles(repo_transport,
1699
'lock', lockdir.LockDir)
1700
text_store = self._get_text_store(repo_transport, control_files)
1701
control_store = self._get_control_store(repo_transport, control_files)
1702
_revision_store = self._get_revision_store(repo_transport, control_files)
1703
return self.repository_class(_format=self,
1705
control_files=control_files,
1706
_revision_store=_revision_store,
1707
control_store=control_store,
1708
text_store=text_store,
1709
_commit_builder_class=self._commit_builder_class,
1710
_serializer=self._serializer)
1713
class RepositoryFormatKnitPack1(RepositoryFormatPack):
1714
"""A no-subtrees parameterised Pack repository.
1716
This format was introduced in 0.92.
1719
repository_class = KnitPackRepository
1720
_commit_builder_class = PackCommitBuilder
1721
_serializer = xml5.serializer_v5
1723
def _get_matching_bzrdir(self):
1724
return bzrdir.format_registry.make_bzrdir('knitpack-experimental')
1726
def _ignore_setting_bzrdir(self, format):
1729
_matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
1731
def get_format_string(self):
1732
"""See RepositoryFormat.get_format_string()."""
1733
return "Bazaar pack repository format 1 (needs bzr 0.92)\n"
1735
def get_format_description(self):
1736
"""See RepositoryFormat.get_format_description()."""
1737
return "Packs containing knits without subtree support"
1739
def check_conversion_target(self, target_format):
1743
class RepositoryFormatKnitPack3(RepositoryFormatPack):
1744
"""A subtrees parameterised Pack repository.
1746
This repository format uses the xml7 serializer to get:
1747
- support for recording full info about the tree root
1748
- support for recording tree-references
1750
This format was introduced in 0.92.
1753
repository_class = KnitPackRepository
1754
_commit_builder_class = PackRootCommitBuilder
1755
rich_root_data = True
1756
supports_tree_reference = True
1757
_serializer = xml7.serializer_v7
1759
def _get_matching_bzrdir(self):
1760
return bzrdir.format_registry.make_bzrdir(
1761
'knitpack-subtree-experimental')
1763
def _ignore_setting_bzrdir(self, format):
1766
_matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
1768
def check_conversion_target(self, target_format):
1769
if not target_format.rich_root_data:
1770
raise errors.BadConversionTarget(
1771
'Does not support rich root data.', target_format)
1772
if not getattr(target_format, 'supports_tree_reference', False):
1773
raise errors.BadConversionTarget(
1774
'Does not support nested trees', target_format)
1776
def get_format_string(self):
1777
"""See RepositoryFormat.get_format_string()."""
1778
return "Bazaar pack repository format 1 with subtree support (needs bzr 0.92)\n"
1780
def get_format_description(self):
1781
"""See RepositoryFormat.get_format_description()."""
1782
return "Packs containing knits with subtree support\n"