~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/repofmt/pack_repo.py

Merge bzr.dev and tree-file-ids-as-tuples.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005, 2006, 2007, 2008 Canonical Ltd
 
1
# Copyright (C) 2007-2011 Canonical Ltd
2
2
#
3
3
# This program is free software; you can redistribute it and/or modify
4
4
# it under the terms of the GNU General Public License as published by
12
12
#
13
13
# You should have received a copy of the GNU General Public License
14
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
 
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 
16
 
 
17
from __future__ import absolute_import
 
18
 
 
19
import re
 
20
import sys
16
21
 
17
22
from bzrlib.lazy_import import lazy_import
18
23
lazy_import(globals(), """
20
25
import time
21
26
 
22
27
from bzrlib import (
 
28
    chk_map,
 
29
    cleanup,
 
30
    config,
23
31
    debug,
24
32
    graph,
25
33
    osutils,
26
34
    pack,
27
35
    transactions,
 
36
    tsort,
28
37
    ui,
29
 
    xml5,
30
 
    xml6,
31
 
    xml7,
32
38
    )
33
39
from bzrlib.index import (
34
40
    CombinedGraphIndex,
35
 
    GraphIndex,
36
 
    GraphIndexBuilder,
37
41
    GraphIndexPrefixAdapter,
38
 
    InMemoryGraphIndex,
39
 
    )
40
 
from bzrlib.knit import (
41
 
    KnitPlainFactory,
42
 
    KnitVersionedFiles,
43
 
    _KnitGraphIndex,
44
 
    _DirectPackAccess,
45
 
    )
46
 
from bzrlib import tsort
 
42
    )
47
43
""")
48
44
from bzrlib import (
49
 
    bzrdir,
 
45
    btree_index,
50
46
    errors,
51
47
    lockable_files,
52
48
    lockdir,
53
 
    symbol_versioning,
54
49
    )
55
50
 
56
 
from bzrlib.decorators import needs_write_lock
57
 
from bzrlib.btree_index import (
58
 
    BTreeGraphIndex,
59
 
    BTreeBuilder,
60
 
    )
61
 
from bzrlib.index import (
62
 
    GraphIndex,
63
 
    InMemoryGraphIndex,
64
 
    )
65
 
from bzrlib.repofmt.knitrepo import KnitRepository
 
51
from bzrlib.decorators import (
 
52
    needs_read_lock,
 
53
    needs_write_lock,
 
54
    only_raises,
 
55
    )
 
56
from bzrlib.lock import LogicalLockResult
66
57
from bzrlib.repository import (
67
 
    CommitBuilder,
68
 
    MetaDirRepositoryFormat,
69
 
    RepositoryFormat,
70
 
    RootCommitBuilder,
71
 
    )
72
 
import bzrlib.revision as _mod_revision
 
58
    _LazyListJoin,
 
59
    MetaDirRepository,
 
60
    RepositoryFormatMetaDir,
 
61
    RepositoryWriteLockResult,
 
62
    )
 
63
from bzrlib.vf_repository import (
 
64
    MetaDirVersionedFileRepository,
 
65
    MetaDirVersionedFileRepositoryFormat,
 
66
    VersionedFileCommitBuilder,
 
67
    VersionedFileRootCommitBuilder,
 
68
    )
73
69
from bzrlib.trace import (
74
70
    mutter,
 
71
    note,
75
72
    warning,
76
73
    )
77
74
 
78
75
 
79
 
class PackCommitBuilder(CommitBuilder):
80
 
    """A subclass of CommitBuilder to add texts with pack semantics.
81
 
    
 
76
class PackCommitBuilder(VersionedFileCommitBuilder):
 
77
    """Subclass of VersionedFileCommitBuilder to add texts with pack semantics.
 
78
 
82
79
    Specifically this uses one knit object rather than one knit object per
83
80
    added text, reducing memory and object pressure.
84
81
    """
85
82
 
86
83
    def __init__(self, repository, parents, config, timestamp=None,
87
84
                 timezone=None, committer=None, revprops=None,
88
 
                 revision_id=None):
89
 
        CommitBuilder.__init__(self, repository, parents, config,
 
85
                 revision_id=None, lossy=False):
 
86
        VersionedFileCommitBuilder.__init__(self, repository, parents, config,
90
87
            timestamp=timestamp, timezone=timezone, committer=committer,
91
 
            revprops=revprops, revision_id=revision_id)
 
88
            revprops=revprops, revision_id=revision_id, lossy=lossy)
92
89
        self._file_graph = graph.Graph(
93
90
            repository._pack_collection.text_index.combined_index)
94
91
 
97
94
        return set([key[1] for key in self._file_graph.heads(keys)])
98
95
 
99
96
 
100
 
class PackRootCommitBuilder(RootCommitBuilder):
 
97
class PackRootCommitBuilder(VersionedFileRootCommitBuilder):
101
98
    """A subclass of RootCommitBuilder to add texts with pack semantics.
102
 
    
 
99
 
103
100
    Specifically this uses one knit object rather than one knit object per
104
101
    added text, reducing memory and object pressure.
105
102
    """
106
103
 
107
104
    def __init__(self, repository, parents, config, timestamp=None,
108
105
                 timezone=None, committer=None, revprops=None,
109
 
                 revision_id=None):
110
 
        CommitBuilder.__init__(self, repository, parents, config,
111
 
            timestamp=timestamp, timezone=timezone, committer=committer,
112
 
            revprops=revprops, revision_id=revision_id)
 
106
                 revision_id=None, lossy=False):
 
107
        super(PackRootCommitBuilder, self).__init__(repository, parents,
 
108
            config, timestamp=timestamp, timezone=timezone,
 
109
            committer=committer, revprops=revprops, revision_id=revision_id,
 
110
            lossy=lossy)
113
111
        self._file_graph = graph.Graph(
114
112
            repository._pack_collection.text_index.combined_index)
115
113
 
125
123
    ExistingPack and NewPack are used.
126
124
    """
127
125
 
 
126
    # A map of index 'type' to the file extension and position in the
 
127
    # index_sizes array.
 
128
    index_definitions = {
 
129
        'chk': ('.cix', 4),
 
130
        'revision': ('.rix', 0),
 
131
        'inventory': ('.iix', 1),
 
132
        'text': ('.tix', 2),
 
133
        'signature': ('.six', 3),
 
134
        }
 
135
 
128
136
    def __init__(self, revision_index, inventory_index, text_index,
129
 
        signature_index):
 
137
        signature_index, chk_index=None):
130
138
        """Create a pack instance.
131
139
 
132
140
        :param revision_index: A GraphIndex for determining what revisions are
139
147
            texts/deltas (via (fileid, revisionid) tuples).
140
148
        :param signature_index: A GraphIndex for determining what signatures are
141
149
            present in the Pack and accessing the locations of their texts.
 
150
        :param chk_index: A GraphIndex for accessing content by CHK, if the
 
151
            pack has one.
142
152
        """
143
153
        self.revision_index = revision_index
144
154
        self.inventory_index = inventory_index
145
155
        self.text_index = text_index
146
156
        self.signature_index = signature_index
 
157
        self.chk_index = chk_index
147
158
 
148
159
    def access_tuple(self):
149
160
        """Return a tuple (transport, name) for the pack content."""
150
161
        return self.pack_transport, self.file_name()
151
162
 
 
163
    def _check_references(self):
 
164
        """Make sure our external references are present.
 
165
 
 
166
        Packs are allowed to have deltas whose base is not in the pack, but it
 
167
        must be present somewhere in this collection.  It is not allowed to
 
168
        have deltas based on a fallback repository.
 
169
        (See <https://bugs.launchpad.net/bzr/+bug/288751>)
 
170
        """
 
171
        missing_items = {}
 
172
        for (index_name, external_refs, index) in [
 
173
            ('texts',
 
174
                self._get_external_refs(self.text_index),
 
175
                self._pack_collection.text_index.combined_index),
 
176
            ('inventories',
 
177
                self._get_external_refs(self.inventory_index),
 
178
                self._pack_collection.inventory_index.combined_index),
 
179
            ]:
 
180
            missing = external_refs.difference(
 
181
                k for (idx, k, v, r) in
 
182
                index.iter_entries(external_refs))
 
183
            if missing:
 
184
                missing_items[index_name] = sorted(list(missing))
 
185
        if missing_items:
 
186
            from pprint import pformat
 
187
            raise errors.BzrCheckError(
 
188
                "Newly created pack file %r has delta references to "
 
189
                "items not in its repository:\n%s"
 
190
                % (self, pformat(missing_items)))
 
191
 
152
192
    def file_name(self):
153
193
        """Get the file name for the pack on disk."""
154
194
        return self.name + '.pack'
156
196
    def get_revision_count(self):
157
197
        return self.revision_index.key_count()
158
198
 
 
199
    def index_name(self, index_type, name):
 
200
        """Get the disk name of an index type for pack name 'name'."""
 
201
        return name + Pack.index_definitions[index_type][0]
 
202
 
 
203
    def index_offset(self, index_type):
 
204
        """Get the position in a index_size array for a given index type."""
 
205
        return Pack.index_definitions[index_type][1]
 
206
 
159
207
    def inventory_index_name(self, name):
160
208
        """The inv index is the name + .iix."""
161
209
        return self.index_name('inventory', name)
172
220
        """The text index is the name + .tix."""
173
221
        return self.index_name('text', name)
174
222
 
175
 
    def _external_compression_parents_of_texts(self):
176
 
        keys = set()
177
 
        refs = set()
178
 
        for node in self.text_index.iter_all_entries():
179
 
            keys.add(node[1])
180
 
            refs.update(node[3][1])
181
 
        return refs - keys
 
223
    def _replace_index_with_readonly(self, index_type):
 
224
        unlimited_cache = False
 
225
        if index_type == 'chk':
 
226
            unlimited_cache = True
 
227
        index = self.index_class(self.index_transport,
 
228
                    self.index_name(index_type, self.name),
 
229
                    self.index_sizes[self.index_offset(index_type)],
 
230
                    unlimited_cache=unlimited_cache)
 
231
        if index_type == 'chk':
 
232
            index._leaf_factory = btree_index._gcchk_factory
 
233
        setattr(self, index_type + '_index', index)
182
234
 
183
235
 
184
236
class ExistingPack(Pack):
185
237
    """An in memory proxy for an existing .pack and its disk indices."""
186
238
 
187
239
    def __init__(self, pack_transport, name, revision_index, inventory_index,
188
 
        text_index, signature_index):
 
240
        text_index, signature_index, chk_index=None):
189
241
        """Create an ExistingPack object.
190
242
 
191
243
        :param pack_transport: The transport where the pack file resides.
192
244
        :param name: The name of the pack on disk in the pack_transport.
193
245
        """
194
246
        Pack.__init__(self, revision_index, inventory_index, text_index,
195
 
            signature_index)
 
247
            signature_index, chk_index)
196
248
        self.name = name
197
249
        self.pack_transport = pack_transport
198
250
        if None in (revision_index, inventory_index, text_index,
206
258
        return not self.__eq__(other)
207
259
 
208
260
    def __repr__(self):
209
 
        return "<bzrlib.repofmt.pack_repo.Pack object at 0x%x, %s, %s" % (
210
 
            id(self), self.pack_transport, self.name)
 
261
        return "<%s.%s object at 0x%x, %s, %s" % (
 
262
            self.__class__.__module__, self.__class__.__name__, id(self),
 
263
            self.pack_transport, self.name)
 
264
 
 
265
 
 
266
class ResumedPack(ExistingPack):
 
267
 
 
268
    def __init__(self, name, revision_index, inventory_index, text_index,
 
269
        signature_index, upload_transport, pack_transport, index_transport,
 
270
        pack_collection, chk_index=None):
 
271
        """Create a ResumedPack object."""
 
272
        ExistingPack.__init__(self, pack_transport, name, revision_index,
 
273
            inventory_index, text_index, signature_index,
 
274
            chk_index=chk_index)
 
275
        self.upload_transport = upload_transport
 
276
        self.index_transport = index_transport
 
277
        self.index_sizes = [None, None, None, None]
 
278
        indices = [
 
279
            ('revision', revision_index),
 
280
            ('inventory', inventory_index),
 
281
            ('text', text_index),
 
282
            ('signature', signature_index),
 
283
            ]
 
284
        if chk_index is not None:
 
285
            indices.append(('chk', chk_index))
 
286
            self.index_sizes.append(None)
 
287
        for index_type, index in indices:
 
288
            offset = self.index_offset(index_type)
 
289
            self.index_sizes[offset] = index._size
 
290
        self.index_class = pack_collection._index_class
 
291
        self._pack_collection = pack_collection
 
292
        self._state = 'resumed'
 
293
        # XXX: perhaps check that the .pack file exists?
 
294
 
 
295
    def access_tuple(self):
 
296
        if self._state == 'finished':
 
297
            return Pack.access_tuple(self)
 
298
        elif self._state == 'resumed':
 
299
            return self.upload_transport, self.file_name()
 
300
        else:
 
301
            raise AssertionError(self._state)
 
302
 
 
303
    def abort(self):
 
304
        self.upload_transport.delete(self.file_name())
 
305
        indices = [self.revision_index, self.inventory_index, self.text_index,
 
306
            self.signature_index]
 
307
        if self.chk_index is not None:
 
308
            indices.append(self.chk_index)
 
309
        for index in indices:
 
310
            index._transport.delete(index._name)
 
311
 
 
312
    def finish(self):
 
313
        self._check_references()
 
314
        index_types = ['revision', 'inventory', 'text', 'signature']
 
315
        if self.chk_index is not None:
 
316
            index_types.append('chk')
 
317
        for index_type in index_types:
 
318
            old_name = self.index_name(index_type, self.name)
 
319
            new_name = '../indices/' + old_name
 
320
            self.upload_transport.move(old_name, new_name)
 
321
            self._replace_index_with_readonly(index_type)
 
322
        new_name = '../packs/' + self.file_name()
 
323
        self.upload_transport.move(self.file_name(), new_name)
 
324
        self._state = 'finished'
 
325
 
 
326
    def _get_external_refs(self, index):
 
327
        """Return compression parents for this index that are not present.
 
328
 
 
329
        This returns any compression parents that are referenced by this index,
 
330
        which are not contained *in* this index. They may be present elsewhere.
 
331
        """
 
332
        return index.external_references(1)
211
333
 
212
334
 
213
335
class NewPack(Pack):
214
336
    """An in memory proxy for a pack which is being created."""
215
337
 
216
 
    # A map of index 'type' to the file extension and position in the
217
 
    # index_sizes array.
218
 
    index_definitions = {
219
 
        'revision': ('.rix', 0),
220
 
        'inventory': ('.iix', 1),
221
 
        'text': ('.tix', 2),
222
 
        'signature': ('.six', 3),
223
 
        }
224
 
 
225
 
    def __init__(self, upload_transport, index_transport, pack_transport,
226
 
        upload_suffix='', file_mode=None, index_builder_class=None,
227
 
        index_class=None):
 
338
    def __init__(self, pack_collection, upload_suffix='', file_mode=None):
228
339
        """Create a NewPack instance.
229
340
 
230
 
        :param upload_transport: A writable transport for the pack to be
231
 
            incrementally uploaded to.
232
 
        :param index_transport: A writable transport for the pack's indices to
233
 
            be written to when the pack is finished.
234
 
        :param pack_transport: A writable transport for the pack to be renamed
235
 
            to when the upload is complete. This *must* be the same as
236
 
            upload_transport.clone('../packs').
 
341
        :param pack_collection: A PackCollection into which this is being inserted.
237
342
        :param upload_suffix: An optional suffix to be given to any temporary
238
343
            files created during the pack creation. e.g '.autopack'
239
 
        :param file_mode: An optional file mode to create the new files with.
240
 
        :param index_builder_class: Required keyword parameter - the class of
241
 
            index builder to use.
242
 
        :param index_class: Required keyword parameter - the class of index
243
 
            object to use.
 
344
        :param file_mode: Unix permissions for newly created file.
244
345
        """
245
346
        # The relative locations of the packs are constrained, but all are
246
347
        # passed in because the caller has them, so as to avoid object churn.
 
348
        index_builder_class = pack_collection._index_builder_class
 
349
        if pack_collection.chk_index is not None:
 
350
            chk_index = index_builder_class(reference_lists=0)
 
351
        else:
 
352
            chk_index = None
247
353
        Pack.__init__(self,
248
354
            # Revisions: parents list, no text compression.
249
355
            index_builder_class(reference_lists=1),
258
364
            # Signatures: Just blobs to store, no compression, no parents
259
365
            # listing.
260
366
            index_builder_class(reference_lists=0),
 
367
            # CHK based storage - just blobs, no compression or parents.
 
368
            chk_index=chk_index
261
369
            )
 
370
        self._pack_collection = pack_collection
262
371
        # When we make readonly indices, we need this.
263
 
        self.index_class = index_class
 
372
        self.index_class = pack_collection._index_class
264
373
        # where should the new pack be opened
265
 
        self.upload_transport = upload_transport
 
374
        self.upload_transport = pack_collection._upload_transport
266
375
        # where are indices written out to
267
 
        self.index_transport = index_transport
 
376
        self.index_transport = pack_collection._index_transport
268
377
        # where is the pack renamed to when it is finished?
269
 
        self.pack_transport = pack_transport
 
378
        self.pack_transport = pack_collection._pack_transport
270
379
        # What file mode to upload the pack and indices with.
271
380
        self._file_mode = file_mode
272
381
        # tracks the content written to the .pack file.
273
382
        self._hash = osutils.md5()
274
 
        # a four-tuple with the length in bytes of the indices, once the pack
275
 
        # is finalised. (rev, inv, text, sigs)
 
383
        # a tuple with the length in bytes of the indices, once the pack
 
384
        # is finalised. (rev, inv, text, sigs, chk_if_in_use)
276
385
        self.index_sizes = None
277
386
        # How much data to cache when writing packs. Note that this is not
278
387
        # synchronised with reads, because it's not in the transport layer, so
290
399
            mutter('%s: create_pack: pack stream open: %s%s t+%6.3fs',
291
400
                time.ctime(), self.upload_transport.base, self.random_name,
292
401
                time.time() - self.start_time)
293
 
        # A list of byte sequences to be written to the new pack, and the 
294
 
        # aggregate size of them.  Stored as a list rather than separate 
 
402
        # A list of byte sequences to be written to the new pack, and the
 
403
        # aggregate size of them.  Stored as a list rather than separate
295
404
        # variables so that the _write_data closure below can update them.
296
405
        self._buffer = [[], 0]
297
 
        # create a callable for adding data 
 
406
        # create a callable for adding data
298
407
        #
299
408
        # robertc says- this is a closure rather than a method on the object
300
409
        # so that the variables are locals, and faster than accessing object
316
425
        self._writer.begin()
317
426
        # what state is the pack in? (open, finished, aborted)
318
427
        self._state = 'open'
 
428
        # no name until we finish writing the content
 
429
        self.name = None
319
430
 
320
431
    def abort(self):
321
432
        """Cancel creating this pack."""
339
450
        return bool(self.get_revision_count() or
340
451
            self.inventory_index.key_count() or
341
452
            self.text_index.key_count() or
342
 
            self.signature_index.key_count())
343
 
 
344
 
    def finish(self):
 
453
            self.signature_index.key_count() or
 
454
            (self.chk_index is not None and self.chk_index.key_count()))
 
