~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/repofmt/pack_repo.py

(jameinel) Allow 'bzr serve' to interpret SIGHUP as a graceful shutdown.
 (bug #795025) (John A Meinel)

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