455
 
 
456
    def finish_content(self):
 
457
        if self.name is not None:
 
458
            return
 
459
        self._writer.end()
 
460
        if self._buffer[1]:
 
461
            self._write_data('', flush=True)
 
462
        self.name = self._hash.hexdigest()
 
463
 
 
464
    def finish(self, suspend=False):
345
465
        """Finish the new pack.
346
466
 
347
467
        This:
352
472
         - stores the index size tuple for the pack in the index_sizes
353
473
           attribute.
354
474
        """
355
 
        self._writer.end()
356
 
        if self._buffer[1]:
357
 
            self._write_data('', flush=True)
358
 
        self.name = self._hash.hexdigest()
 
475
        self.finish_content()
 
476
        if not suspend:
 
477
            self._check_references()
359
478
        # write indices
360
479
        # XXX: It'd be better to write them all to temporary names, then
361
480
        # rename them all into place, so that the window when only some are
362
481
        # visible is smaller.  On the other hand none will be seen until
363
482
        # they're in the names list.
364
483
        self.index_sizes = [None, None, None, None]
365
 
        self._write_index('revision', self.revision_index, 'revision')
366
 
        self._write_index('inventory', self.inventory_index, 'inventory')
367
 
        self._write_index('text', self.text_index, 'file texts')
 
484
        self._write_index('revision', self.revision_index, 'revision',
 
485
            suspend)
 
486
        self._write_index('inventory', self.inventory_index, 'inventory',
 
487
            suspend)
 
488
        self._write_index('text', self.text_index, 'file texts', suspend)
368
489
        self._write_index('signature', self.signature_index,
369
 
            'revision signatures')
370
 
        self.write_stream.close()
 
490
            'revision signatures', suspend)
 
491
        if self.chk_index is not None:
 
492
            self.index_sizes.append(None)
 
493
            self._write_index('chk', self.chk_index,
 
494
                'content hash bytes', suspend)
 
495
        self.write_stream.close(
 
496
            want_fdatasync=self._pack_collection.config_stack.get('repository.fdatasync'))
371
497
        # Note that this will clobber an existing pack with the same name,
372
498
        # without checking for hash collisions. While this is undesirable this
373
499
        # is something that can be rectified in a subsequent release. One way
379
505
        #  - try for HASH.pack
380
506
        #  - try for temporary-name
381
507
        #  - refresh the pack-list to see if the pack is now absent
382
 
        self.upload_transport.rename(self.random_name,
383
 
                '../packs/' + self.name + '.pack')
 
508
        new_name = self.name + '.pack'
 
509
        if not suspend:
 
510
            new_name = '../packs/' + new_name
 
511
        self.upload_transport.move(self.random_name, new_name)
384
512
        self._state = 'finished'
385
513
        if 'pack' in debug.debug_flags:
386
514
            # XXX: size might be interesting?
387
 
            mutter('%s: create_pack: pack renamed into place: %s%s->%s%s t+%6.3fs',
 
515
            mutter('%s: create_pack: pack finished: %s%s->%s t+%6.3fs',
388
516
                time.ctime(), self.upload_transport.base, self.random_name,
389
 
                self.pack_transport, self.name,
390
 
                time.time() - self.start_time)
 
517
                new_name, time.time() - self.start_time)
391
518
 
392
519
    def flush(self):
393
520
        """Flush any current data."""
397
524
            self._hash.update(bytes)
398
525
            self._buffer[:] = [[], 0]
399
526
 
400
 
    def index_name(self, index_type, name):
401
 
        """Get the disk name of an index type for pack name 'name'."""
402
 
        return name + NewPack.index_definitions[index_type][0]
403
 
 
404
 
    def index_offset(self, index_type):
405
 
        """Get the position in a index_size array for a given index type."""
406
 
        return NewPack.index_definitions[index_type][1]
407
 
 
408
 
    def _replace_index_with_readonly(self, index_type):
409
 
        setattr(self, index_type + '_index',
410
 
            self.index_class(self.index_transport,
411
 
                self.index_name(index_type, self.name),
412
 
                self.index_sizes[self.index_offset(index_type)]))
 
527
    def _get_external_refs(self, index):
 
528
        return index._external_references()
413
529
 
414
530
    def set_write_cache_size(self, size):
415
531
        self._cache_limit = size
416
532
 
417
 
    def _write_index(self, index_type, index, label):
 
533
    def _write_index(self, index_type, index, label, suspend=False):
418
534
        """Write out an index.
419
535
 
420
536
        :param index_type: The type of index to write - e.g. 'revision'.
422
538
        :param label: What label to give the index e.g. 'revision'.
423
539
        """
424
540
        index_name = self.index_name(index_type, self.name)
425
 
        self.index_sizes[self.index_offset(index_type)] = \
426
 
            self.index_transport.put_file(index_name, index.finish(),
 
541
        if suspend:
 
542
            transport = self.upload_transport
 
543
        else:
 
544
            transport = self.index_transport
 
545
        index_tempfile = index.finish()
 
546
        index_bytes = index_tempfile.read()
 
547
        write_stream = transport.open_write_stream(index_name,
427
548
            mode=self._file_mode)
 
549
        write_stream.write(index_bytes)
 
550
        write_stream.close(
 
551
            want_fdatasync=self._pack_collection.config_stack.get('repository.fdatasync'))
 
552
        self.index_sizes[self.index_offset(index_type)] = len(index_bytes)
428
553
        if 'pack' in debug.debug_flags:
429
554
            # XXX: size might be interesting?
430
555
            mutter('%s: create_pack: wrote %s index: %s%s t+%6.3fs',
431
556
                time.ctime(), label, self.upload_transport.base,
432
557
                self.random_name, time.time() - self.start_time)
433
 
        # Replace the writable index on this object with a readonly, 
 
558
        # Replace the writable index on this object with a readonly,
434
559
        # presently unloaded index. We should alter
435
560
        # the index layer to make its finish() error if add_node is
436
561
        # subsequently used. RBC
445
570
    such as 'revision index'.
446
571
 
447
572
    A CombinedIndex provides an index on a single key space built up
448
 
    from several on-disk indices.  The AggregateIndex builds on this 
 
573
    from several on-disk indices.  The AggregateIndex builds on this
449
574
    to provide a knit access layer, and allows having up to one writable
450
575
    index within the collection.
451
576
    """
452
577
    # XXX: Probably 'can be written to' could/should be separated from 'acts
453
578
    # like a knit index' -- mbp 20071024
454
579
 
455
 
    def __init__(self):
456
 
        """Create an AggregateIndex."""
 
580
    def __init__(self, reload_func=None, flush_func=None):
 
581
        """Create an AggregateIndex.
 
582
 
 
583
        :param reload_func: A function to call if we find we are missing an
 
584
            index. Should have the form reload_func() => True if the list of
 
585
            active pack files has changed.
 
586
        """
 
587
        self._reload_func = reload_func
457
588
        self.index_to_pack = {}
458
 
        self.combined_index = CombinedGraphIndex([])
459
 
        self.data_access = _DirectPackAccess(self.index_to_pack)
460
 
        self.add_callback = None
461
 
 
462
 
    def replace_indices(self, index_to_pack, indices):
463
 
        """Replace the current mappings with fresh ones.
464
 
 
465
 
        This should probably not be used eventually, rather incremental add and
466
 
        removal of indices. It has been added during refactoring of existing
467
 
        code.
468
 
 
469
 
        :param index_to_pack: A mapping from index objects to
470
 
            (transport, name) tuples for the pack file data.
471
 
        :param indices: A list of indices.
472
 
        """
473
 
        # refresh the revision pack map dict without replacing the instance.
474
 
        self.index_to_pack.clear()
475
 
        self.index_to_pack.update(index_to_pack)
476
 
        # XXX: API break - clearly a 'replace' method would be good?
477
 
        self.combined_index._indices[:] = indices
478
 
        # the current add nodes callback for the current writable index if
479
 
        # there is one.
 
589
        self.combined_index = CombinedGraphIndex([], reload_func=reload_func)
 
590
        self.data_access = _DirectPackAccess(self.index_to_pack,
 
591
                                             reload_func=reload_func,
 
592
                                             flush_func=flush_func)
480
593
        self.add_callback = None
481
594
 
482
595
    def add_index(self, index, pack):
484
597
 
485
598
        Future searches on the aggregate index will seach this new index
486
599
        before all previously inserted indices.
487
 
        
 
600
 
488
601
        :param index: An Index for the pack.
489
602
        :param pack: A Pack instance.
490
603
        """
491
604
        # expose it to the index map
492
605
        self.index_to_pack[index] = pack.access_tuple()
493
606
        # put it at the front of the linear index list
494
 
        self.combined_index.insert_index(0, index)
 
607
        self.combined_index.insert_index(0, index, pack.name)
495
608
 
496
609
    def add_writable_index(self, index, pack):
497
610
        """Add an index which is able to have data added to it.
498
611
 
499
612
        There can be at most one writable index at any time.  Any
500
613
        modifications made to the knit are put into this index.
501
 
        
 
614
 
502
615
        :param index: An index from the pack parameter.
503
616
        :param pack: A Pack instance.
504
617
        """
517
630
        self.data_access.set_writer(None, None, (None, None))
518
631
        self.index_to_pack.clear()
519
632
        del self.combined_index._indices[:]
 
633
        del self.combined_index._index_names[:]
520
634
        self.add_callback = None
521
635
 
522
 
    def remove_index(self, index, pack):
 
636
    def remove_index(self, index):
523
637
        """Remove index from the indices used to answer queries.
524
 
        
 
638
 
525
639
        :param index: An index from the pack parameter.
526
 
        :param pack: A Pack instance.
527
640
        """
528
641
        del self.index_to_pack[index]
529
 
        self.combined_index._indices.remove(index)
 
642
        pos = self.combined_index._indices.index(index)
 
643
        del self.combined_index._indices[pos]
 
644
        del self.combined_index._index_names[pos]
530
645
        if (self.add_callback is not None and
531
646
            getattr(index, 'add_nodes', None) == self.add_callback):
532
647
            self.add_callback = None
536
651
class Packer(object):
537
652
    """Create a pack from packs."""
538
653
 
539
 
    def __init__(self, pack_collection, packs, suffix, revision_ids=None):
 
654
    def __init__(self, pack_collection, packs, suffix, revision_ids=None,
 
655
                 reload_func=None):
540
656
        """Create a Packer.
541
657
 
542
658
        :param pack_collection: A RepositoryPackCollection object where the
544
660
        :param packs: The packs to combine.
545
661
        :param suffix: The suffix to use on the temporary files for the pack.
546
662
        :param revision_ids: Revision ids to limit the pack to.
 
663
        :param reload_func: A function to call if a pack file/index goes
 
664
            missing. The side effect of calling this function should be to
 
665
            update self.packs. See also AggregateIndex
547
666
        """
548
667
        self.packs = packs
549
668
        self.suffix = suffix
551
670
        # The pack object we are creating.
552
671
        self.new_pack = None
553
672
        self._pack_collection = pack_collection
 
673
        self._reload_func = reload_func
554
674
        # The index layer keys for the revisions being copied. None for 'all
555
675
        # objects'.
556
676
        self._revision_keys = None
557
677
        # What text keys to copy. None for 'all texts'. This is set by
558
678
        # _copy_inventory_texts
559
679
        self._text_filter = None
560
 
        self._extra_init()
561
 
 
562
 
    def _extra_init(self):
563
 
        """A template hook to allow extending the constructor trivially."""
564
680
 
565
681
    def pack(self, pb=None):
566
682
        """Create a new pack by reading data from other packs.
568
684
        This does little more than a bulk copy of data. One key difference
569
685
        is that data with the same item key across multiple packs is elided
570
686
        from the output. The new pack is written into the current pack store
571
 
        along with its indices, and the name added to the pack names. The 
 
687
        along with its indices, and the name added to the pack names. The
572
688
        source packs are not altered and are not required to be in the current
573
689
        pack collection.
574
690
 
577
693
        :return: A Pack object, or None if nothing was copied.
578
694
        """
579
695
        # open a pack - using the same name as the last temporary file
580
 
        # - which has already been flushed, so its safe.
 
696
        # - which has already been flushed, so it's safe.
581
697
        # XXX: - duplicate code warning with start_write_group; fix before
582
698
        #      considering 'done'.
583
699
        if self._pack_collection._new_pack is not None:
584
 
            raise errors.BzrError('call to create_pack_from_packs while '
585
 
                'another pack is being written.')
 
700
            raise errors.BzrError('call to %s.pack() while another pack is'
 
701
                                  ' being written.'
 
702
                                  % (self.__class__.__name__,))
586
703
        if self.revision_ids is not None:
587
704
            if len(self.revision_ids) == 0:
588
705
                # silly fetch request.
603
720
 
604
721
    def open_pack(self):
605
722
        """Open a pack for the pack we are creating."""
606
 
        return NewPack(self._pack_collection._upload_transport,
607
 
            self._pack_collection._index_transport,
608
 
            self._pack_collection._pack_transport, upload_suffix=self.suffix,
609
 
            file_mode=self._pack_collection.repo.bzrdir._get_file_mode(),
610
 
            index_builder_class=self._pack_collection._index_builder_class,
611
 
            index_class=self._pack_collection._index_class)
 
723
        new_pack = self._pack_collection.pack_factory(self._pack_collection,
 
724
                upload_suffix=self.suffix,
 
725
                file_mode=self._pack_collection.repo.bzrdir._get_file_mode())
 
726
        # We know that we will process all nodes in order, and don't need to
 
727
        # query, so don't combine any indices spilled to disk until we are done
 
728
        new_pack.revision_index.set_optimize(combine_backing_indices=False)
 
729
        new_pack.inventory_index.set_optimize(combine_backing_indices=False)
 
730
        new_pack.text_index.set_optimize(combine_backing_indices=False)
 
731
        new_pack.signature_index.set_optimize(combine_backing_indices=False)
 
732
        return new_pack
612
733
 
613
734
    def _copy_revision_texts(self):
614
735
        """Copy revision data to the new pack."""
615
 
        # select revisions
616
 
        if self.revision_ids:
617
 
            revision_keys = [(revision_id,) for revision_id in self.revision_ids]
618
 
        else:
619
 
            revision_keys = None
620
 
        # select revision keys
621
 
        revision_index_map = self._pack_collection._packs_list_to_pack_map_and_index_list(
622
 
            self.packs, 'revision_index')[0]
623
 
        revision_nodes = self._pack_collection._index_contents(revision_index_map, revision_keys)
624
 
        # copy revision keys and adjust values
625
 
        self.pb.update("Copying revision texts", 1)
626
 
        total_items, readv_group_iter = self._revision_node_readv(revision_nodes)
627
 
        list(self._copy_nodes_graph(revision_index_map, self.new_pack._writer,
628
 
            self.new_pack.revision_index, readv_group_iter, total_items))
629
 
        if 'pack' in debug.debug_flags:
630
 
            mutter('%s: create_pack: revisions copied: %s%s %d items t+%6.3fs',
631
 
                time.ctime(), self._pack_collection._upload_transport.base,
632
 
                self.new_pack.random_name,
633
 
                self.new_pack.revision_index.key_count(),
634
 
                time.time() - self.new_pack.start_time)
635
 
        self._revision_keys = revision_keys
 
736
        raise NotImplementedError(self._copy_revision_texts)
636
737
 
637
738
    def _copy_inventory_texts(self):
638
739
        """Copy the inventory texts to the new pack.
641
742
 
642
743
        Sets self._text_filter appropriately.
643
744
        """
644
 
        # select inventory keys
645
 
        inv_keys = self._revision_keys # currently the same keyspace, and note that
646
 
        # querying for keys here could introduce a bug where an inventory item
647
 
        # is missed, so do not change it to query separately without cross
648
 
        # checking like the text key check below.
649
 
        inventory_index_map = self._pack_collection._packs_list_to_pack_map_and_index_list(
650
 
            self.packs, 'inventory_index')[0]
651
 
        inv_nodes = self._pack_collection._index_contents(inventory_index_map, inv_keys)
652
 
        # copy inventory keys and adjust values
653
 
        # XXX: Should be a helper function to allow different inv representation
654
 
        # at this point.
655
 
        self.pb.update("Copying inventory texts", 2)
656
 
        total_items, readv_group_iter = self._least_readv_node_readv(inv_nodes)
657
 
        # Only grab the output lines if we will be processing them
658
 
        output_lines = bool(self.revision_ids)
659
 
        inv_lines = self._copy_nodes_graph(inventory_index_map,
660
 
            self.new_pack._writer, self.new_pack.inventory_index,
661
 
            readv_group_iter, total_items, output_lines=output_lines)
662
 
        if self.revision_ids:
663
 
            self._process_inventory_lines(inv_lines)
664
 
        else:
665
 
            # eat the iterator to cause it to execute.
666
 
            list(inv_lines)
667
 
            self._text_filter = None
668
 
        if 'pack' in debug.debug_flags:
669
 
            mutter('%s: create_pack: inventories copied: %s%s %d items t+%6.3fs',
670
 
                time.ctime(), self._pack_collection._upload_transport.base,
671
 
                self.new_pack.random_name,
672
 
                self.new_pack.inventory_index.key_count(),
673
 
                time.time() - self.new_pack.start_time)
 
745
        raise NotImplementedError(self._copy_inventory_texts)
674
746
 
675
747
    def _copy_text_texts(self):
676
 
        # select text keys
677
 
        text_index_map, text_nodes = self._get_text_nodes()
678
 
        if self._text_filter is not None:
679
 
            # We could return the keys copied as part of the return value from
680
 
            # _copy_nodes_graph but this doesn't work all that well with the
681
 
            # need to get line output too, so we check separately, and as we're
682
 
            # going to buffer everything anyway, we check beforehand, which
683
 
            # saves reading knit data over the wire when we know there are
684
 
            # mising records.
685
 
            text_nodes = set(text_nodes)
686
 
            present_text_keys = set(_node[1] for _node in text_nodes)
687
 
            missing_text_keys = set(self._text_filter) - present_text_keys
688
 
            if missing_text_keys:
689
 
                # TODO: raise a specific error that can handle many missing
690
 
                # keys.
691
 
                a_missing_key = missing_text_keys.pop()
692
 
                raise errors.RevisionNotPresent(a_missing_key[1],
693
 
                    a_missing_key[0])
694
 
        # copy text keys and adjust values
695
 
        self.pb.update("Copying content texts", 3)
696
 
        total_items, readv_group_iter = self._least_readv_node_readv(text_nodes)
697
 
        list(self._copy_nodes_graph(text_index_map, self.new_pack._writer,
698
 
            self.new_pack.text_index, readv_group_iter, total_items))
699
 
        self._log_copied_texts()
700
 
 
701
 
    def _check_references(self):
702
 
        """Make sure our external refereneces are present."""
703
 
        external_refs = self.new_pack._external_compression_parents_of_texts()
704
 
        if external_refs:
705
 
            index = self._pack_collection.text_index.combined_index
706
 
            found_items = list(index.iter_entries(external_refs))
707
 
            if len(found_items) != len(external_refs):
708
 
                found_keys = set(k for idx, k, refs, value in found_items)
709
 
                missing_items = external_refs - found_keys
710
 
                missing_file_id, missing_revision_id = missing_items.pop()
711
 
                raise errors.RevisionNotPresent(missing_revision_id,
712
 
                                                missing_file_id)
 
748
        raise NotImplementedError(self._copy_text_texts)
713
749
 
714
750
    def _create_pack_from_packs(self):
715
 
        self.pb.update("Opening pack", 0, 5)
716
 
        self.new_pack = self.open_pack()
717
 
        new_pack = self.new_pack
718
 
        # buffer data - we won't be reading-back during the pack creation and
719
 
        # this makes a significant difference on sftp pushes.
720
 
        new_pack.set_write_cache_size(1024*1024)
721
 
        if 'pack' in debug.debug_flags:
722
 
            plain_pack_list = ['%s%s' % (a_pack.pack_transport.base, a_pack.name)
723
 
                for a_pack in self.packs]
724
 
            if self.revision_ids is not None:
725
 
                rev_count = len(self.revision_ids)
726
 
            else:
727
 
                rev_count = 'all'
728
 
            mutter('%s: create_pack: creating pack from source packs: '
729
 
                '%s%s %s revisions wanted %s t=0',
730
 
                time.ctime(), self._pack_collection._upload_transport.base, new_pack.random_name,
731
 
                plain_pack_list, rev_count)
732
 
        self._copy_revision_texts()
733
 
        self._copy_inventory_texts()
734
 
        self._copy_text_texts()
735
 
        # select signature keys
736
 
        signature_filter = self._revision_keys # same keyspace
737
 
        signature_index_map = self._pack_collection._packs_list_to_pack_map_and_index_list(
738
 
            self.packs, 'signature_index')[0]
739
 
        signature_nodes = self._pack_collection._index_contents(signature_index_map,
740
 
            signature_filter)
741
 
        # copy signature keys and adjust values
742
 
        self.pb.update("Copying signature texts", 4)
743
 
        self._copy_nodes(signature_nodes, signature_index_map, new_pack._writer,
744
 
            new_pack.signature_index)
745
 
        if 'pack' in debug.debug_flags:
746
 
            mutter('%s: create_pack: revision signatures copied: %s%s %d items t+%6.3fs',
747
 
                time.ctime(), self._pack_collection._upload_transport.base, new_pack.random_name,
748
 
                new_pack.signature_index.key_count(),
749
 
                time.time() - new_pack.start_time)
750
 
        self._check_references()
751
 
        if not self._use_pack(new_pack):
752
 
            new_pack.abort()
753
 
            return None
754
 
        self.pb.update("Finishing pack", 5)
755
 
        new_pack.finish()
756
 
        self._pack_collection.allocate(new_pack)
757
 
        return new_pack
758
 
 
759
 
    def _copy_nodes(self, nodes, index_map, writer, write_index):
760
 
        """Copy knit nodes between packs with no graph references."""
761
 
        pb = ui.ui_factory.nested_progress_bar()
762
 
        try:
763
 
            return self._do_copy_nodes(nodes, index_map, writer,
764
 
                write_index, pb)
765
 
        finally:
766
 
            pb.finished()
767
 
 
768
 
    def _do_copy_nodes(self, nodes, index_map, writer, write_index, pb):
769
 
        # for record verification
770
 
        knit = KnitVersionedFiles(None, None)
771
 
        # plan a readv on each source pack:
772
 
        # group by pack
773
 
        nodes = sorted(nodes)
774
 
        # how to map this into knit.py - or knit.py into this?
775
 
        # we don't want the typical knit logic, we want grouping by pack
776
 
        # at this point - perhaps a helper library for the following code 
777
 
        # duplication points?
778
 
        request_groups = {}
779
 
        for index, key, value in nodes:
780
 
            if index not in request_groups:
781
 
                request_groups[index] = []
782
 
            request_groups[index].append((key, value))
783
 
        record_index = 0
784
 
        pb.update("Copied record", record_index, len(nodes))
785
 
        for index, items in request_groups.iteritems():
786
 
            pack_readv_requests = []
787
 
            for key, value in items:
788
 
                # ---- KnitGraphIndex.get_position
789
 
                bits = value[1:].split(' ')
790
 
                offset, length = int(bits[0]), int(bits[1])
791
 
                pack_readv_requests.append((offset, length, (key, value[0])))
792
 
            # linear scan up the pack
793
 
            pack_readv_requests.sort()
794
 
            # copy the data
795
 
            transport, path = index_map[index]
796
 
            reader = pack.make_readv_reader(transport, path,
797
 
                [offset[0:2] for offset in pack_readv_requests])
798
 
            for (names, read_func), (_1, _2, (key, eol_flag)) in \
799
 
                izip(reader.iter_records(), pack_readv_requests):
800
 
                raw_data = read_func(None)
801
 
                # check the header only
802
 
                df, _ = knit._parse_record_header(key, raw_data)
803
 
                df.close()
804
 
                pos, size = writer.add_bytes_record(raw_data, names)
805
 
                write_index.add_node(key, eol_flag + "%d %d" % (pos, size))
806
 
                pb.update("Copied record", record_index)
807
 
                record_index += 1
808
 
 
809
 
    def _copy_nodes_graph(self, index_map, writer, write_index,
810
 
        readv_group_iter, total_items, output_lines=False):
811
 
        """Copy knit nodes between packs.
812
 
 
813
 
        :param output_lines: Return lines present in the copied data as
814
 
            an iterator of line,version_id.
815
 
        """
816
 
        pb = ui.ui_factory.nested_progress_bar()
817
 
        try:
818
 
            for result in self._do_copy_nodes_graph(index_map, writer,
819
 
                write_index, output_lines, pb, readv_group_iter, total_items):
820
 
                yield result
821
 
        except Exception:
822
 
            # Python 2.4 does not permit try:finally: in a generator.
823
 
            pb.finished()
824
 
            raise
825
 
        else:
826
 
            pb.finished()
827
 
 
828
 
    def _do_copy_nodes_graph(self, index_map, writer, write_index,
829
 
        output_lines, pb, readv_group_iter, total_items):
830
 
        # for record verification
831
 
        knit = KnitVersionedFiles(None, None)
832
 
        # for line extraction when requested (inventories only)
833
 
        if output_lines:
834
 
            factory = KnitPlainFactory()
835
 
        record_index = 0
836
 
        pb.update("Copied record", record_index, total_items)
837
 
        for index, readv_vector, node_vector in readv_group_iter:
838
 
            # copy the data
839
 
            transport, path = index_map[index]
840
 
            reader = pack.make_readv_reader(transport, path, readv_vector)
841
 
            for (names, read_func), (key, eol_flag, references) in \
842
 
                izip(reader.iter_records(), node_vector):
843
 
                raw_data = read_func(None)
844
 
                if output_lines:
845
 
                    # read the entire thing
846
 
                    content, _ = knit._parse_record(key[-1], raw_data)
847
 
                    if len(references[-1]) == 0:
848
 
                        line_iterator = factory.get_fulltext_content(content)
849
 
                    else:
850
 
                        line_iterator = factory.get_linedelta_content(content)
851
 
                    for line in line_iterator:
852
 
                        yield line, key
853
 
                else:
854
 
                    # check the header only
855
 
                    df, _ = knit._parse_record_header(key, raw_data)
856
 
                    df.close()
857
 
                pos, size = writer.add_bytes_record(raw_data, names)
858
 
                write_index.add_node(key, eol_flag + "%d %d" % (pos, size), references)
859
 
                pb.update("Copied record", record_index)
860
 
                record_index += 1
861
 
 
862
 
    def _get_text_nodes(self):
863
 
        text_index_map = self._pack_collection._packs_list_to_pack_map_and_index_list(
864
 
            self.packs, 'text_index')[0]
865
 
        return text_index_map, self._pack_collection._index_contents(text_index_map,
866
 
            self._text_filter)
867
 
 
868
 
    def _least_readv_node_readv(self, nodes):
869
 
        """Generate request groups for nodes using the least readv's.
870
 
        
871
 
        :param nodes: An iterable of graph index nodes.
872
 
        :return: Total node count and an iterator of the data needed to perform
873
 
            readvs to obtain the data for nodes. Each item yielded by the
874
 
            iterator is a tuple with:
875
 
            index, readv_vector, node_vector. readv_vector is a list ready to
876
 
            hand to the transport readv method, and node_vector is a list of
877
 
            (key, eol_flag, references) for the the node retrieved by the
878
 
            matching readv_vector.
879
 
        """
880
 
        # group by pack so we do one readv per pack
881
 
        nodes = sorted(nodes)
882
 
        total = len(nodes)
883
 
        request_groups = {}
884
 
        for index, key, value, references in nodes:
885
 
            if index not in request_groups:
886
 
                request_groups[index] = []
887
 
            request_groups[index].append((key, value, references))
888
 
        result = []
889
 
        for index, items in request_groups.iteritems():
890
 
            pack_readv_requests = []
891
 
            for key, value, references in items:
892
 
                # ---- KnitGraphIndex.get_position
893
 
                bits = value[1:].split(' ')
894
 
                offset, length = int(bits[0]), int(bits[1])
895
 
                pack_readv_requests.append(
896
 
                    ((offset, length), (key, value[0], references)))
897
 
            # linear scan up the pack to maximum range combining.
898
 
            pack_readv_requests.sort()
899
 
            # split out the readv and the node data.
900
 
            pack_readv = [readv for readv, node in pack_readv_requests]
901
 
            node_vector = [node for readv, node in pack_readv_requests]
902
 
            result.append((index, pack_readv, node_vector))
903
 
        return total, result
 
751
        raise NotImplementedError(self._create_pack_from_packs)
904
752
 
905
753
    def _log_copied_texts(self):
906
754
        if 'pack' in debug.debug_flags:
910
758
                self.new_pack.text_index.key_count(),
911
759
                time.time() - self.new_pack.start_time)
912
760
 
913
 
    def _process_inventory_lines(self, inv_lines):
914
 
        """Use up the inv_lines generator and setup a text key filter."""
915
 
        repo = self._pack_collection.repo
916
 
        fileid_revisions = repo._find_file_ids_from_xml_inventory_lines(
917
 
            inv_lines, self.revision_keys)
918
 
        text_filter = []
919
 
        for fileid, file_revids in fileid_revisions.iteritems():
920
 
            text_filter.extend([(fileid, file_revid) for file_revid in file_revids])
921
 
        self._text_filter = text_filter
922
 
 
923
 
    def _revision_node_readv(self, revision_nodes):
924
 
        """Return the total revisions and the readv's to issue.
925
 
 
926
 
        :param revision_nodes: The revision index contents for the packs being
927
 
            incorporated into the new pack.
928
 
        :return: As per _least_readv_node_readv.
929
 
        """
930
 
        return self._least_readv_node_readv(revision_nodes)
931
 
 
932
761
    def _use_pack(self, new_pack):
933
762
        """Return True if new_pack should be used.
934
763
 
938
767
        return new_pack.data_inserted()
939
768
 
940
769
 
941
 
class OptimisingPacker(Packer):
942
 
    """A packer which spends more time to create better disk layouts."""
943
 
 
944
 
    def _revision_node_readv(self, revision_nodes):
945
 
        """Return the total revisions and the readv's to issue.
946
 
 
947
 
        This sort places revisions in topological order with the ancestors
948
 
        after the children.
949
 
 
950
 
        :param revision_nodes: The revision index contents for the packs being
951
 
            incorporated into the new pack.
952
 
        :return: As per _least_readv_node_readv.
953
 
        """
954
 
        # build an ancestors dict
955
 
        ancestors = {}
956
 
        by_key = {}
957
 
        for index, key, value, references in revision_nodes:
958
 
            ancestors[key] = references[0]
959
 
            by_key[key] = (index, value, references)
960
 
        order = tsort.topo_sort(ancestors)
961
 
        total = len(order)
962
 
        # Single IO is pathological, but it will work as a starting point.
963
 
        requests = []
964
 
        for key in reversed(order):
965
 
            index, value, references = by_key[key]
966
 
            # ---- KnitGraphIndex.get_position
967
 
            bits = value[1:].split(' ')
968
 
            offset, length = int(bits[0]), int(bits[1])
969
 
            requests.append(
970
 
                (index, [(offset, length)], [(key, value[0], references)]))
971
 
        # TODO: combine requests in the same index that are in ascending order.
972
 
        return total, requests
973
 
 
974
 
 
975
 
class ReconcilePacker(Packer):
976
 
    """A packer which regenerates indices etc as it copies.
977
 
    
978
 
    This is used by ``bzr reconcile`` to cause parent text pointers to be
979
 
    regenerated.
980
 
    """
981
 
 
982
 
    def _extra_init(self):
983
 
        self._data_changed = False
984
 
 
985
 
    def _process_inventory_lines(self, inv_lines):
986
 
        """Generate a text key reference map rather for reconciling with."""
987
 
        repo = self._pack_collection.repo
988
 
        refs = repo._find_text_key_references_from_xml_inventory_lines(
989
 
            inv_lines)
990
 
        self._text_refs = refs
991
 
        # during reconcile we:
992
 
        #  - convert unreferenced texts to full texts
993
 
        #  - correct texts which reference a text not copied to be full texts
994
 
        #  - copy all others as-is but with corrected parents.
995
 
        #  - so at this point we don't know enough to decide what becomes a full
996
 
        #    text.
997
 
        self._text_filter = None
998
 
 
999
 
    def _copy_text_texts(self):
1000
 
        """generate what texts we should have and then copy."""
1001
 
        self.pb.update("Copying content texts", 3)
1002
 
        # we have three major tasks here:
1003
 
        # 1) generate the ideal index
1004
 
        repo = self._pack_collection.repo
1005
 
        ancestors = dict([(key[0], tuple(ref[0] for ref in refs[0])) for
1006
 
            _1, key, _2, refs in 
1007
 
            self.new_pack.revision_index.iter_all_entries()])
1008
 
        ideal_index = repo._generate_text_key_index(self._text_refs, ancestors)
1009
 
        # 2) generate a text_nodes list that contains all the deltas that can
1010
 
        #    be used as-is, with corrected parents.
1011
 
        ok_nodes = []
1012
 
        bad_texts = []
1013
 
        discarded_nodes = []
1014
 
        NULL_REVISION = _mod_revision.NULL_REVISION
1015
 
        text_index_map, text_nodes = self._get_text_nodes()
1016
 
        for node in text_nodes:
1017
 
            # 0 - index
1018
 
            # 1 - key 
1019
 
            # 2 - value
1020
 
            # 3 - refs
1021
 
            try:
1022
 
                ideal_parents = tuple(ideal_index[node[1]])
1023
 
            except KeyError:
1024
 
                discarded_nodes.append(node)
1025
 
                self._data_changed = True
1026
 
            else:
1027
 
                if ideal_parents == (NULL_REVISION,):
1028
 
                    ideal_parents = ()
1029
 
                if ideal_parents == node[3][0]:
1030
 
                    # no change needed.
1031
 
                    ok_nodes.append(node)
1032
 
                elif ideal_parents[0:1] == node[3][0][0:1]:
1033
 
                    # the left most parent is the same, or there are no parents
1034
 
                    # today. Either way, we can preserve the representation as
1035
 
                    # long as we change the refs to be inserted.
1036
 
                    self._data_changed = True
1037
 
                    ok_nodes.append((node[0], node[1], node[2],
1038
 
                        (ideal_parents, node[3][1])))
1039
 
                    self._data_changed = True
1040
 
                else:
1041
 
                    # Reinsert this text completely
1042
 
                    bad_texts.append((node[1], ideal_parents))
1043
 
                    self._data_changed = True
1044
 
        # we're finished with some data.
1045
 
        del ideal_index
1046
 
        del text_nodes
1047
 
        # 3) bulk copy the ok data
1048
 
        total_items, readv_group_iter = self._least_readv_node_readv(ok_nodes)
1049
 
        list(self._copy_nodes_graph(text_index_map, self.new_pack._writer,
1050
 
            self.new_pack.text_index, readv_group_iter, total_items))
1051
 
        # 4) adhoc copy all the other texts.
1052
 
        # We have to topologically insert all texts otherwise we can fail to
1053
 
        # reconcile when parts of a single delta chain are preserved intact,
1054
 
        # and other parts are not. E.g. Discarded->d1->d2->d3. d1 will be
1055
 
        # reinserted, and if d3 has incorrect parents it will also be
1056
 
        # reinserted. If we insert d3 first, d2 is present (as it was bulk
1057
 
        # copied), so we will try to delta, but d2 is not currently able to be
1058
 
        # extracted because it's basis d1 is not present. Topologically sorting
1059
 
        # addresses this. The following generates a sort for all the texts that
1060
 
        # are being inserted without having to reference the entire text key
1061
 
        # space (we only topo sort the revisions, which is smaller).
1062
 
        topo_order = tsort.topo_sort(ancestors)
1063
 
        rev_order = dict(zip(topo_order, range(len(topo_order))))
1064
 
        bad_texts.sort(key=lambda key:rev_order[key[0][1]])
1065
 
        transaction = repo.get_transaction()
1066
 
        file_id_index = GraphIndexPrefixAdapter(
1067
 
            self.new_pack.text_index,
1068
 
            ('blank', ), 1,
1069
 
            add_nodes_callback=self.new_pack.text_index.add_nodes)
1070
 
        data_access = _DirectPackAccess(
1071
 
                {self.new_pack.text_index:self.new_pack.access_tuple()})
1072
 
        data_access.set_writer(self.new_pack._writer, self.new_pack.text_index,
1073
 
            self.new_pack.access_tuple())
1074
 
        output_texts = KnitVersionedFiles(
1075
 
            _KnitGraphIndex(self.new_pack.text_index,
1076
 
                add_callback=self.new_pack.text_index.add_nodes,
1077
 
                deltas=True, parents=True, is_locked=repo.is_locked),
1078
 
            data_access=data_access, max_delta_chain=200)
1079
 
        for key, parent_keys in bad_texts:
1080
 
            # We refer to the new pack to delta data being output.
1081
 
            # A possible improvement would be to catch errors on short reads
1082
 
            # and only flush then.
1083
 
            self.new_pack.flush()
1084
 
            parents = []
1085
 
            for parent_key in parent_keys:
1086
 
                if parent_key[0] != key[0]:
1087
 
                    # Graph parents must match the fileid
1088
 
                    raise errors.BzrError('Mismatched key parent %r:%r' %
1089
 
                        (key, parent_keys))
1090
 
                parents.append(parent_key[1])
1091
 
            text_lines = osutils.split_lines(repo.texts.get_record_stream(
1092
 
                [key], 'unordered', True).next().get_bytes_as('fulltext'))
1093
 
            output_texts.add_lines(key, parent_keys, text_lines,
1094
 
                random_id=True, check_content=False)
1095
 
        # 5) check that nothing inserted has a reference outside the keyspace.
1096
 
        missing_text_keys = self.new_pack._external_compression_parents_of_texts()
1097
 
        if missing_text_keys:
1098
 
            raise errors.BzrError('Reference to missing compression parents %r'
1099
 
                % (missing_text_keys,))
1100
 
        self._log_copied_texts()
1101
 
 
1102
 
    def _use_pack(self, new_pack):
1103
 
        """Override _use_pack to check for reconcile having changed content."""
1104
 
        # XXX: we might be better checking this at the copy time.
1105
 
        original_inventory_keys = set()
1106
 
        inv_index = self._pack_collection.inventory_index.combined_index
1107
 
        for entry in inv_index.iter_all_entries():
1108
 
            original_inventory_keys.add(entry[1])
1109
 
        new_inventory_keys = set()
1110
 
        for entry in new_pack.inventory_index.iter_all_entries():
1111
 
            new_inventory_keys.add(entry[1])
1112
 
        if new_inventory_keys != original_inventory_keys:
1113
 
            self._data_changed = True
1114
 
        return new_pack.data_inserted() and self._data_changed
1115
 
 
1116
 
 
1117
770
class RepositoryPackCollection(object):
1118
771
    """Management of packs within a repository.
1119
 
    
 
772
 
1120
773
    :ivar _names: map of {pack_name: (index_size,)}
1121
774
    """
1122
775
 
 
776
    pack_factory = None
 
777
    resumed_pack_factory = None
 
778
    normal_packer_class = None
 
779
    optimising_packer_class = None
 
780
 
1123
781
    def __init__(self, repo, transport, index_transport, upload_transport,
1124
 
                 pack_transport, index_builder_class, index_class):
 
782
                 pack_transport, index_builder_class, index_class,
 
783
                 use_chk_index):
1125
784
        """Create a new RepositoryPackCollection.
1126
785
 
1127
 
        :param transport: Addresses the repository base directory 
 
786
        :param transport: Addresses the repository base directory
1128
787
            (typically .bzr/repository/).
1129
788
        :param index_transport: Addresses the directory containing indices.
1130
789
        :param upload_transport: Addresses the directory into which packs are written
1132
791
        :param pack_transport: Addresses the directory of existing complete packs.
1133
792
        :param index_builder_class: The index builder class to use.
1134
793
        :param index_class: The index class to use.
 
794
        :param use_chk_index: Whether to setup and manage a CHK index.
1135
795
        """
 
796
        # XXX: This should call self.reset()
1136
797
        self.repo = repo
1137
798
        self.transport = transport
1138
799
        self._index_transport = index_transport
1140
801
        self._pack_transport = pack_transport
1141
802
        self._index_builder_class = index_builder_class
1142
803
        self._index_class = index_class
1143
 
        self._suffix_offsets = {'.rix': 0, '.iix': 1, '.tix': 2, '.six': 3}
 
804
        self._suffix_offsets = {'.rix': 0, '.iix': 1, '.tix': 2, '.six': 3,
 
805
            '.cix': 4}
1144
806
        self.packs = []
1145
807
        # name:Pack mapping
 
808
        self._names = None
1146
809
        self._packs_by_name = {}
1147
810
        # the previous pack-names content
1148
811
        self._packs_at_load = None
1149
812
        # when a pack is being created by this object, the state of that pack.
1150
813
        self._new_pack = None
1151
814
        # aggregated revision index data
1152
 
        self.revision_index = AggregateIndex()
1153
 
        self.inventory_index = AggregateIndex()
1154
 
        self.text_index = AggregateIndex()
1155
 
        self.signature_index = AggregateIndex()
 
815
        flush = self._flush_new_pack
 
816
        self.revision_index = AggregateIndex(self.reload_pack_names, flush)
 
817
        self.inventory_index = AggregateIndex(self.reload_pack_names, flush)
 
818
        self.text_index = AggregateIndex(self.reload_pack_names, flush)
 
819
        self.signature_index = AggregateIndex(self.reload_pack_names, flush)
 
820
        all_indices = [self.revision_index, self.inventory_index,
 
821
                self.text_index, self.signature_index]
 
822
        if use_chk_index:
 
823
            self.chk_index = AggregateIndex(self.reload_pack_names, flush)
 
824
            all_indices.append(self.chk_index)
 
825
        else:
 
826
            # used to determine if we're using a chk_index elsewhere.
 
827
            self.chk_index = None
 
828
        # Tell all the CombinedGraphIndex objects about each other, so they can
 
829
        # share hints about which pack names to search first.
 
830
        all_combined = [agg_idx.combined_index for agg_idx in all_indices]
 
831
        for combined_idx in all_combined:
 
832
            combined_idx.set_sibling_indices(
 
833
                set(all_combined).difference([combined_idx]))
 
834
        # resumed packs
 
835
        self._resumed_packs = []
 
836
        self.config_stack = config.LocationStack(self.transport.base)
 
837
 
 
838
    def __repr__(self):
 
839
        return '%s(%r)' % (self.__class__.__name__, self.repo)
1156
840
 
1157
841
    def add_pack_to_memory(self, pack):
1158
842
        """Make a Pack object available to the repository to satisfy queries.
1159
 
        
 
843
 
1160
844
        :param pack: A Pack object.
1161
845
        """
1162
846
        if pack.name in self._packs_by_name:
1163
 
            raise AssertionError()
 
847
            raise AssertionError(
 
848
                'pack %s already in _packs_by_name' % (pack.name,))
1164
849
        self.packs.append(pack)
1165
850
        self._packs_by_name[pack.name] = pack
1166
851
        self.revision_index.add_index(pack.revision_index, pack)
1167
852
        self.inventory_index.add_index(pack.inventory_index, pack)
1168
853
        self.text_index.add_index(pack.text_index, pack)
1169
854
        self.signature_index.add_index(pack.signature_index, pack)
1170
 
        
 
855
        if self.chk_index is not None:
 
856
            self.chk_index.add_index(pack.chk_index, pack)
 
857
 
1171
858
    def all_packs(self):
1172
859
        """Return a list of all the Pack objects this repository has.
1173
860
 
1182
869
 
1183
870
    def autopack(self):
1184
871
        """Pack the pack collection incrementally.
1185
 
        
 
872
 
1186
873
        This will not attempt global reorganisation or recompression,
1187
874
        rather it will just ensure that the total number of packs does
1188
875
        not grow without bound. It uses the _max_pack_count method to
1194
881
        in synchronisation with certain steps. Otherwise the names collection
1195
882
        is not flushed.
1196
883
 
1197
 
        :return: True if packing took place.
 
884
        :return: Something evaluating true if packing took place.
1198
885
        """
 
886
        while True:
 
887
            try:
 
888
                return self._do_autopack()
 
889
            except errors.RetryAutopack:
 
890
                # If we get a RetryAutopack exception, we should abort the
 
891
                # current action, and retry.
 
892
                pass
 
893
 
 
894
    def _do_autopack(self):
1199
895
        # XXX: Should not be needed when the management of indices is sane.
1200
896
        total_revisions = self.revision_index.combined_index.key_count()
1201
897
        total_packs = len(self._names)
1202
898
        if self._max_pack_count(total_revisions) >= total_packs:
1203
 
            return False
1204
 
        # XXX: the following may want to be a class, to pack with a given
1205
 
        # policy.
1206
 
        mutter('Auto-packing repository %s, which has %d pack files, '
1207
 
            'containing %d revisions into %d packs.', self, total_packs,
1208
 
            total_revisions, self._max_pack_count(total_revisions))
 
899
            return None
1209
900
        # determine which packs need changing
1210
901
        pack_distribution = self.pack_distribution(total_revisions)
1211
902
        existing_packs = []
1219
910
                # group their data with the relevant commit, and that may
1220
911
                # involve rewriting ancient history - which autopack tries to
1221
912
                # avoid. Alternatively we could not group the data but treat
1222
 
                # each of these as having a single revision, and thus add 
 
913
                # each of these as having a single revision, and thus add
1223
914
                # one revision for each to the total revision count, to get
1224
915
                # a matching distribution.
1225
916
                continue
1226
917
            existing_packs.append((revision_count, pack))
1227
918
        pack_operations = self.plan_autopack_combinations(
1228
919
            existing_packs, pack_distribution)
1229
 
        self._execute_pack_operations(pack_operations)
1230
 
        return True
 
920
        num_new_packs = len(pack_operations)
 
921
        num_old_packs = sum([len(po[1]) for po in pack_operations])
 
922
        num_revs_affected = sum([po[0] for po in pack_operations])
 
923
        mutter('Auto-packing repository %s, which has %d pack files, '
 
924
            'containing %d revisions. Packing %d files into %d affecting %d'
 
925
            ' revisions', self, total_packs, total_revisions, num_old_packs,
 
926
            num_new_packs, num_revs_affected)
 
927
        result = self._execute_pack_operations(pack_operations, packer_class=self.normal_packer_class,
 
928
                                      reload_func=self._restart_autopack)
 
929
        mutter('Auto-packing repository %s completed', self)
 
930
        return result
1231
931
 
1232
 
    def _execute_pack_operations(self, pack_operations, _packer_class=Packer):
 
932
    def _execute_pack_operations(self, pack_operations, packer_class,
 
933
            reload_func=None):
1233
934
        """Execute a series of pack operations.
1234
935
 
1235
936
        :param pack_operations: A list of [revision_count, packs_to_combine].
1236
 
        :param _packer_class: The class of packer to use (default: Packer).
1237
 
        :return: None.
 
937
        :param packer_class: The class of packer to use
 
938
        :return: The new pack names.
1238
939
        """
1239
940
        for revision_count, packs in pack_operations:
1240
941
            # we may have no-ops from the setup logic
1241
942
            if len(packs) == 0:
1242
943
                continue
1243
 
            _packer_class(self, packs, '.autopack').pack()
 
944
            packer = packer_class(self, packs, '.autopack',
 
945
                                   reload_func=reload_func)
 
946
            try:
 
947
                result = packer.pack()
 
948
            except errors.RetryWithNewPacks:
 
949
                # An exception is propagating out of this context, make sure
 
950
                # this packer has cleaned up. Packer() doesn't set its new_pack
 
951
                # state into the RepositoryPackCollection object, so we only
 
952
                # have access to it directly here.
 
953
                if packer.new_pack is not None:
 
954
                    packer.new_pack.abort()
 
955
                raise
 
956
            if result is None:
 
957
                return
1244
958
            for pack in packs:
1245
959
                self._remove_pack_from_memory(pack)
1246
960
        # record the newly available packs and stop advertising the old
1247
961
        # packs
1248
 
        self._save_pack_names(clear_obsolete_packs=True)
1249
 
        # Move the old packs out of the way now they are no longer referenced.
1250
 
        for revision_count, packs in pack_operations:
1251
 
            self._obsolete_packs(packs)
 
962
        to_be_obsoleted = []
 
963
        for _, packs in pack_operations:
 
964
            to_be_obsoleted.extend(packs)
 
965
        result = self._save_pack_names(clear_obsolete_packs=True,
 
966
                                       obsolete_packs=to_be_obsoleted)
 
967
        return result
 
968
 
 
969
    def _flush_new_pack(self):
 
970
        if self._new_pack is not None:
 
971
            self._new_pack.flush()
1252
972
 
1253
973
    def lock_names(self):
1254
974
        """Acquire the mutex around the pack-names index.
1255
 
        
 
975
 
1256
976
        This cannot be used in the middle of a read-only transaction on the
1257
977
        repository.
1258
978
        """
1259
979
        self.repo.control_files.lock_write()
1260
980
 
1261
 
    def pack(self):
 
981
    def _already_packed(self):
 
982
        """Is the collection already packed?"""
 
983
        return not (self.repo._format.pack_compresses or (len(self._names) > 1))
 
984
 
 
985
    def pack(self, hint=None, clean_obsolete_packs=False):
1262
986
        """Pack the pack collection totally."""
1263
987
        self.ensure_loaded()
1264
988
        total_packs = len(self._names)
1265
 
        if total_packs < 2:
1266
 
            # This is arguably wrong because we might not be optimal, but for
1267
 
            # now lets leave it in. (e.g. reconcile -> one pack. But not
1268
 
            # optimal.
 
989
        if self._already_packed():
1269
990
            return
1270
991
        total_revisions = self.revision_index.combined_index.key_count()
1271
992
        # XXX: the following may want to be a class, to pack with a given
1272
993
        # policy.
1273
994
        mutter('Packing repository %s, which has %d pack files, '
1274
 
            'containing %d revisions into 1 packs.', self, total_packs,
1275
 
            total_revisions)
 
995
            'containing %d revisions with hint %r.', self, total_packs,
 
996
            total_revisions, hint)
 
997
        while True:
 
998
            try:
 
999
                self._try_pack_operations(hint)
 
1000
            except RetryPackOperations:
 
1001
                continue
 
1002
            break
 
1003
 
 
1004
        if clean_obsolete_packs:
 
1005
            self._clear_obsolete_packs()
 
1006
 
 
1007
    def _try_pack_operations(self, hint):
 
1008
        """Calculate the pack operations based on the hint (if any), and
 
1009
        execute them.
 
1010
        """
1276
1011
        # determine which packs need changing
1277
 
        pack_distribution = [1]
1278
1012
        pack_operations = [[0, []]]
1279
1013
        for pack in self.all_packs():
1280
 
            pack_operations[-1][0] += pack.get_revision_count()
1281
 
            pack_operations[-1][1].append(pack)
1282
 
        self._execute_pack_operations(pack_operations, OptimisingPacker)
 
1014
            if hint is None or pack.name in hint:
 
1015
                # Either no hint was provided (so we are packing everything),
 
1016
                # or this pack was included in the hint.
 
1017
                pack_operations[-1][0] += pack.get_revision_count()
 
1018
                pack_operations[-1][1].append(pack)
 
1019
        self._execute_pack_operations(pack_operations,
 
1020
            packer_class=self.optimising_packer_class,
 
1021
            reload_func=self._restart_pack_operations)
1283
1022
 
1284
1023
    def plan_autopack_combinations(self, existing_packs, pack_distribution):
1285
1024
        """Plan a pack operation.
1295
1034
        pack_operations = [[0, []]]
1296
1035
        # plan out what packs to keep, and what to reorganise
1297
1036
        while len(existing_packs):
1298
 
            # take the largest pack, and if its less than the head of the
 
1037
            # take the largest pack, and if it's less than the head of the
1299
1038
            # distribution chart we will include its contents in the new pack
1300
 
            # for that position. If its larger, we remove its size from the
 
1039
            # for that position. If it's larger, we remove its size from the
1301
1040
            # distribution chart
1302
1041
            next_pack_rev_count, next_pack = existing_packs.pop(0)
1303
1042
            if next_pack_rev_count >= pack_distribution[0]:
1334
1073
        return [[final_rev_count, final_pack_list]]
1335
1074
 
1336
1075
    def ensure_loaded(self):
1337
 
        # NB: if you see an assertion error here, its probably access against
 
1076
        """Ensure we have read names from disk.
 
1077
 
 
1078
        :return: True if the disk names had not been previously read.
 
1079
        """
 
1080
        # NB: if you see an assertion error here, it's probably access against
1338
1081
        # an unlocked repo. Naughty.
1339
1082
        if not self.repo.is_locked():
1340
1083
            raise errors.ObjectNotLocked(self.repo)
1345
1088
                name = key[0]
1346
1089
                self._names[name] = self._parse_index_sizes(value)
1347
1090
                self._packs_at_load.add((key, value))
 
1091
            result = True
 
1092
        else:
 
1093
            result = False
1348
1094
        # populate all the metadata.
1349
1095
        self.all_packs()
 
1096
        return result
1350
1097
 
1351
1098
    def _parse_index_sizes(self, value):
1352
1099
        """Parse a string of index sizes."""
1365
1112
            inv_index = self._make_index(name, '.iix')
1366
1113
            txt_index = self._make_index(name, '.tix')
1367
1114
            sig_index = self._make_index(name, '.six')
 
1115
            if self.chk_index is not None:
 
1116
                chk_index = self._make_index(name, '.cix', is_chk=True)
 
1117
            else:
 
1118
                chk_index = None
1368
1119
            result = ExistingPack(self._pack_transport, name, rev_index,
1369
 
                inv_index, txt_index, sig_index)
 
1120
                inv_index, txt_index, sig_index, chk_index)
1370
1121
            self.add_pack_to_memory(result)
1371
1122
            return result
1372
1123
 
 
1124
    def _resume_pack(self, name):
 
1125
        """Get a suspended Pack object by name.
 
1126
 
 
1127
        :param name: The name of the pack - e.g. '123456'
 
1128
        :return: A Pack object.
 
1129
        """
 
1130
        if not re.match('[a-f0-9]{32}', name):
 
1131
            # Tokens should be md5sums of the suspended pack file, i.e. 32 hex
 
1132
            # digits.
 
1133
            raise errors.UnresumableWriteGroup(
 
1134
                self.repo, [name], 'Malformed write group token')
 
1135
        try:
 
1136
            rev_index = self._make_index(name, '.rix', resume=True)
 
1137
            inv_index = self._make_index(name, '.iix', resume=True)
 
1138
            txt_index = self._make_index(name, '.tix', resume=True)
 
1139
            sig_index = self._make_index(name, '.six', resume=True)
 
1140
            if self.chk_index is not None:
 
1141
                chk_index = self._make_index(name, '.cix', resume=True,
 
1142
                                             is_chk=True)
 
1143
            else:
 
1144
                chk_index = None
 
1145
            result = self.resumed_pack_factory(name, rev_index, inv_index,
 
1146
                txt_index, sig_index, self._upload_transport,
 
1147
                self._pack_transport, self._index_transport, self,
 
1148
                chk_index=chk_index)
 
1149
        except errors.NoSuchFile, e:
 
1150
            raise errors.UnresumableWriteGroup(self.repo, [name], str(e))
 
1151
        self.add_pack_to_memory(result)
 
1152
        self._resumed_packs.append(result)
 
1153
        return result
 
1154
 
1373
1155
    def allocate(self, a_new_pack):
1374
1156
        """Allocate name in the list of packs.
1375
1157
 
1385
1167
 
1386
1168
    def _iter_disk_pack_index(self):
1387
1169
        """Iterate over the contents of the pack-names index.
1388
 
        
 
1170
 
1389
1171
        This is used when loading the list from disk, and before writing to
1390
1172
        detect updates from others during our write operation.
1391
1173
        :return: An iterator of the index contents.
1393
1175
        return self._index_class(self.transport, 'pack-names', None
1394
1176
                ).iter_all_entries()
1395
1177
 
1396
 
    def _make_index(self, name, suffix):
 
1178
    def _make_index(self, name, suffix, resume=False, is_chk=False):
1397
1179
        size_offset = self._suffix_offsets[suffix]
1398
1180
        index_name = name + suffix
1399
 
        index_size = self._names[name][size_offset]
1400
 
        return self._index_class(
1401
 
            self._index_transport, index_name, index_size)
 
1181
        if resume:
 
1182
            transport = self._upload_transport
 
1183
            index_size = transport.stat(index_name).st_size
 
1184
        else:
 
1185
            transport = self._index_transport
 
1186
            index_size = self._names[name][size_offset]
 
1187
        index = self._index_class(transport, index_name, index_size,
 
1188
                                  unlimited_cache=is_chk)
 
1189
        if is_chk and self._index_class is btree_index.BTreeGraphIndex: 
 
1190
            index._leaf_factory = btree_index._gcchk_factory
 
1191
        return index
1402
1192
 
1403
1193
    def _max_pack_count(self, total_revisions):
1404
1194
        """Return the maximum number of packs to use for total revisions.
1405
 
        
 
1195
 
1406
1196
        :param total_revisions: The total number of revisions in the
1407
1197
            repository.
1408
1198
        """
1432
1222
        :param return: None.
1433
1223
        """
1434
1224
        for pack in packs:
1435
 
            pack.pack_transport.rename(pack.file_name(),
1436
 
                '../obsolete_packs/' + pack.file_name())
 
1225
            try:
 
1226
                try:
 
1227
                    pack.pack_transport.move(pack.file_name(),
 
1228
                        '../obsolete_packs/' + pack.file_name())
 
1229
                except errors.NoSuchFile:
 
1230
                    # perhaps obsolete_packs was removed? Let's create it and
 
1231
                    # try again
 
1232
                    try:
 
1233
                        pack.pack_transport.mkdir('../obsolete_packs/')
 
1234
                    except errors.FileExists:
 
1235
                        pass
 
1236
                    pack.pack_transport.move(pack.file_name(),
 
1237
                        '../obsolete_packs/' + pack.file_name())
 
1238
            except (errors.PathError, errors.TransportError), e:
 
1239
                # TODO: Should these be warnings or mutters?
 
1240
                mutter("couldn't rename obsolete pack, skipping it:\n%s"
 
1241
                       % (e,))
1437
1242
            # TODO: Probably needs to know all possible indices for this pack
1438
1243
            # - or maybe list the directory and move all indices matching this
1439
1244
            # name whether we recognize it or not?
1440
 
            for suffix in ('.iix', '.six', '.tix', '.rix'):
1441
 
                self._index_transport.rename(pack.name + suffix,
1442
 
                    '../obsolete_packs/' + pack.name + suffix)
 
1245
            suffixes = ['.iix', '.six', '.tix', '.rix']
 
1246
            if self.chk_index is not None:
 
1247
                suffixes.append('.cix')
 
1248
            for suffix in suffixes:
 
1249
                try:
 
1250
                    self._index_transport.move(pack.name + suffix,
 
1251
                        '../obsolete_packs/' + pack.name + suffix)
 
1252
                except (errors.PathError, errors.TransportError), e:
 
1253
                    mutter("couldn't rename obsolete index, skipping it:\n%s"
 
1254
                           % (e,))
1443
1255
 
1444
1256
    def pack_distribution(self, total_revisions):
1445
1257
        """Generate a list of the number of revisions to put in each pack.
1463
1275
 
1464
1276
    def _remove_pack_from_memory(self, pack):
1465
1277
        """Remove pack from the packs accessed by this repository.
1466
 
        
 
1278
 
1467
1279
        Only affects memory state, until self._save_pack_names() is invoked.
1468
1280
        """
1469
1281
        self._names.pop(pack.name)
1470
1282
        self._packs_by_name.pop(pack.name)
1471
1283
        self._remove_pack_indices(pack)
 
1284
        self.packs.remove(pack)
1472
1285
 
1473
 
    def _remove_pack_indices(self, pack):
1474
 
        """Remove the indices for pack from the aggregated indices."""
1475
 
        self.revision_index.remove_index(pack.revision_index, pack)
1476
 
        self.inventory_index.remove_index(pack.inventory_index, pack)
1477
 
        self.text_index.remove_index(pack.text_index, pack)
1478
 
        self.signature_index.remove_index(pack.signature_index, pack)
 
1286
    def _remove_pack_indices(self, pack, ignore_missing=False):
 
1287
        """Remove the indices for pack from the aggregated indices.
 
1288
        
 
1289
        :param ignore_missing: Suppress KeyErrors from calling remove_index.
 
1290
        """
 
1291
        for index_type in Pack.index_definitions.keys():
 
1292
            attr_name = index_type + '_index'
 
1293
            aggregate_index = getattr(self, attr_name)
 
1294
            if aggregate_index is not None:
 
1295
                pack_index = getattr(pack, attr_name)
 
1296
                try:
 
1297
                    aggregate_index.remove_index(pack_index)
 
1298
                except KeyError:
 
1299
                    if ignore_missing:
 
1300
                        continue
 
1301
                    raise
1479
1302
 
1480
1303
    def reset(self):
1481
1304
        """Clear all cached data."""
1482
1305
        # cached revision data
1483
 
        self.repo._revision_knit = None
1484
1306
        self.revision_index.clear()
1485
1307
        # cached signature data
1486
 
        self.repo._signature_knit = None
1487
1308
        self.signature_index.clear()
1488
1309
        # cached file text data
1489
1310
        self.text_index.clear()
1490
 
        self.repo._text_knit = None
1491
1311
        # cached inventory data
1492
1312
        self.inventory_index.clear()
 
1313
        # cached chk data
 
1314
        if self.chk_index is not None:
 
1315
            self.chk_index.clear()
1493
1316
        # remove the open pack
1494
1317
        self._new_pack = None
1495
1318
        # information about packs.
1498
1321
        self._packs_by_name = {}
1499
1322
        self._packs_at_load = None
1500
1323
 
1501
 
    def _make_index_map(self, index_suffix):
1502
 
        """Return information on existing indices.
1503
 
 
1504
 
        :param suffix: Index suffix added to pack name.
1505
 
 
1506
 
        :returns: (pack_map, indices) where indices is a list of GraphIndex 
1507
 
        objects, and pack_map is a mapping from those objects to the 
1508
 
        pack tuple they describe.
1509
 
        """
1510
 
        # TODO: stop using this; it creates new indices unnecessarily.
1511
 
        self.ensure_loaded()
1512
 
        suffix_map = {'.rix': 'revision_index',
1513
 
            '.six': 'signature_index',
1514
 
            '.iix': 'inventory_index',
1515
 
            '.tix': 'text_index',
1516
 
        }
1517
 
        return self._packs_list_to_pack_map_and_index_list(self.all_packs(),
1518
 
            suffix_map[index_suffix])
1519
 
 
1520
 
    def _packs_list_to_pack_map_and_index_list(self, packs, index_attribute):
1521
 
        """Convert a list of packs to an index pack map and index list.
1522
 
 
1523
 
        :param packs: The packs list to process.
1524
 
        :param index_attribute: The attribute that the desired index is found
1525
 
            on.
1526
 
        :return: A tuple (map, list) where map contains the dict from
1527
 
            index:pack_tuple, and lsit contains the indices in the same order
1528
 
            as the packs list.
1529
 
        """
1530
 
        indices = []
1531
 
        pack_map = {}
1532
 
        for pack in packs:
1533
 
            index = getattr(pack, index_attribute)
1534
 
            indices.append(index)
1535
 
            pack_map[index] = (pack.pack_transport, pack.file_name())
1536
 
        return pack_map, indices
1537
 
 
1538
 
    def _index_contents(self, pack_map, key_filter=None):
1539
 
        """Get an iterable of the index contents from a pack_map.
1540
 
 
1541
 
        :param pack_map: A map from indices to pack details.
1542
 
        :param key_filter: An optional filter to limit the
1543
 
            keys returned.
1544
 
        """
1545
 
        indices = [index for index in pack_map.iterkeys()]
1546
 
        all_index = CombinedGraphIndex(indices)
1547
 
        if key_filter is None:
1548
 
            return all_index.iter_all_entries()
1549
 
        else:
1550
 
            return all_index.iter_entries(key_filter)
1551
 
 
1552
1324
    def _unlock_names(self):
1553
1325
        """Release the mutex around the pack-names index."""
1554
1326
        self.repo.control_files.unlock()
1555
1327
 
1556
 
    def _save_pack_names(self, clear_obsolete_packs=False):
1557
 
        """Save the list of packs.
1558
 
 
1559
 
        This will take out the mutex around the pack names list for the
1560
 
        duration of the method call. If concurrent updates have been made, a
1561
 
        three-way merge between the current list and the current in memory list
1562
 
        is performed.
1563
 
 
1564
 
        :param clear_obsolete_packs: If True, clear out the contents of the
1565
 
            obsolete_packs directory.
1566
 
        """
1567
 
        self.lock_names()
1568
 
        try:
1569
 
            builder = self._index_builder_class()
1570
 
            # load the disk nodes across
1571
 
            disk_nodes = set()
1572
 
            for index, key, value in self._iter_disk_pack_index():
1573
 
                disk_nodes.add((key, value))
1574
 
            # do a two-way diff against our original content
1575
 
            current_nodes = set()
1576
 
            for name, sizes in self._names.iteritems():
1577
 
                current_nodes.add(
1578
 
                    ((name, ), ' '.join(str(size) for size in sizes)))
1579
 
            deleted_nodes = self._packs_at_load - current_nodes
1580
 
            new_nodes = current_nodes - self._packs_at_load
1581
 
            disk_nodes.difference_update(deleted_nodes)
1582
 
            disk_nodes.update(new_nodes)
1583
 
            # TODO: handle same-name, index-size-changes here - 
1584
 
            # e.g. use the value from disk, not ours, *unless* we're the one
1585
 
            # changing it.
1586
 
            for key, value in disk_nodes:
1587
 
                builder.add_node(key, value)
1588
 
            self.transport.put_file('pack-names', builder.finish(),
1589
 
                mode=self.repo.bzrdir._get_file_mode())
1590
 
            # move the baseline forward
1591
 
            self._packs_at_load = disk_nodes
1592
 
            if clear_obsolete_packs:
1593
 
                self._clear_obsolete_packs()
1594
 
        finally:
1595
 
            self._unlock_names()
1596
 
        # synchronise the memory packs list with what we just wrote:
 
1328
    def _diff_pack_names(self):
 
1329
        """Read the pack names from disk, and compare it to the one in memory.
 
1330
 
 
1331
        :return: (disk_nodes, deleted_nodes, new_nodes)
 
1332
            disk_nodes    The final set of nodes that should be referenced
 
1333
            deleted_nodes Nodes which have been removed from when we started
 
1334
            new_nodes     Nodes that are newly introduced
 
1335
        """
 
1336
        # load the disk nodes across
 
1337
        disk_nodes = set()
 
1338
        for index, key, value in self._iter_disk_pack_index():
 
1339
            disk_nodes.add((key, value))
 
1340
        orig_disk_nodes = set(disk_nodes)
 
1341
 
 
1342
        # do a two-way diff against our original content
 
1343
        current_nodes = set()
 
1344
        for name, sizes in self._names.iteritems():
 
1345
            current_nodes.add(
 
1346
                ((name, ), ' '.join(str(size) for size in sizes)))
 
1347
 
 
1348
        # Packs no longer present in the repository, which were present when we
 
1349
        # locked the repository
 
1350
        deleted_nodes = self._packs_at_load - current_nodes
 
1351
        # Packs which this process is adding
 
1352
        new_nodes = current_nodes - self._packs_at_load
 
1353
 
 
1354
        # Update the disk_nodes set to include the ones we are adding, and
 
1355
        # remove the ones which were removed by someone else
 
1356
        disk_nodes.difference_update(deleted_nodes)
 
1357
        disk_nodes.update(new_nodes)
 
1358
 
 
1359
        return disk_nodes, deleted_nodes, new_nodes, orig_disk_nodes
 
1360
 
 
1361
    def _syncronize_pack_names_from_disk_nodes(self, disk_nodes):
 
1362
        """Given the correct set of pack files, update our saved info.
 
1363
 
 
1364
        :return: (removed, added, modified)
 
1365
            removed     pack names removed from self._names
 
1366
            added       pack names added to self._names
 
1367
            modified    pack names that had changed value
 
1368
        """
 
1369
        removed = []
 
1370
        added = []
 
1371
        modified = []
 
1372
        ## self._packs_at_load = disk_nodes
1597
1373
        new_names = dict(disk_nodes)
1598
1374
        # drop no longer present nodes
1599
1375
        for pack in self.all_packs():
1600
1376
            if (pack.name,) not in new_names:
 
1377
                removed.append(pack.name)
1601
1378
                self._remove_pack_from_memory(pack)
1602
1379
        # add new nodes/refresh existing ones
1603
1380
        for key, value in disk_nodes:
1613
1390
                    # disk index because the set values are the same, unless
1614
1391
                    # the only index shows up as deleted by the set difference
1615
1392
                    # - which it may. Until there is a specific test for this,
1616
 
                    # assume its broken. RBC 20071017.
 
1393
                    # assume it's broken. RBC 20071017.
1617
1394
                    self._remove_pack_from_memory(self.get_pack_by_name(name))
1618
1395
                    self._names[name] = sizes
1619
1396
                    self.get_pack_by_name(name)
 
1397
                    modified.append(name)
1620
1398
            else:
1621
1399
                # new
1622
1400
                self._names[name] = sizes
1623
1401
                self.get_pack_by_name(name)
1624
 
 
1625
 
    def _clear_obsolete_packs(self):
 
1402
                added.append(name)
 
1403
        return removed, added, modified
 
1404
 
 
1405
    def _save_pack_names(self, clear_obsolete_packs=False, obsolete_packs=None):
 
1406
        """Save the list of packs.
 
1407
 
 
1408
        This will take out the mutex around the pack names list for the
 
1409
        duration of the method call. If concurrent updates have been made, a
 
1410
        three-way merge between the current list and the current in memory list
 
1411
        is performed.
 
1412
 
 
1413
        :param clear_obsolete_packs: If True, clear out the contents of the
 
1414
            obsolete_packs directory.
 
1415
        :param obsolete_packs: Packs that are obsolete once the new pack-names
 
1416
            file has been written.
 
1417
        :return: A list of the names saved that were not previously on disk.
 
1418
        """
 
1419
        already_obsolete = []
 
1420
        self.lock_names()
 
1421
        try:
 
1422
            builder = self._index_builder_class()
 
1423
            (disk_nodes, deleted_nodes, new_nodes,
 
1424
             orig_disk_nodes) = self._diff_pack_names()
 
1425
            # TODO: handle same-name, index-size-changes here -
 
1426
            # e.g. use the value from disk, not ours, *unless* we're the one
 
1427
            # changing it.
 
1428
            for key, value in disk_nodes:
 
1429
                builder.add_node(key, value)
 
1430
            self.transport.put_file('pack-names', builder.finish(),
 
1431
                mode=self.repo.bzrdir._get_file_mode())
 
1432
            self._packs_at_load = disk_nodes
 
1433
            if clear_obsolete_packs:
 
1434
                to_preserve = None
 
1435
                if obsolete_packs:
 
1436
                    to_preserve = set([o.name for o in obsolete_packs])
 
1437
                already_obsolete = self._clear_obsolete_packs(to_preserve)
 
1438
        finally:
 
1439
            self._unlock_names()
 
1440
        # synchronise the memory packs list with what we just wrote:
 
1441
        self._syncronize_pack_names_from_disk_nodes(disk_nodes)
 
1442
        if obsolete_packs:
 
1443
            # TODO: We could add one more condition here. "if o.name not in
 
1444
            #       orig_disk_nodes and o != the new_pack we haven't written to
 
1445
            #       disk yet. However, the new pack object is not easily
 
1446
            #       accessible here (it would have to be passed through the
 
1447
            #       autopacking code, etc.)
 
1448
            obsolete_packs = [o for o in obsolete_packs
 
1449
                              if o.name not in already_obsolete]
 
1450
            self._obsolete_packs(obsolete_packs)
 
1451
        return [new_node[0][0] for new_node in new_nodes]
 
1452
 
 
1453
    def reload_pack_names(self):
 
1454
        """Sync our pack listing with what is present in the repository.
 
1455
 
 
1456
        This should be called when we find out that something we thought was
 
1457
        present is now missing. This happens when another process re-packs the
 
1458
        repository, etc.
 
1459
 
 
1460
        :return: True if the in-memory list of packs has been altered at all.
 
1461
        """
 
1462
        # The ensure_loaded call is to handle the case where the first call
 
1463
        # made involving the collection was to reload_pack_names, where we 
 
1464
        # don't have a view of disk contents. It's a bit of a bandaid, and
 
1465
        # causes two reads of pack-names, but it's a rare corner case not
 
1466
        # struck with regular push/pull etc.
 
1467
        first_read = self.ensure_loaded()
 
1468
        if first_read:
 
1469
            return True
 
1470
        # out the new value.
 
1471
        (disk_nodes, deleted_nodes, new_nodes,
 
1472
         orig_disk_nodes) = self._diff_pack_names()
 
1473
        # _packs_at_load is meant to be the explicit list of names in
 
1474
        # 'pack-names' at then start. As such, it should not contain any
 
1475
        # pending names that haven't been written out yet.
 
1476
        self._packs_at_load = orig_disk_nodes
 
1477
        (removed, added,
 
1478
         modified) = self._syncronize_pack_names_from_disk_nodes(disk_nodes)
 
1479
        if removed or added or modified:
 
1480
            return True
 
1481
        return False
 
1482
 
 
1483
    def _restart_autopack(self):
 
1484
        """Reload the pack names list, and restart the autopack code."""
 
1485
        if not self.reload_pack_names():
 
1486
            # Re-raise the original exception, because something went missing
 
1487
            # and a restart didn't find it
 
1488
            raise
 
1489
        raise errors.RetryAutopack(self.repo, False, sys.exc_info())
 
1490
 
 
1491
    def _restart_pack_operations(self):
 
1492
        """Reload the pack names list, and restart the autopack code."""
 
1493
        if not self.reload_pack_names():
 
1494
            # Re-raise the original exception, because something went missing
 
1495
            # and a restart didn't find it
 
1496
            raise
 
1497
        raise RetryPackOperations(self.repo, False, sys.exc_info())
 
1498
 
 
1499
    def _clear_obsolete_packs(self, preserve=None):
1626
1500
        """Delete everything from the obsolete-packs directory.
 
1501
 
 
1502
        :return: A list of pack identifiers (the filename without '.pack') that
 
1503
            were found in obsolete_packs.
1627
1504
        """
 
1505
        found = []
1628
1506
        obsolete_pack_transport = self.transport.clone('obsolete_packs')
1629
 
        for filename in obsolete_pack_transport.list_dir('.'):
 
1507
        if preserve is None:
 
1508
            preserve = set()
 
1509
        try:
 
1510
            obsolete_pack_files = obsolete_pack_transport.list_dir('.')
 
1511
        except errors.NoSuchFile:
 
1512
            return found
 
1513
        for filename in obsolete_pack_files:
 
1514
            name, ext = osutils.splitext(filename)
 
1515
            if ext == '.pack':
 
1516
                found.append(name)
 
1517
            if name in preserve:
 
1518
                continue
1630
1519
            try:
1631
1520
                obsolete_pack_transport.delete(filename)
1632
1521
            except (errors.PathError, errors.TransportError), e:
1633
 
                warning("couldn't delete obsolete pack, skipping it:\n%s" % (e,))
 
1522
                warning("couldn't delete obsolete pack, skipping it:\n%s"
 
1523
                        % (e,))
 
1524
        return found
1634
1525
 
1635
1526
    def _start_write_group(self):
1636
1527
        # Do not permit preparation for writing if we're not in a 'write lock'.
1637
1528
        if not self.repo.is_write_locked():
1638
1529
            raise errors.NotWriteLocked(self)
1639
 
        self._new_pack = NewPack(self._upload_transport, self._index_transport,
1640
 
            self._pack_transport, upload_suffix='.pack',
1641
 
            file_mode=self.repo.bzrdir._get_file_mode(),
1642
 
            index_builder_class=self._index_builder_class,
1643
 
            index_class=self._index_class)
 
1530
        self._new_pack = self.pack_factory(self, upload_suffix='.pack',
 
1531
            file_mode=self.repo.bzrdir._get_file_mode())
1644
1532
        # allow writing: queue writes to a new index
1645
1533
        self.revision_index.add_writable_index(self._new_pack.revision_index,
1646
1534
            self._new_pack)
1648
1536
            self._new_pack)
1649
1537
        self.text_index.add_writable_index(self._new_pack.text_index,
1650
1538
            self._new_pack)
 
1539
        self._new_pack.text_index.set_optimize(combine_backing_indices=False)
1651
1540
        self.signature_index.add_writable_index(self._new_pack.signature_index,
1652
1541
            self._new_pack)
 
1542
        if self.chk_index is not None:
 
1543
            self.chk_index.add_writable_index(self._new_pack.chk_index,
 
1544
                self._new_pack)
 
1545
            self.repo.chk_bytes._index._add_callback = self.chk_index.add_callback
 
1546
            self._new_pack.chk_index.set_optimize(combine_backing_indices=False)
1653
1547
 
1654
1548
        self.repo.inventories._index._add_callback = self.inventory_index.add_callback
1655
1549
        self.repo.revisions._index._add_callback = self.revision_index.add_callback
1660
1554
        # FIXME: just drop the transient index.
1661
1555
        # forget what names there are
1662
1556
        if self._new_pack is not None:
1663
 
            self._new_pack.abort()
1664
 
            self._remove_pack_indices(self._new_pack)
1665
 
            self._new_pack = None
1666
 
        self.repo._text_knit = None
1667
 
 
 
1557
            operation = cleanup.OperationWithCleanups(self._new_pack.abort)
 
1558
            operation.add_cleanup(setattr, self, '_new_pack', None)
 
1559
            # If we aborted while in the middle of finishing the write
 
1560
            # group, _remove_pack_indices could fail because the indexes are
 
1561
            # already gone.  But they're not there we shouldn't fail in this
 
1562
            # case, so we pass ignore_missing=True.
 
1563
            operation.add_cleanup(self._remove_pack_indices, self._new_pack,
 
1564
                ignore_missing=True)
 
1565
            operation.run_simple()
 
1566
        for resumed_pack in self._resumed_packs:
 
1567
            operation = cleanup.OperationWithCleanups(resumed_pack.abort)
 
1568
            # See comment in previous finally block.
 
1569
            operation.add_cleanup(self._remove_pack_indices, resumed_pack,
 
1570
                ignore_missing=True)
 
1571
            operation.run_simple()
 
1572
        del self._resumed_packs[:]
 
1573
 
 
1574
    def _remove_resumed_pack_indices(self):
 
1575
        for resumed_pack in self._resumed_packs:
 
1576
            self._remove_pack_indices(resumed_pack)
 
1577
        del self._resumed_packs[:]
 
1578
 
 
1579
    def _check_new_inventories(self):
 
1580
        """Detect missing inventories in this write group.
 
1581
 
 
1582
        :returns: list of strs, summarising any problems found.  If the list is
 
1583
            empty no problems were found.
 
1584
        """
 
1585
        # The base implementation does no checks.  GCRepositoryPackCollection
 
1586
        # overrides this.
 
1587
        return []
 
1588
        
1668
1589
    def _commit_write_group(self):
 
1590
        all_missing = set()
 
1591
        for prefix, versioned_file in (
 
1592
                ('revisions', self.repo.revisions),
 
1593
                ('inventories', self.repo.inventories),
 
1594
                ('texts', self.repo.texts),
 
1595
                ('signatures', self.repo.signatures),
 
1596
                ):
 
1597
            missing = versioned_file.get_missing_compression_parent_keys()
 
1598
            all_missing.update([(prefix,) + key for key in missing])
 
1599
        if all_missing:
 
1600
            raise errors.BzrCheckError(
 
1601
                "Repository %s has missing compression parent(s) %r "
 
1602
                 % (self.repo, sorted(all_missing)))
 
1603
        problems = self._check_new_inventories()
 
1604
        if problems:
 
1605
            problems_summary = '\n'.join(problems)
 
1606
            raise errors.BzrCheckError(
 
1607
                "Cannot add revision(s) to repository: " + problems_summary)
1669
1608
        self._remove_pack_indices(self._new_pack)
 
1609
        any_new_content = False
1670
1610
        if self._new_pack.data_inserted():
1671
1611
            # get all the data to disk and read to use
1672
1612
            self._new_pack.finish()
1673
1613
            self.allocate(self._new_pack)
1674
1614
            self._new_pack = None
1675
 
            if not self.autopack():
 
1615
            any_new_content = True
 
1616
        else:
 
1617
            self._new_pack.abort()
 
1618
            self._new_pack = None
 
1619
        for resumed_pack in self._resumed_packs:
 
1620
            # XXX: this is a pretty ugly way to turn the resumed pack into a
 
1621
            # properly committed pack.
 
1622
            self._names[resumed_pack.name] = None
 
1623
            self._remove_pack_from_memory(resumed_pack)
 
1624
            resumed_pack.finish()
 
1625
            self.allocate(resumed_pack)
 
1626
            any_new_content = True
 
1627
        del self._resumed_packs[:]
 
1628
        if any_new_content:
 
1629
            result = self.autopack()
 
1630
            if not result:
1676
1631
                # when autopack takes no steps, the names list is still
1677
1632
                # unsaved.
1678
 
                self._save_pack_names()
 
1633
                return self._save_pack_names()
 
1634
            return result
 
1635
        return []
 
1636
 
 
1637
    def _suspend_write_group(self):
 
1638
        tokens = [pack.name for pack in self._resumed_packs]
 
1639
        self._remove_pack_indices(self._new_pack)
 
1640
        if self._new_pack.data_inserted():
 
1641
            # get all the data to disk and read to use
 
1642
            self._new_pack.finish(suspend=True)
 
1643
            tokens.append(self._new_pack.name)
 
1644
            self._new_pack = None
1679
1645
        else:
1680
1646
            self._new_pack.abort()
1681
1647
            self._new_pack = None
1682
 
        self.repo._text_knit = None
1683
 
 
1684
 
 
1685
 
class KnitPackRepository(KnitRepository):
 
1648
        self._remove_resumed_pack_indices()
 
1649
        return tokens
 
1650
 
 
1651
    def _resume_write_group(self, tokens):
 
1652
        for token in tokens:
 
1653
            self._resume_pack(token)
 
1654
 
 
1655
 
 
1656
class PackRepository(MetaDirVersionedFileRepository):
1686
1657
    """Repository with knit objects stored inside pack containers.
1687
 
    
 
1658
 
1688
1659
    The layering for a KnitPackRepository is:
1689
1660
 
1690
1661
    Graph        |  HPSS    | Repository public layer |
1691
1662
    ===================================================
1692
1663
    Tuple based apis below, string based, and key based apis above
1693
1664
    ---------------------------------------------------
1694
 
    KnitVersionedFiles
 
1665
    VersionedFiles
1695
1666
      Provides .texts, .revisions etc
1696
1667
      This adapts the N-tuple keys to physical knit records which only have a
1697
1668
      single string identifier (for historical reasons), which in older formats
1704
1675
      pack file. The GraphIndex layer works in N-tuples and is unaware of any
1705
1676
      semantic value.
1706
1677
    ===================================================
1707
 
    
 
1678
 
1708
1679
    """
1709
1680
 
 
1681
    # These attributes are inherited from the Repository base class. Setting
 
1682
    # them to None ensures that if the constructor is changed to not initialize
 
1683
    # them, or a subclass fails to call the constructor, that an error will
 
1684
    # occur rather than the system working but generating incorrect data.
 
1685
    _commit_builder_class = None
 
1686
    _serializer = None
 
1687
 
1710
1688
    def __init__(self, _format, a_bzrdir, control_files, _commit_builder_class,
1711
1689
        _serializer):
1712
 
        KnitRepository.__init__(self, _format, a_bzrdir, control_files,
1713
 
            _commit_builder_class, _serializer)
1714
 
        index_transport = self._transport.clone('indices')
1715
 
        self._pack_collection = RepositoryPackCollection(self, self._transport,
1716
 
            index_transport,
1717
 
            self._transport.clone('upload'),
1718
 
            self._transport.clone('packs'),
1719
 
            _format.index_builder_class,
1720
 
            _format.index_class)
1721
 
        self.inventories = KnitVersionedFiles(
1722
 
            _KnitGraphIndex(self._pack_collection.inventory_index.combined_index,
1723
 
                add_callback=self._pack_collection.inventory_index.add_callback,
1724
 
                deltas=True, parents=True, is_locked=self.is_locked),
1725
 
            data_access=self._pack_collection.inventory_index.data_access,
1726
 
            max_delta_chain=200)
1727
 
        self.revisions = KnitVersionedFiles(
1728
 
            _KnitGraphIndex(self._pack_collection.revision_index.combined_index,
1729
 
                add_callback=self._pack_collection.revision_index.add_callback,
1730
 
                deltas=False, parents=True, is_locked=self.is_locked),
1731
 
            data_access=self._pack_collection.revision_index.data_access,
1732
 
            max_delta_chain=0)
1733
 
        self.signatures = KnitVersionedFiles(
1734
 
            _KnitGraphIndex(self._pack_collection.signature_index.combined_index,
1735
 
                add_callback=self._pack_collection.signature_index.add_callback,
1736
 
                deltas=False, parents=False, is_locked=self.is_locked),
1737
 
            data_access=self._pack_collection.signature_index.data_access,
1738
 
            max_delta_chain=0)
1739
 
        self.texts = KnitVersionedFiles(
1740
 
            _KnitGraphIndex(self._pack_collection.text_index.combined_index,
1741
 
                add_callback=self._pack_collection.text_index.add_callback,
1742
 
                deltas=True, parents=True, is_locked=self.is_locked),
1743
 
            data_access=self._pack_collection.text_index.data_access,
1744
 
            max_delta_chain=200)
1745
 
        # True when the repository object is 'write locked' (as opposed to the
1746
 
        # physical lock only taken out around changes to the pack-names list.) 
1747
 
        # Another way to represent this would be a decorator around the control
1748
 
        # files object that presents logical locks as physical ones - if this
1749
 
        # gets ugly consider that alternative design. RBC 20071011
1750
 
        self._write_lock_count = 0
1751
 
        self._transaction = None
1752
 
        # for tests
1753
 
        self._reconcile_does_inventory_gc = True
 
1690
        MetaDirRepository.__init__(self, _format, a_bzrdir, control_files)
 
1691
        self._commit_builder_class = _commit_builder_class
 
1692
        self._serializer = _serializer
1754
1693
        self._reconcile_fixes_text_parents = True
1755
 
        self._reconcile_backsup_inventory = False
1756
 
        self._fetch_order = 'unordered'
 
1694
        if self._format.supports_external_lookups:
 
1695
            self._unstacked_provider = graph.CachingParentsProvider(
 
1696
                self._make_parents_provider_unstacked())
 
1697
        else:
 
1698
            self._unstacked_provider = graph.CachingParentsProvider(self)
 
1699
        self._unstacked_provider.disable_cache()
1757
1700
 
1758
 
    def _warn_if_deprecated(self):
1759
 
        # This class isn't deprecated, but one sub-format is
1760
 
        if isinstance(self._format, RepositoryFormatKnitPack5RichRootBroken):
1761
 
            from bzrlib import repository
1762
 
            if repository._deprecation_warning_done:
1763
 
                return
1764
 
            repository._deprecation_warning_done = True
1765
 
            warning("Format %s for %s is deprecated - please use"
1766
 
                    " 'bzr upgrade --1.6.1-rich-root'"
1767
 
                    % (self._format, self.bzrdir.transport.base))
 
1701
    @needs_read_lock
 
1702
    def _all_revision_ids(self):
 
1703
        """See Repository.all_revision_ids()."""
 
1704
        return [key[0] for key in self.revisions.keys()]
1768
1705
 
1769
1706
    def _abort_write_group(self):
 
1707
        self.revisions._index._key_dependencies.clear()
1770
1708
        self._pack_collection._abort_write_group()
1771
1709
 
1772
 
    def _find_inconsistent_revision_parents(self):
1773
 
        """Find revisions with incorrectly cached parents.
1774
 
 
1775
 
        :returns: an iterator yielding tuples of (revison-id, parents-in-index,
1776
 
            parents-in-revision).
1777
 
        """
1778
 
        if not self.is_locked():
1779
 
            raise errors.ObjectNotLocked(self)
1780
 
        pb = ui.ui_factory.nested_progress_bar()
1781
 
        result = []
1782
 
        try:
1783
 
            revision_nodes = self._pack_collection.revision_index \
1784
 
                .combined_index.iter_all_entries()
1785
 
            index_positions = []
1786
 
            # Get the cached index values for all revisions, and also the location
1787
 
            # in each index of the revision text so we can perform linear IO.
1788
 
            for index, key, value, refs in revision_nodes:
1789
 
                pos, length = value[1:].split(' ')
1790
 
                index_positions.append((index, int(pos), key[0],
1791
 
                    tuple(parent[0] for parent in refs[0])))
1792
 
                pb.update("Reading revision index.", 0, 0)
1793
 
            index_positions.sort()
1794
 
            batch_count = len(index_positions) / 1000 + 1
1795
 
            pb.update("Checking cached revision graph.", 0, batch_count)
1796
 
            for offset in xrange(batch_count):
1797
 
                pb.update("Checking cached revision graph.", offset)
1798
 
                to_query = index_positions[offset * 1000:(offset + 1) * 1000]
1799
 
                if not to_query:
1800
 
                    break
1801
 
                rev_ids = [item[2] for item in to_query]
1802
 
                revs = self.get_revisions(rev_ids)
1803
 
                for revision, item in zip(revs, to_query):
1804
 
                    index_parents = item[3]
1805
 
                    rev_parents = tuple(revision.parent_ids)
1806
 
                    if index_parents != rev_parents:
1807
 
                        result.append((revision.revision_id, index_parents, rev_parents))
1808
 
        finally:
1809
 
            pb.finished()
1810
 
        return result
1811
 
 
1812
 
    @symbol_versioning.deprecated_method(symbol_versioning.one_one)
1813
 
    def get_parents(self, revision_ids):
1814
 
        """See graph._StackedParentsProvider.get_parents."""
1815
 
        parent_map = self.get_parent_map(revision_ids)
1816
 
        return [parent_map.get(r, None) for r in revision_ids]
1817
 
 
1818
1710
    def _make_parents_provider(self):
1819
 
        return graph.CachingParentsProvider(self)
 
1711
        if not self._format.supports_external_lookups:
 
1712
            return self._unstacked_provider
 
1713
        return graph.StackedParentsProvider(_LazyListJoin(
 
1714
            [self._unstacked_provider], self._fallback_repositories))
1820
1715
 
1821
1716
    def _refresh_data(self):
1822
 
        if self._write_lock_count == 1 or (
1823
 
            self.control_files._lock_count == 1 and
1824
 
            self.control_files._lock_mode == 'r'):
1825
 
            # forget what names there are
1826
 
            self._pack_collection.reset()
1827
 
            # XXX: Better to do an in-memory merge when acquiring a new lock -
1828
 
            # factor out code from _save_pack_names.
1829
 
            self._pack_collection.ensure_loaded()
 
1717
        if not self.is_locked():
 
1718
            return
 
1719
        self._pack_collection.reload_pack_names()
 
1720
        self._unstacked_provider.disable_cache()
 
1721
        self._unstacked_provider.enable_cache()
1830
1722
 
1831
1723
    def _start_write_group(self):
1832
1724
        self._pack_collection._start_write_group()
1833
1725
 
1834
1726
    def _commit_write_group(self):
1835
 
        return self._pack_collection._commit_write_group()
 
1727
        hint = self._pack_collection._commit_write_group()
 
1728
        self.revisions._index._key_dependencies.clear()
 
1729
        # The commit may have added keys that were previously cached as
 
1730
        # missing, so reset the cache.
 
1731
        self._unstacked_provider.disable_cache()
 
1732
        self._unstacked_provider.enable_cache()
 
1733
        return hint
 
1734
 
 
1735
    def suspend_write_group(self):
 
1736
        # XXX check self._write_group is self.get_transaction()?
 
1737
        tokens = self._pack_collection._suspend_write_group()
 
1738
        self.revisions._index._key_dependencies.clear()
 
1739
        self._write_group = None
 
1740
        return tokens
 
1741
 
 
1742
    def _resume_write_group(self, tokens):
 
1743
        self._start_write_group()
 
1744
        try:
 
1745
            self._pack_collection._resume_write_group(tokens)
 
1746
        except errors.UnresumableWriteGroup:
 
1747
            self._abort_write_group()
 
1748
            raise
 
1749
        for pack in self._pack_collection._resumed_packs:
 
1750
            self.revisions._index.scan_unvalidated_index(pack.revision_index)
1836
1751
 
1837
1752
    def get_transaction(self):
1838
1753
        if self._write_lock_count:
1847
1762
        return self._write_lock_count
1848
1763
 
1849
1764
    def lock_write(self, token=None):
1850
 
        if not self._write_lock_count and self.is_locked():
 
1765
        """Lock the repository for writes.
 
1766
 
 
1767
        :return: A bzrlib.repository.RepositoryWriteLockResult.
 
1768
        """
 
1769
        locked = self.is_locked()
 
1770
        if not self._write_lock_count and locked:
1851
1771
            raise errors.ReadOnlyError(self)
1852
1772
        self._write_lock_count += 1
1853
1773
        if self._write_lock_count == 1:
1854
1774
            self._transaction = transactions.WriteTransaction()
 
1775
        if not locked:
 
1776
            if 'relock' in debug.debug_flags and self._prev_lock == 'w':
 
1777
                note('%r was write locked again', self)
 
1778
            self._prev_lock = 'w'
 
1779
            self._unstacked_provider.enable_cache()
1855
1780
            for repo in self._fallback_repositories:
1856
1781
                # Writes don't affect fallback repos
1857
1782
                repo.lock_read()
1858
 
        self._refresh_data()
 
1783
            self._refresh_data()
 
1784
        return RepositoryWriteLockResult(self.unlock, None)
1859
1785
 
1860
1786
    def lock_read(self):
 
1787
        """Lock the repository for reads.
 
1788
 
 
1789
        :return: A bzrlib.lock.LogicalLockResult.
 
1790
        """
 
1791
        locked = self.is_locked()
1861
1792
        if self._write_lock_count:
1862
1793
            self._write_lock_count += 1
1863
1794
        else:
1864
1795
            self.control_files.lock_read()
 
1796
        if not locked:
 
1797
            if 'relock' in debug.debug_flags and self._prev_lock == 'r':
 
1798
                note('%r was read locked again', self)
 
1799
            self._prev_lock = 'r'
 
1800
            self._unstacked_provider.enable_cache()
1865
1801
            for repo in self._fallback_repositories:
1866
 
                # Writes don't affect fallback repos
1867
1802
                repo.lock_read()
1868
 
        self._refresh_data()
 
1803
            self._refresh_data()
 
1804
        return LogicalLockResult(self.unlock)
1869
1805
 
1870
1806
    def leave_lock_in_place(self):
1871
1807
        # not supported - raise an error
1876
1812
        raise NotImplementedError(self.dont_leave_lock_in_place)
1877
1813
 
1878
1814
    @needs_write_lock
1879
 
    def pack(self):
 
1815
    def pack(self, hint=None, clean_obsolete_packs=False):
1880
1816
        """Compress the data within the repository.
1881
1817
 
1882
1818
        This will pack all the data to a single pack. In future it may
1883
1819
        recompress deltas or do other such expensive operations.
1884
1820
        """
1885
 
        self._pack_collection.pack()
 
1821
        self._pack_collection.pack(hint=hint, clean_obsolete_packs=clean_obsolete_packs)
1886
1822
 
1887
1823
    @needs_write_lock
1888
1824
    def reconcile(self, other=None, thorough=False):
1892
1828
        reconciler.reconcile()
1893
1829
        return reconciler
1894
1830
 
 
1831
    def _reconcile_pack(self, collection, packs, extension, revs, pb):
 
1832
        raise NotImplementedError(self._reconcile_pack)
 
1833
 
 
1834
    @only_raises(errors.LockNotHeld, errors.LockBroken)
1895
1835
    def unlock(self):
1896
1836
        if self._write_lock_count == 1 and self._write_group is not None:
1897
1837
            self.abort_write_group()
 
1838
            self._unstacked_provider.disable_cache()
1898
1839
            self._transaction = None
1899
1840
            self._write_lock_count = 0
1900
1841
            raise errors.BzrError(
1906
1847
                transaction = self._transaction
1907
1848
                self._transaction = None
1908
1849
                transaction.finish()
1909
 
                for repo in self._fallback_repositories:
1910
 
                    repo.unlock()
1911
1850
        else:
1912
1851
            self.control_files.unlock()
 
1852
 
 
1853
        if not self.is_locked():
 
1854
            self._unstacked_provider.disable_cache()
1913
1855
            for repo in self._fallback_repositories:
1914
1856
                repo.unlock()
1915
1857
 
1916
1858
 
1917
 
class RepositoryFormatPack(MetaDirRepositoryFormat):
 
1859
class RepositoryFormatPack(MetaDirVersionedFileRepositoryFormat):
1918
1860
    """Format logic for pack structured repositories.
1919
1861
 
1920
1862
    This repository format has:
1939
1881
    # Set this attribute in derived clases to control the _serializer that the
1940
1882
    # repository objects will have passed to their constructor.
1941
1883
    _serializer = None
 
1884
    # Packs are not confused by ghosts.
 
1885
    supports_ghosts = True
1942
1886
    # External references are not supported in pack repositories yet.
1943
1887
    supports_external_lookups = False
 
1888
    # Most pack formats do not use chk lookups.
 
1889
    supports_chks = False
1944
1890
    # What index classes to use
1945
1891
    index_builder_class = None
1946
1892
    index_class = None
 
1893
    _fetch_uses_deltas = True
 
1894
    fast_deltas = False
 
1895
    supports_funky_characters = True
 
1896
    revision_graph_can_have_wrong_parents = True
1947
1897
 
1948
1898
    def initialize(self, a_bzrdir, shared=False):
1949
1899
        """Create a pack based repository.
1958
1908
        builder = self.index_builder_class()
1959
1909
        files = [('pack-names', builder.finish())]
1960
1910
        utf8_files = [('format', self.get_format_string())]
1961
 
        
 
1911
 
1962
1912
        self._upload_blank_content(a_bzrdir, dirs, files, utf8_files, shared)
1963
 
        return self.open(a_bzrdir=a_bzrdir, _found=True)
 
1913
        repository = self.open(a_bzrdir=a_bzrdir, _found=True)
 
1914
        self._run_post_repo_init_hooks(repository, a_bzrdir, shared)
 
1915
        return repository
1964
1916
 
1965
1917
    def open(self, a_bzrdir, _found=False, _override_transport=None):
1966
1918
        """See RepositoryFormat.open().
1967
 
        
 
1919
 
1968
1920
        :param _override_transport: INTERNAL USE ONLY. Allows opening the
1969
1921
                                    repository at a slightly different url
1970
1922
                                    than normal. I.e. during 'upgrade'.
1971
1923
        """
1972
1924
        if not _found:
1973
 
            format = RepositoryFormat.find_format(a_bzrdir)
 
1925
            format = RepositoryFormatMetaDir.find_format(a_bzrdir)
1974
1926
        if _override_transport is not None:
1975
1927
            repo_transport = _override_transport
1976
1928
        else:
1984
1936
                              _serializer=self._serializer)
1985
1937
 
1986
1938
 
1987
 
class RepositoryFormatKnitPack1(RepositoryFormatPack):
1988
 
    """A no-subtrees parameterized Pack repository.
1989
 
 
1990
 
    This format was introduced in 0.92.
1991
 
    """
1992
 
 
1993
 
    repository_class = KnitPackRepository
1994
 
    _commit_builder_class = PackCommitBuilder
1995
 
    @property
1996
 
    def _serializer(self):
1997
 
        return xml5.serializer_v5
1998
 
    # What index classes to use
1999
 
    index_builder_class = InMemoryGraphIndex
2000
 
    index_class = GraphIndex
2001
 
 
2002
 
    def _get_matching_bzrdir(self):
2003
 
        return bzrdir.format_registry.make_bzrdir('pack-0.92')
2004
 
 
2005
 
    def _ignore_setting_bzrdir(self, format):
2006
 
        pass
2007
 
 
2008
 
    _matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
2009
 
 
2010
 
    def get_format_string(self):
2011
 
        """See RepositoryFormat.get_format_string()."""
2012
 
        return "Bazaar pack repository format 1 (needs bzr 0.92)\n"
2013
 
 
2014
 
    def get_format_description(self):
2015
 
        """See RepositoryFormat.get_format_description()."""
2016
 
        return "Packs containing knits without subtree support"
2017
 
 
2018
 
    def check_conversion_target(self, target_format):
2019
 
        pass
2020
 
 
2021
 
 
2022
 
class RepositoryFormatKnitPack3(RepositoryFormatPack):
2023
 
    """A subtrees parameterized Pack repository.
2024
 
 
2025
 
    This repository format uses the xml7 serializer to get:
2026
 
     - support for recording full info about the tree root
2027
 
     - support for recording tree-references
2028
 
 
2029
 
    This format was introduced in 0.92.
2030
 
    """
2031
 
 
2032
 
    repository_class = KnitPackRepository
2033
 
    _commit_builder_class = PackRootCommitBuilder
2034
 
    rich_root_data = True
2035
 
    supports_tree_reference = True
2036
 
    @property
2037
 
    def _serializer(self):
2038
 
        return xml7.serializer_v7
2039
 
    # What index classes to use
2040
 
    index_builder_class = InMemoryGraphIndex
2041
 
    index_class = GraphIndex
2042
 
 
2043
 
    def _get_matching_bzrdir(self):
2044
 
        return bzrdir.format_registry.make_bzrdir(
2045
 
            'pack-0.92-subtree')
2046
 
 
2047
 
    def _ignore_setting_bzrdir(self, format):
2048
 
        pass
2049
 
 
2050
 
    _matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
2051
 
 
2052
 
    def check_conversion_target(self, target_format):
2053
 
        if not target_format.rich_root_data:
2054
 
            raise errors.BadConversionTarget(
2055
 
                'Does not support rich root data.', target_format)
2056
 
        if not getattr(target_format, 'supports_tree_reference', False):
2057
 
            raise errors.BadConversionTarget(
2058
 
                'Does not support nested trees', target_format)
2059
 
            
2060
 
    def get_format_string(self):
2061
 
        """See RepositoryFormat.get_format_string()."""
2062
 
        return "Bazaar pack repository format 1 with subtree support (needs bzr 0.92)\n"
2063
 
 
2064
 
    def get_format_description(self):
2065
 
        """See RepositoryFormat.get_format_description()."""
2066
 
        return "Packs containing knits with subtree support\n"
2067
 
 
2068
 
 
2069
 
class RepositoryFormatKnitPack4(RepositoryFormatPack):
2070
 
    """A rich-root, no subtrees parameterized Pack repository.
2071
 
 
2072
 
    This repository format uses the xml6 serializer to get:
2073
 
     - support for recording full info about the tree root
2074
 
 
2075
 
    This format was introduced in 1.0.
2076
 
    """
2077
 
 
2078
 
    repository_class = KnitPackRepository
2079
 
    _commit_builder_class = PackRootCommitBuilder
2080
 
    rich_root_data = True
2081
 
    supports_tree_reference = False
2082
 
    @property
2083
 
    def _serializer(self):
2084
 
        return xml6.serializer_v6
2085
 
    # What index classes to use
2086
 
    index_builder_class = InMemoryGraphIndex
2087
 
    index_class = GraphIndex
2088
 
 
2089
 
    def _get_matching_bzrdir(self):
2090
 
        return bzrdir.format_registry.make_bzrdir(
2091
 
            'rich-root-pack')
2092
 
 
2093
 
    def _ignore_setting_bzrdir(self, format):
2094
 
        pass
2095
 
 
2096
 
    _matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
2097
 
 
2098
 
    def check_conversion_target(self, target_format):
2099
 
        if not target_format.rich_root_data:
2100
 
            raise errors.BadConversionTarget(
2101
 
                'Does not support rich root data.', target_format)
2102
 
 
2103
 
    def get_format_string(self):
2104
 
        """See RepositoryFormat.get_format_string()."""
2105
 
        return ("Bazaar pack repository format 1 with rich root"
2106
 
                " (needs bzr 1.0)\n")
2107
 
 
2108
 
    def get_format_description(self):
2109
 
        """See RepositoryFormat.get_format_description()."""
2110
 
        return "Packs containing knits with rich root support\n"
2111
 
 
2112
 
 
2113
 
class RepositoryFormatKnitPack5(RepositoryFormatPack):
2114
 
    """Repository that supports external references to allow stacking.
2115
 
 
2116
 
    New in release 1.6.
2117
 
 
2118
 
    Supports external lookups, which results in non-truncated ghosts after
2119
 
    reconcile compared to pack-0.92 formats.
2120
 
    """
2121
 
 
2122
 
    repository_class = KnitPackRepository
2123
 
    _commit_builder_class = PackCommitBuilder
2124
 
    supports_external_lookups = True
2125
 
    # What index classes to use
2126
 
    index_builder_class = InMemoryGraphIndex
2127
 
    index_class = GraphIndex
2128
 
 
2129
 
    @property
2130
 
    def _serializer(self):
2131
 
        return xml5.serializer_v5
2132
 
 
2133
 
    def _get_matching_bzrdir(self):
2134
 
        return bzrdir.format_registry.make_bzrdir('1.6')
2135
 
 
2136
 
    def _ignore_setting_bzrdir(self, format):
2137
 
        pass
2138
 
 
2139
 
    _matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
2140
 
 
2141
 
    def get_format_string(self):
2142
 
        """See RepositoryFormat.get_format_string()."""
2143
 
        return "Bazaar RepositoryFormatKnitPack5 (bzr 1.6)\n"
2144
 
 
2145
 
    def get_format_description(self):
2146
 
        """See RepositoryFormat.get_format_description()."""
2147
 
        return "Packs 5 (adds stacking support, requires bzr 1.6)"
2148
 
 
2149
 
    def check_conversion_target(self, target_format):
2150
 
        pass
2151
 
 
2152
 
 
2153
 
class RepositoryFormatKnitPack5RichRoot(RepositoryFormatPack):
2154
 
    """A repository with rich roots and stacking.
2155
 
 
2156
 
    New in release 1.6.1.
2157
 
 
2158
 
    Supports stacking on other repositories, allowing data to be accessed
2159
 
    without being stored locally.
2160
 
    """
2161
 
 
2162
 
    repository_class = KnitPackRepository
2163
 
    _commit_builder_class = PackRootCommitBuilder
2164
 
    rich_root_data = True
2165
 
    supports_tree_reference = False # no subtrees
2166
 
    supports_external_lookups = True
2167
 
    # What index classes to use
2168
 
    index_builder_class = InMemoryGraphIndex
2169
 
    index_class = GraphIndex
2170
 
 
2171
 
    @property
2172
 
    def _serializer(self):
2173
 
        return xml6.serializer_v6
2174
 
 
2175
 
    def _get_matching_bzrdir(self):
2176
 
        return bzrdir.format_registry.make_bzrdir(
2177
 
            '1.6.1-rich-root')
2178
 
 
2179
 
    def _ignore_setting_bzrdir(self, format):
2180
 
        pass
2181
 
 
2182
 
    _matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
2183
 
 
2184
 
    def check_conversion_target(self, target_format):
2185
 
        if not target_format.rich_root_data:
2186
 
            raise errors.BadConversionTarget(
2187
 
                'Does not support rich root data.', target_format)
2188
 
 
2189
 
    def get_format_string(self):
2190
 
        """See RepositoryFormat.get_format_string()."""
2191
 
        return "Bazaar RepositoryFormatKnitPack5RichRoot (bzr 1.6.1)\n"
2192
 
 
2193
 
    def get_format_description(self):
2194
 
        return "Packs 5 rich-root (adds stacking support, requires bzr 1.6.1)"
2195
 
 
2196
 
 
2197
 
class RepositoryFormatKnitPack5RichRootBroken(RepositoryFormatPack):
2198
 
    """A repository with rich roots and external references.
2199
 
 
2200
 
    New in release 1.6.
2201
 
 
2202
 
    Supports external lookups, which results in non-truncated ghosts after
2203
 
    reconcile compared to pack-0.92 formats.
2204
 
 
2205
 
    This format was deprecated because the serializer it uses accidentally
2206
 
    supported subtrees, when the format was not intended to. This meant that
2207
 
    someone could accidentally fetch from an incorrect repository.
2208
 
    """
2209
 
 
2210
 
    repository_class = KnitPackRepository
2211
 
    _commit_builder_class = PackRootCommitBuilder
2212
 
    rich_root_data = True
2213
 
    supports_tree_reference = False # no subtrees
2214
 
 
2215
 
    supports_external_lookups = True
2216
 
    # What index classes to use
2217
 
    index_builder_class = InMemoryGraphIndex
2218
 
    index_class = GraphIndex
2219
 
 
2220
 
    @property
2221
 
    def _serializer(self):
2222
 
        return xml7.serializer_v7
2223
 
 
2224
 
    def _get_matching_bzrdir(self):
2225
 
        return bzrdir.format_registry.make_bzrdir(
2226
 
            '1.6.1-rich-root')
2227
 
 
2228
 
    def _ignore_setting_bzrdir(self, format):
2229
 
        pass
2230
 
 
2231
 
    _matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
2232
 
 
2233
 
    def check_conversion_target(self, target_format):
2234
 
        if not target_format.rich_root_data:
2235
 
            raise errors.BadConversionTarget(
2236
 
                'Does not support rich root data.', target_format)
2237
 
 
2238
 
    def get_format_string(self):
2239
 
        """See RepositoryFormat.get_format_string()."""
2240
 
        return "Bazaar RepositoryFormatKnitPack5RichRoot (bzr 1.6)\n"
2241
 
 
2242
 
    def get_format_description(self):
2243
 
        return ("Packs 5 rich-root (adds stacking support, requires bzr 1.6)"
2244
 
                " (deprecated)")
2245
 
 
2246
 
 
2247
 
class RepositoryFormatPackDevelopment2(RepositoryFormatPack):
2248
 
    """A no-subtrees development repository.
2249
 
 
2250
 
    This format should be retained until the second release after bzr 1.7.
2251
 
 
2252
 
    This is pack-1.6.1 with B+Tree indices.
2253
 
    """
2254
 
 
2255
 
    repository_class = KnitPackRepository
2256
 
    _commit_builder_class = PackCommitBuilder
2257
 
    supports_external_lookups = True
2258
 
    # What index classes to use
2259
 
    index_builder_class = BTreeBuilder
2260
 
    index_class = BTreeGraphIndex
2261
 
 
2262
 
    @property
2263
 
    def _serializer(self):
2264
 
        return xml5.serializer_v5
2265
 
 
2266
 
    def _get_matching_bzrdir(self):
2267
 
        return bzrdir.format_registry.make_bzrdir('development2')
2268
 
 
2269
 
    def _ignore_setting_bzrdir(self, format):
2270
 
        pass
2271
 
 
2272
 
    _matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
2273
 
 
2274
 
    def get_format_string(self):
2275
 
        """See RepositoryFormat.get_format_string()."""
2276
 
        return "Bazaar development format 2 (needs bzr.dev from before 1.8)\n"
2277
 
 
2278
 
    def get_format_description(self):
2279
 
        """See RepositoryFormat.get_format_description()."""
2280
 
        return ("Development repository format, currently the same as "
2281
 
            "1.6.1 with B+Trees.\n")
2282
 
 
2283
 
    def check_conversion_target(self, target_format):
2284
 
        pass
2285
 
 
2286
 
 
2287
 
class RepositoryFormatPackDevelopment2Subtree(RepositoryFormatPack):
2288
 
    """A subtrees development repository.
2289
 
 
2290
 
    This format should be retained until the second release after bzr 1.7.
2291
 
 
2292
 
    1.6.1-subtree[as it might have been] with B+Tree indices.
2293
 
    """
2294
 
 
2295
 
    repository_class = KnitPackRepository
2296
 
    _commit_builder_class = PackRootCommitBuilder
2297
 
    rich_root_data = True
2298
 
    supports_tree_reference = True
2299
 
    supports_external_lookups = True
2300
 
    # What index classes to use
2301
 
    index_builder_class = BTreeBuilder
2302
 
    index_class = BTreeGraphIndex
2303
 
 
2304
 
    @property
2305
 
    def _serializer(self):
2306
 
        return xml7.serializer_v7
2307
 
 
2308
 
    def _get_matching_bzrdir(self):
2309
 
        return bzrdir.format_registry.make_bzrdir(
2310
 
            'development2-subtree')
2311
 
 
2312
 
    def _ignore_setting_bzrdir(self, format):
2313
 
        pass
2314
 
 
2315
 
    _matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
2316
 
 
2317
 
    def check_conversion_target(self, target_format):
2318
 
        if not target_format.rich_root_data:
2319
 
            raise errors.BadConversionTarget(
2320
 
                'Does not support rich root data.', target_format)
2321
 
        if not getattr(target_format, 'supports_tree_reference', False):
2322
 
            raise errors.BadConversionTarget(
2323
 
                'Does not support nested trees', target_format)
2324
 
            
2325
 
    def get_format_string(self):
2326
 
        """See RepositoryFormat.get_format_string()."""
2327
 
        return ("Bazaar development format 2 with subtree support "
2328
 
            "(needs bzr.dev from before 1.8)\n")
2329
 
 
2330
 
    def get_format_description(self):
2331
 
        """See RepositoryFormat.get_format_description()."""
2332
 
        return ("Development repository format, currently the same as "
2333
 
            "1.6.1-subtree with B+Tree indices.\n")
 
1939
class RetryPackOperations(errors.RetryWithNewPacks):
 
1940
    """Raised when we are packing and we find a missing file.
 
1941
 
 
1942
    Meant as a signaling exception, to tell the RepositoryPackCollection.pack
 
1943
    code it should try again.
 
1944
    """
 
1945
 
 
1946
    internal_error = True
 
1947
 
 
1948
    _fmt = ("Pack files have changed, reload and try pack again."
 
1949
            " context: %(context)s %(orig_error)s")
 
1950
 
 
1951
 
 
1952
class _DirectPackAccess(object):
 
1953
    """Access to data in one or more packs with less translation."""
 
1954
 
 
1955
    def __init__(self, index_to_packs, reload_func=None, flush_func=None):
 
1956
        """Create a _DirectPackAccess object.
 
1957
 
 
1958
        :param index_to_packs: A dict mapping index objects to the transport
 
1959
            and file names for obtaining data.
 
1960
        :param reload_func: A function to call if we determine that the pack
 
1961
            files have moved and we need to reload our caches. See
 
1962
            bzrlib.repo_fmt.pack_repo.AggregateIndex for more details.
 
1963
        """
 
1964
        self._container_writer = None
 
1965
        self._write_index = None
 
1966
        self._indices = index_to_packs
 
1967
        self._reload_func = reload_func
 
1968
        self._flush_func = flush_func
 
1969
 
 
1970
    def add_raw_records(self, key_sizes, raw_data):
 
1971
        """Add raw knit bytes to a storage area.
 
1972
 
 
1973
        The data is spooled to the container writer in one bytes-record per
 
1974
        raw data item.
 
1975
 
 
1976
        :param sizes: An iterable of tuples containing the key and size of each
 
1977
            raw data segment.
 
1978
        :param raw_data: A bytestring containing the data.
 
1979
        :return: A list of memos to retrieve the record later. Each memo is an
 
1980
            opaque index memo. For _DirectPackAccess the memo is (index, pos,
 
1981
            length), where the index field is the write_index object supplied
 
1982
            to the PackAccess object.
 
1983
        """
 
1984
        if type(raw_data) is not str:
 
1985
            raise AssertionError(
 
1986
                'data must be plain bytes was %s' % type(raw_data))
 
1987
        result = []
 
1988
        offset = 0
 
1989
        for key, size in key_sizes:
 
1990
            p_offset, p_length = self._container_writer.add_bytes_record(
 
1991
                raw_data[offset:offset+size], [])
 
1992
            offset += size
 
1993
            result.append((self._write_index, p_offset, p_length))
 
1994
        return result
 
1995
 
 
1996
    def flush(self):
 
1997
        """Flush pending writes on this access object.
 
1998
 
 
1999
        This will flush any buffered writes to a NewPack.
 
2000
        """
 
2001
        if self._flush_func is not None:
 
2002
            self._flush_func()
 
2003
 
 
2004
    def get_raw_records(self, memos_for_retrieval):
 
2005
        """Get the raw bytes for a records.
 
2006
 
 
2007
        :param memos_for_retrieval: An iterable containing the (index, pos,
 
2008
            length) memo for retrieving the bytes. The Pack access method
 
2009
            looks up the pack to use for a given record in its index_to_pack
 
2010
            map.
 
2011
        :return: An iterator over the bytes of the records.
 
2012
        """
 
2013
        # first pass, group into same-index requests
 
2014
        request_lists = []
 
2015
        current_index = None
 
2016
        for (index, offset, length) in memos_for_retrieval:
 
2017
            if current_index == index:
 
2018
                current_list.append((offset, length))
 
2019
            else:
 
2020
                if current_index is not None:
 
2021
                    request_lists.append((current_index, current_list))
 
2022
                current_index = index
 
2023
                current_list = [(offset, length)]
 
2024
        # handle the last entry
 
2025
        if current_index is not None:
 
2026
            request_lists.append((current_index, current_list))
 
2027
        for index, offsets in request_lists:
 
2028
            try:
 
2029
                transport, path = self._indices[index]
 
2030
            except KeyError:
 
2031
                # A KeyError here indicates that someone has triggered an index
 
2032
                # reload, and this index has gone missing, we need to start
 
2033
                # over.
 
2034
                if self._reload_func is None:
 
2035
                    # If we don't have a _reload_func there is nothing that can
 
2036
                    # be done
 
2037
                    raise
 
2038
                raise errors.RetryWithNewPacks(index,
 
2039
                                               reload_occurred=True,
 
2040
                                               exc_info=sys.exc_info())
 
2041
            try:
 
2042
                reader = pack.make_readv_reader(transport, path, offsets)
 
2043
                for names, read_func in reader.iter_records():
 
2044
                    yield read_func(None)
 
2045
            except errors.NoSuchFile:
 
2046
                # A NoSuchFile error indicates that a pack file has gone
 
2047
                # missing on disk, we need to trigger a reload, and start over.
 
2048
                if self._reload_func is None:
 
2049
                    raise
 
2050
                raise errors.RetryWithNewPacks(transport.abspath(path),
 
2051
                                               reload_occurred=False,
 
2052
                                               exc_info=sys.exc_info())
 
2053
 
 
2054
    def set_writer(self, writer, index, transport_packname):
 
2055
        """Set a writer to use for adding data."""
 
2056
        if index is not None:
 
2057
            self._indices[index] = transport_packname
 
2058
        self._container_writer = writer
 
2059
        self._write_index = index
 
2060
 
 
2061
    def reload_or_raise(self, retry_exc):
 
2062
        """Try calling the reload function, or re-raise the original exception.
 
2063
 
 
2064
        This should be called after _DirectPackAccess raises a
 
2065
        RetryWithNewPacks exception. This function will handle the common logic
 
2066
        of determining when the error is fatal versus being temporary.
 
2067
        It will also make sure that the original exception is raised, rather
 
2068
        than the RetryWithNewPacks exception.
 
2069
 
 
2070
        If this function returns, then the calling function should retry
 
2071
        whatever operation was being performed. Otherwise an exception will
 
2072
        be raised.
 
2073
 
 
2074
        :param retry_exc: A RetryWithNewPacks exception.
 
2075
        """
 
2076
        is_error = False
 
2077
        if self._reload_func is None:
 
2078
            is_error = True
 
2079
        elif not self._reload_func():
 
2080
            # The reload claimed that nothing changed
 
2081
            if not retry_exc.reload_occurred:
 
2082
                # If there wasn't an earlier reload, then we really were
 
2083
                # expecting to find changes. We didn't find them, so this is a
 
2084
                # hard error
 
2085
                is_error = True
 
2086
        if is_error:
 
2087
            exc_class, exc_value, exc_traceback = retry_exc.exc_info
 
2088
            raise exc_class, exc_value, exc_traceback
 
2089
 
 
2090
 
 
2091