/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to breezy/bzr/pack_repo.py

  • Committer: Jelmer Vernooij
  • Date: 2019-03-13 23:24:13 UTC
  • mto: (7290.1.23 work)
  • mto: This revision was merged to the branch mainline in revision 7311.
  • Revision ID: jelmer@jelmer.uk-20190313232413-y1c951be4surcc9g
Fix formatting.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2007-2011 Canonical Ltd
 
2
#
 
3
# This program is free software; you can redistribute it and/or modify
 
4
# it under the terms of the GNU General Public License as published by
 
5
# the Free Software Foundation; either version 2 of the License, or
 
6
# (at your option) any later version.
 
7
#
 
8
# This program is distributed in the hope that it will be useful,
 
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
 
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
11
# GNU General Public License for more details.
 
12
#
 
13
# You should have received a copy of the GNU General Public License
 
14
# along with this program; if not, write to the Free Software
 
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 
16
 
 
17
from __future__ import absolute_import
 
18
 
 
19
import re
 
20
import sys
 
21
 
 
22
from ..lazy_import import lazy_import
 
23
lazy_import(globals(), """
 
24
import time
 
25
 
 
26
from breezy import (
 
27
    cleanup,
 
28
    config,
 
29
    debug,
 
30
    graph,
 
31
    osutils,
 
32
    transactions,
 
33
    ui,
 
34
    )
 
35
from breezy.bzr import (
 
36
    pack,
 
37
    )
 
38
from breezy.bzr.index import (
 
39
    CombinedGraphIndex,
 
40
    )
 
41
""")
 
42
from .. import (
 
43
    errors,
 
44
    lockable_files,
 
45
    lockdir,
 
46
    )
 
47
from ..bzr import (
 
48
    btree_index,
 
49
    )
 
50
 
 
51
from ..decorators import (
 
52
    only_raises,
 
53
    )
 
54
from ..lock import LogicalLockResult
 
55
from ..repository import (
 
56
    _LazyListJoin,
 
57
    RepositoryWriteLockResult,
 
58
    )
 
59
from ..bzr.repository import (
 
60
    MetaDirRepository,
 
61
    RepositoryFormatMetaDir,
 
62
    )
 
63
from ..sixish import (
 
64
    reraise,
 
65
    viewitems,
 
66
    )
 
67
from ..bzr.vf_repository import (
 
68
    MetaDirVersionedFileRepository,
 
69
    MetaDirVersionedFileRepositoryFormat,
 
70
    VersionedFileCommitBuilder,
 
71
    )
 
72
from ..trace import (
 
73
    mutter,
 
74
    note,
 
75
    warning,
 
76
    )
 
77
 
 
78
 
 
79
class PackCommitBuilder(VersionedFileCommitBuilder):
 
80
    """Subclass of VersionedFileCommitBuilder to add texts with pack semantics.
 
81
 
 
82
    Specifically this uses one knit object rather than one knit object per
 
83
    added text, reducing memory and object pressure.
 
84
    """
 
85
 
 
86
    def __init__(self, repository, parents, config, timestamp=None,
 
87
                 timezone=None, committer=None, revprops=None,
 
88
                 revision_id=None, lossy=False):
 
89
        VersionedFileCommitBuilder.__init__(self, repository, parents, config,
 
90
                                            timestamp=timestamp, timezone=timezone, committer=committer,
 
91
                                            revprops=revprops, revision_id=revision_id, lossy=lossy)
 
92
        self._file_graph = graph.Graph(
 
93
            repository._pack_collection.text_index.combined_index)
 
94
 
 
95
    def _heads(self, file_id, revision_ids):
 
96
        keys = [(file_id, revision_id) for revision_id in revision_ids]
 
97
        return {key[1] for key in self._file_graph.heads(keys)}
 
98
 
 
99
 
 
100
class Pack(object):
 
101
    """An in memory proxy for a pack and its indices.
 
102
 
 
103
    This is a base class that is not directly used, instead the classes
 
104
    ExistingPack and NewPack are used.
 
105
    """
 
106
 
 
107
    # A map of index 'type' to the file extension and position in the
 
108
    # index_sizes array.
 
109
    index_definitions = {
 
110
        'chk': ('.cix', 4),
 
111
        'revision': ('.rix', 0),
 
112
        'inventory': ('.iix', 1),
 
113
        'text': ('.tix', 2),
 
114
        'signature': ('.six', 3),
 
115
        }
 
116
 
 
117
    def __init__(self, revision_index, inventory_index, text_index,
 
118
                 signature_index, chk_index=None):
 
119
        """Create a pack instance.
 
120
 
 
121
        :param revision_index: A GraphIndex for determining what revisions are
 
122
            present in the Pack and accessing the locations of their texts.
 
123
        :param inventory_index: A GraphIndex for determining what inventories are
 
124
            present in the Pack and accessing the locations of their
 
125
            texts/deltas.
 
126
        :param text_index: A GraphIndex for determining what file texts
 
127
            are present in the pack and accessing the locations of their
 
128
            texts/deltas (via (fileid, revisionid) tuples).
 
129
        :param signature_index: A GraphIndex for determining what signatures are
 
130
            present in the Pack and accessing the locations of their texts.
 
131
        :param chk_index: A GraphIndex for accessing content by CHK, if the
 
132
            pack has one.
 
133
        """
 
134
        self.revision_index = revision_index
 
135
        self.inventory_index = inventory_index
 
136
        self.text_index = text_index
 
137
        self.signature_index = signature_index
 
138
        self.chk_index = chk_index
 
139
 
 
140
    def access_tuple(self):
 
141
        """Return a tuple (transport, name) for the pack content."""
 
142
        return self.pack_transport, self.file_name()
 
143
 
 
144
    def _check_references(self):
 
145
        """Make sure our external references are present.
 
146
 
 
147
        Packs are allowed to have deltas whose base is not in the pack, but it
 
148
        must be present somewhere in this collection.  It is not allowed to
 
149
        have deltas based on a fallback repository.
 
150
        (See <https://bugs.launchpad.net/bzr/+bug/288751>)
 
151
        """
 
152
        missing_items = {}
 
153
        for (index_name, external_refs, index) in [
 
154
                ('texts',
 
155
                    self._get_external_refs(self.text_index),
 
156
                    self._pack_collection.text_index.combined_index),
 
157
                ('inventories',
 
158
                    self._get_external_refs(self.inventory_index),
 
159
                    self._pack_collection.inventory_index.combined_index),
 
160
                ]:
 
161
            missing = external_refs.difference(
 
162
                k for (idx, k, v, r) in
 
163
                index.iter_entries(external_refs))
 
164
            if missing:
 
165
                missing_items[index_name] = sorted(list(missing))
 
166
        if missing_items:
 
167
            from pprint import pformat
 
168
            raise errors.BzrCheckError(
 
169
                "Newly created pack file %r has delta references to "
 
170
                "items not in its repository:\n%s"
 
171
                % (self, pformat(missing_items)))
 
172
 
 
173
    def file_name(self):
 
174
        """Get the file name for the pack on disk."""
 
175
        return self.name + '.pack'
 
176
 
 
177
    def get_revision_count(self):
 
178
        return self.revision_index.key_count()
 
179
 
 
180
    def index_name(self, index_type, name):
 
181
        """Get the disk name of an index type for pack name 'name'."""
 
182
        return name + Pack.index_definitions[index_type][0]
 
183
 
 
184
    def index_offset(self, index_type):
 
185
        """Get the position in a index_size array for a given index type."""
 
186
        return Pack.index_definitions[index_type][1]
 
187
 
 
188
    def inventory_index_name(self, name):
 
189
        """The inv index is the name + .iix."""
 
190
        return self.index_name('inventory', name)
 
191
 
 
192
    def revision_index_name(self, name):
 
193
        """The revision index is the name + .rix."""
 
194
        return self.index_name('revision', name)
 
195
 
 
196
    def signature_index_name(self, name):
 
197
        """The signature index is the name + .six."""
 
198
        return self.index_name('signature', name)
 
199
 
 
200
    def text_index_name(self, name):
 
201
        """The text index is the name + .tix."""
 
202
        return self.index_name('text', name)
 
203
 
 
204
    def _replace_index_with_readonly(self, index_type):
 
205
        unlimited_cache = False
 
206
        if index_type == 'chk':
 
207
            unlimited_cache = True
 
208
        index = self.index_class(self.index_transport,
 
209
                                 self.index_name(index_type, self.name),
 
210
                                 self.index_sizes[self.index_offset(
 
211
                                     index_type)],
 
212
                                 unlimited_cache=unlimited_cache)
 
213
        if index_type == 'chk':
 
214
            index._leaf_factory = btree_index._gcchk_factory
 
215
        setattr(self, index_type + '_index', index)
 
216
 
 
217
    def __lt__(self, other):
 
218
        if not isinstance(other, Pack):
 
219
            raise TypeError(other)
 
220
        return (id(self) < id(other))
 
221
 
 
222
    def __hash__(self):
 
223
        return hash((type(self), self.revision_index, self.inventory_index,
 
224
                     self.text_index, self.signature_index, self.chk_index))
 
225
 
 
226
 
 
227
class ExistingPack(Pack):
 
228
    """An in memory proxy for an existing .pack and its disk indices."""
 
229
 
 
230
    def __init__(self, pack_transport, name, revision_index, inventory_index,
 
231
                 text_index, signature_index, chk_index=None):
 
232
        """Create an ExistingPack object.
 
233
 
 
234
        :param pack_transport: The transport where the pack file resides.
 
235
        :param name: The name of the pack on disk in the pack_transport.
 
236
        """
 
237
        Pack.__init__(self, revision_index, inventory_index, text_index,
 
238
                      signature_index, chk_index)
 
239
        self.name = name
 
240
        self.pack_transport = pack_transport
 
241
        if None in (revision_index, inventory_index, text_index,
 
242
                    signature_index, name, pack_transport):
 
243
            raise AssertionError()
 
244
 
 
245
    def __eq__(self, other):
 
246
        return self.__dict__ == other.__dict__
 
247
 
 
248
    def __ne__(self, other):
 
249
        return not self.__eq__(other)
 
250
 
 
251
    def __repr__(self):
 
252
        return "<%s.%s object at 0x%x, %s, %s" % (
 
253
            self.__class__.__module__, self.__class__.__name__, id(self),
 
254
            self.pack_transport, self.name)
 
255
 
 
256
    def __hash__(self):
 
257
        return hash((type(self), self.name))
 
258
 
 
259
 
 
260
class ResumedPack(ExistingPack):
 
261
 
 
262
    def __init__(self, name, revision_index, inventory_index, text_index,
 
263
                 signature_index, upload_transport, pack_transport, index_transport,
 
264
                 pack_collection, chk_index=None):
 
265
        """Create a ResumedPack object."""
 
266
        ExistingPack.__init__(self, pack_transport, name, revision_index,
 
267
                              inventory_index, text_index, signature_index,
 
268
                              chk_index=chk_index)
 
269
        self.upload_transport = upload_transport
 
270
        self.index_transport = index_transport
 
271
        self.index_sizes = [None, None, None, None]
 
272
        indices = [
 
273
            ('revision', revision_index),
 
274
            ('inventory', inventory_index),
 
275
            ('text', text_index),
 
276
            ('signature', signature_index),
 
277
            ]
 
278
        if chk_index is not None:
 
279
            indices.append(('chk', chk_index))
 
280
            self.index_sizes.append(None)
 
281
        for index_type, index in indices:
 
282
            offset = self.index_offset(index_type)
 
283
            self.index_sizes[offset] = index._size
 
284
        self.index_class = pack_collection._index_class
 
285
        self._pack_collection = pack_collection
 
286
        self._state = 'resumed'
 
287
        # XXX: perhaps check that the .pack file exists?
 
288
 
 
289
    def access_tuple(self):
 
290
        if self._state == 'finished':
 
291
            return Pack.access_tuple(self)
 
292
        elif self._state == 'resumed':
 
293
            return self.upload_transport, self.file_name()
 
294
        else:
 
295
            raise AssertionError(self._state)
 
296
 
 
297
    def abort(self):
 
298
        self.upload_transport.delete(self.file_name())
 
299
        indices = [self.revision_index, self.inventory_index, self.text_index,
 
300
                   self.signature_index]
 
301
        if self.chk_index is not None:
 
302
            indices.append(self.chk_index)
 
303
        for index in indices:
 
304
            index._transport.delete(index._name)
 
305
 
 
306
    def finish(self):
 
307
        self._check_references()
 
308
        index_types = ['revision', 'inventory', 'text', 'signature']
 
309
        if self.chk_index is not None:
 
310
            index_types.append('chk')
 
311
        for index_type in index_types:
 
312
            old_name = self.index_name(index_type, self.name)
 
313
            new_name = '../indices/' + old_name
 
314
            self.upload_transport.move(old_name, new_name)
 
315
            self._replace_index_with_readonly(index_type)
 
316
        new_name = '../packs/' + self.file_name()
 
317
        self.upload_transport.move(self.file_name(), new_name)
 
318
        self._state = 'finished'
 
319
 
 
320
    def _get_external_refs(self, index):
 
321
        """Return compression parents for this index that are not present.
 
322
 
 
323
        This returns any compression parents that are referenced by this index,
 
324
        which are not contained *in* this index. They may be present elsewhere.
 
325
        """
 
326
        return index.external_references(1)
 
327
 
 
328
 
 
329
class NewPack(Pack):
 
330
    """An in memory proxy for a pack which is being created."""
 
331
 
 
332
    def __init__(self, pack_collection, upload_suffix='', file_mode=None):
 
333
        """Create a NewPack instance.
 
334
 
 
335
        :param pack_collection: A PackCollection into which this is being inserted.
 
336
        :param upload_suffix: An optional suffix to be given to any temporary
 
337
            files created during the pack creation. e.g '.autopack'
 
338
        :param file_mode: Unix permissions for newly created file.
 
339
        """
 
340
        # The relative locations of the packs are constrained, but all are
 
341
        # passed in because the caller has them, so as to avoid object churn.
 
342
        index_builder_class = pack_collection._index_builder_class
 
343
        if pack_collection.chk_index is not None:
 
344
            chk_index = index_builder_class(reference_lists=0)
 
345
        else:
 
346
            chk_index = None
 
347
        Pack.__init__(self,
 
348
                      # Revisions: parents list, no text compression.
 
349
                      index_builder_class(reference_lists=1),
 
350
                      # Inventory: We want to map compression only, but currently the
 
351
                      # knit code hasn't been updated enough to understand that, so we
 
352
                      # have a regular 2-list index giving parents and compression
 
353
                      # source.
 
354
                      index_builder_class(reference_lists=2),
 
355
                      # Texts: compression and per file graph, for all fileids - so two
 
356
                      # reference lists and two elements in the key tuple.
 
357
                      index_builder_class(reference_lists=2, key_elements=2),
 
358
                      # Signatures: Just blobs to store, no compression, no parents
 
359
                      # listing.
 
360
                      index_builder_class(reference_lists=0),
 
361
                      # CHK based storage - just blobs, no compression or parents.
 
362
                      chk_index=chk_index
 
363
                      )
 
364
        self._pack_collection = pack_collection
 
365
        # When we make readonly indices, we need this.
 
366
        self.index_class = pack_collection._index_class
 
367
        # where should the new pack be opened
 
368
        self.upload_transport = pack_collection._upload_transport
 
369
        # where are indices written out to
 
370
        self.index_transport = pack_collection._index_transport
 
371
        # where is the pack renamed to when it is finished?
 
372
        self.pack_transport = pack_collection._pack_transport
 
373
        # What file mode to upload the pack and indices with.
 
374
        self._file_mode = file_mode
 
375
        # tracks the content written to the .pack file.
 
376
        self._hash = osutils.md5()
 
377
        # a tuple with the length in bytes of the indices, once the pack
 
378
        # is finalised. (rev, inv, text, sigs, chk_if_in_use)
 
379
        self.index_sizes = None
 
380
        # How much data to cache when writing packs. Note that this is not
 
381
        # synchronised with reads, because it's not in the transport layer, so
 
382
        # is not safe unless the client knows it won't be reading from the pack
 
383
        # under creation.
 
384
        self._cache_limit = 0
 
385
        # the temporary pack file name.
 
386
        self.random_name = osutils.rand_chars(20) + upload_suffix
 
387
        # when was this pack started ?
 
388
        self.start_time = time.time()
 
389
        # open an output stream for the data added to the pack.
 
390
        self.write_stream = self.upload_transport.open_write_stream(
 
391
            self.random_name, mode=self._file_mode)
 
392
        if 'pack' in debug.debug_flags:
 
393
            mutter('%s: create_pack: pack stream open: %s%s t+%6.3fs',
 
394
                   time.ctime(), self.upload_transport.base, self.random_name,
 
395
                   time.time() - self.start_time)
 
396
        # A list of byte sequences to be written to the new pack, and the
 
397
        # aggregate size of them.  Stored as a list rather than separate
 
398
        # variables so that the _write_data closure below can update them.
 
399
        self._buffer = [[], 0]
 
400
        # create a callable for adding data
 
401
        #
 
402
        # robertc says- this is a closure rather than a method on the object
 
403
        # so that the variables are locals, and faster than accessing object
 
404
        # members.
 
405
 
 
406
        def _write_data(bytes, flush=False, _buffer=self._buffer,
 
407
                        _write=self.write_stream.write, _update=self._hash.update):
 
408
            _buffer[0].append(bytes)
 
409
            _buffer[1] += len(bytes)
 
410
            # buffer cap
 
411
            if _buffer[1] > self._cache_limit or flush:
 
412
                bytes = b''.join(_buffer[0])
 
413
                _write(bytes)
 
414
                _update(bytes)
 
415
                _buffer[:] = [[], 0]
 
416
        # expose this on self, for the occasion when clients want to add data.
 
417
        self._write_data = _write_data
 
418
        # a pack writer object to serialise pack records.
 
419
        self._writer = pack.ContainerWriter(self._write_data)
 
420
        self._writer.begin()
 
421
        # what state is the pack in? (open, finished, aborted)
 
422
        self._state = 'open'
 
423
        # no name until we finish writing the content
 
424
        self.name = None
 
425
 
 
426
    def abort(self):
 
427
        """Cancel creating this pack."""
 
428
        self._state = 'aborted'
 
429
        self.write_stream.close()
 
430
        # Remove the temporary pack file.
 
431
        self.upload_transport.delete(self.random_name)
 
432
        # The indices have no state on disk.
 
433
 
 
434
    def access_tuple(self):
 
435
        """Return a tuple (transport, name) for the pack content."""
 
436
        if self._state == 'finished':
 
437
            return Pack.access_tuple(self)
 
438
        elif self._state == 'open':
 
439
            return self.upload_transport, self.random_name
 
440
        else:
 
441
            raise AssertionError(self._state)
 
442
 
 
443
    def data_inserted(self):
 
444
        """True if data has been added to this pack."""
 
445
        return bool(self.get_revision_count() or
 
446
                    self.inventory_index.key_count() or
 
447
                    self.text_index.key_count() or
 
448
                    self.signature_index.key_count() or
 
449
                    (self.chk_index is not None and self.chk_index.key_count()))
 
450
 
 
451
    def finish_content(self):
 
452
        if self.name is not None:
 
453
            return
 
454
        self._writer.end()
 
455
        if self._buffer[1]:
 
456
            self._write_data(b'', flush=True)
 
457
        self.name = self._hash.hexdigest()
 
458
 
 
459
    def finish(self, suspend=False):
 
460
        """Finish the new pack.
 
461
 
 
462
        This:
 
463
         - finalises the content
 
464
         - assigns a name (the md5 of the content, currently)
 
465
         - writes out the associated indices
 
466
         - renames the pack into place.
 
467
         - stores the index size tuple for the pack in the index_sizes
 
468
           attribute.
 
469
        """
 
470
        self.finish_content()
 
471
        if not suspend:
 
472
            self._check_references()
 
473
        # write indices
 
474
        # XXX: It'd be better to write them all to temporary names, then
 
475
        # rename them all into place, so that the window when only some are
 
476
        # visible is smaller.  On the other hand none will be seen until
 
477
        # they're in the names list.
 
478
        self.index_sizes = [None, None, None, None]
 
479
        self._write_index('revision', self.revision_index, 'revision',
 
480
                          suspend)
 
481
        self._write_index('inventory', self.inventory_index, 'inventory',
 
482
                          suspend)
 
483
        self._write_index('text', self.text_index, 'file texts', suspend)
 
484
        self._write_index('signature', self.signature_index,
 
485
                          'revision signatures', suspend)
 
486
        if self.chk_index is not None:
 
487
            self.index_sizes.append(None)
 
488
            self._write_index('chk', self.chk_index,
 
489
                              'content hash bytes', suspend)
 
490
        self.write_stream.close(
 
491
            want_fdatasync=self._pack_collection.config_stack.get('repository.fdatasync'))
 
492
        # Note that this will clobber an existing pack with the same name,
 
493
        # without checking for hash collisions. While this is undesirable this
 
494
        # is something that can be rectified in a subsequent release. One way
 
495
        # to rectify it may be to leave the pack at the original name, writing
 
496
        # its pack-names entry as something like 'HASH: index-sizes
 
497
        # temporary-name'. Allocate that and check for collisions, if it is
 
498
        # collision free then rename it into place. If clients know this scheme
 
499
        # they can handle missing-file errors by:
 
500
        #  - try for HASH.pack
 
501
        #  - try for temporary-name
 
502
        #  - refresh the pack-list to see if the pack is now absent
 
503
        new_name = self.name + '.pack'
 
504
        if not suspend:
 
505
            new_name = '../packs/' + new_name
 
506
        self.upload_transport.move(self.random_name, new_name)
 
507
        self._state = 'finished'
 
508
        if 'pack' in debug.debug_flags:
 
509
            # XXX: size might be interesting?
 
510
            mutter('%s: create_pack: pack finished: %s%s->%s t+%6.3fs',
 
511
                   time.ctime(), self.upload_transport.base, self.random_name,
 
512
                   new_name, time.time() - self.start_time)
 
513
 
 
514
    def flush(self):
 
515
        """Flush any current data."""
 
516
        if self._buffer[1]:
 
517
            bytes = b''.join(self._buffer[0])
 
518
            self.write_stream.write(bytes)
 
519
            self._hash.update(bytes)
 
520
            self._buffer[:] = [[], 0]
 
521
 
 
522
    def _get_external_refs(self, index):
 
523
        return index._external_references()
 
524
 
 
525
    def set_write_cache_size(self, size):
 
526
        self._cache_limit = size
 
527
 
 
528
    def _write_index(self, index_type, index, label, suspend=False):
 
529
        """Write out an index.
 
530
 
 
531
        :param index_type: The type of index to write - e.g. 'revision'.
 
532
        :param index: The index object to serialise.
 
533
        :param label: What label to give the index e.g. 'revision'.
 
534
        """
 
535
        index_name = self.index_name(index_type, self.name)
 
536
        if suspend:
 
537
            transport = self.upload_transport
 
538
        else:
 
539
            transport = self.index_transport
 
540
        index_tempfile = index.finish()
 
541
        index_bytes = index_tempfile.read()
 
542
        write_stream = transport.open_write_stream(index_name,
 
543
                                                   mode=self._file_mode)
 
544
        write_stream.write(index_bytes)
 
545
        write_stream.close(
 
546
            want_fdatasync=self._pack_collection.config_stack.get('repository.fdatasync'))
 
547
        self.index_sizes[self.index_offset(index_type)] = len(index_bytes)
 
548
        if 'pack' in debug.debug_flags:
 
549
            # XXX: size might be interesting?
 
550
            mutter('%s: create_pack: wrote %s index: %s%s t+%6.3fs',
 
551
                   time.ctime(), label, self.upload_transport.base,
 
552
                   self.random_name, time.time() - self.start_time)
 
553
        # Replace the writable index on this object with a readonly,
 
554
        # presently unloaded index. We should alter
 
555
        # the index layer to make its finish() error if add_node is
 
556
        # subsequently used. RBC
 
557
        self._replace_index_with_readonly(index_type)
 
558
 
 
559
 
 
560
class AggregateIndex(object):
 
561
    """An aggregated index for the RepositoryPackCollection.
 
562
 
 
563
    AggregateIndex is reponsible for managing the PackAccess object,
 
564
    Index-To-Pack mapping, and all indices list for a specific type of index
 
565
    such as 'revision index'.
 
566
 
 
567
    A CombinedIndex provides an index on a single key space built up
 
568
    from several on-disk indices.  The AggregateIndex builds on this
 
569
    to provide a knit access layer, and allows having up to one writable
 
570
    index within the collection.
 
571
    """
 
572
    # XXX: Probably 'can be written to' could/should be separated from 'acts
 
573
    # like a knit index' -- mbp 20071024
 
574
 
 
575
    def __init__(self, reload_func=None, flush_func=None):
 
576
        """Create an AggregateIndex.
 
577
 
 
578
        :param reload_func: A function to call if we find we are missing an
 
579
            index. Should have the form reload_func() => True if the list of
 
580
            active pack files has changed.
 
581
        """
 
582
        self._reload_func = reload_func
 
583
        self.index_to_pack = {}
 
584
        self.combined_index = CombinedGraphIndex([], reload_func=reload_func)
 
585
        self.data_access = _DirectPackAccess(self.index_to_pack,
 
586
                                             reload_func=reload_func,
 
587
                                             flush_func=flush_func)
 
588
        self.add_callback = None
 
589
 
 
590
    def add_index(self, index, pack):
 
591
        """Add index to the aggregate, which is an index for Pack pack.
 
592
 
 
593
        Future searches on the aggregate index will seach this new index
 
594
        before all previously inserted indices.
 
595
 
 
596
        :param index: An Index for the pack.
 
597
        :param pack: A Pack instance.
 
598
        """
 
599
        # expose it to the index map
 
600
        self.index_to_pack[index] = pack.access_tuple()
 
601
        # put it at the front of the linear index list
 
602
        self.combined_index.insert_index(0, index, pack.name)
 
603
 
 
604
    def add_writable_index(self, index, pack):
 
605
        """Add an index which is able to have data added to it.
 
606
 
 
607
        There can be at most one writable index at any time.  Any
 
608
        modifications made to the knit are put into this index.
 
609
 
 
610
        :param index: An index from the pack parameter.
 
611
        :param pack: A Pack instance.
 
612
        """
 
613
        if self.add_callback is not None:
 
614
            raise AssertionError(
 
615
                "%s already has a writable index through %s" %
 
616
                (self, self.add_callback))
 
617
        # allow writing: queue writes to a new index
 
618
        self.add_index(index, pack)
 
619
        # Updates the index to packs mapping as a side effect,
 
620
        self.data_access.set_writer(pack._writer, index, pack.access_tuple())
 
621
        self.add_callback = index.add_nodes
 
622
 
 
623
    def clear(self):
 
624
        """Reset all the aggregate data to nothing."""
 
625
        self.data_access.set_writer(None, None, (None, None))
 
626
        self.index_to_pack.clear()
 
627
        del self.combined_index._indices[:]
 
628
        del self.combined_index._index_names[:]
 
629
        self.add_callback = None
 
630
 
 
631
    def remove_index(self, index):
 
632
        """Remove index from the indices used to answer queries.
 
633
 
 
634
        :param index: An index from the pack parameter.
 
635
        """
 
636
        del self.index_to_pack[index]
 
637
        pos = self.combined_index._indices.index(index)
 
638
        del self.combined_index._indices[pos]
 
639
        del self.combined_index._index_names[pos]
 
640
        if (self.add_callback is not None and
 
641
                getattr(index, 'add_nodes', None) == self.add_callback):
 
642
            self.add_callback = None
 
643
            self.data_access.set_writer(None, None, (None, None))
 
644
 
 
645
 
 
646
class Packer(object):
 
647
    """Create a pack from packs."""
 
648
 
 
649
    def __init__(self, pack_collection, packs, suffix, revision_ids=None,
 
650
                 reload_func=None):
 
651
        """Create a Packer.
 
652
 
 
653
        :param pack_collection: A RepositoryPackCollection object where the
 
654
            new pack is being written to.
 
655
        :param packs: The packs to combine.
 
656
        :param suffix: The suffix to use on the temporary files for the pack.
 
657
        :param revision_ids: Revision ids to limit the pack to.
 
658
        :param reload_func: A function to call if a pack file/index goes
 
659
            missing. The side effect of calling this function should be to
 
660
            update self.packs. See also AggregateIndex
 
661
        """
 
662
        self.packs = packs
 
663
        self.suffix = suffix
 
664
        self.revision_ids = revision_ids
 
665
        # The pack object we are creating.
 
666
        self.new_pack = None
 
667
        self._pack_collection = pack_collection
 
668
        self._reload_func = reload_func
 
669
        # The index layer keys for the revisions being copied. None for 'all
 
670
        # objects'.
 
671
        self._revision_keys = None
 
672
        # What text keys to copy. None for 'all texts'. This is set by
 
673
        # _copy_inventory_texts
 
674
        self._text_filter = None
 
675
 
 
676
    def pack(self, pb=None):
 
677
        """Create a new pack by reading data from other packs.
 
678
 
 
679
        This does little more than a bulk copy of data. One key difference
 
680
        is that data with the same item key across multiple packs is elided
 
681
        from the output. The new pack is written into the current pack store
 
682
        along with its indices, and the name added to the pack names. The
 
683
        source packs are not altered and are not required to be in the current
 
684
        pack collection.
 
685
 
 
686
        :param pb: An optional progress bar to use. A nested bar is created if
 
687
            this is None.
 
688
        :return: A Pack object, or None if nothing was copied.
 
689
        """
 
690
        # open a pack - using the same name as the last temporary file
 
691
        # - which has already been flushed, so it's safe.
 
692
        # XXX: - duplicate code warning with start_write_group; fix before
 
693
        #      considering 'done'.
 
694
        if self._pack_collection._new_pack is not None:
 
695
            raise errors.BzrError('call to %s.pack() while another pack is'
 
696
                                  ' being written.'
 
697
                                  % (self.__class__.__name__,))
 
698
        if self.revision_ids is not None:
 
699
            if len(self.revision_ids) == 0:
 
700
                # silly fetch request.
 
701
                return None
 
702
            else:
 
703
                self.revision_ids = frozenset(self.revision_ids)
 
704
                self.revision_keys = frozenset((revid,) for revid in
 
705
                                               self.revision_ids)
 
706
        if pb is None:
 
707
            self.pb = ui.ui_factory.nested_progress_bar()
 
708
        else:
 
709
            self.pb = pb
 
710
        try:
 
711
            return self._create_pack_from_packs()
 
712
        finally:
 
713
            if pb is None:
 
714
                self.pb.finished()
 
715
 
 
716
    def open_pack(self):
 
717
        """Open a pack for the pack we are creating."""
 
718
        new_pack = self._pack_collection.pack_factory(self._pack_collection,
 
719
                                                      upload_suffix=self.suffix,
 
720
                                                      file_mode=self._pack_collection.repo.controldir._get_file_mode())
 
721
        # We know that we will process all nodes in order, and don't need to
 
722
        # query, so don't combine any indices spilled to disk until we are done
 
723
        new_pack.revision_index.set_optimize(combine_backing_indices=False)
 
724
        new_pack.inventory_index.set_optimize(combine_backing_indices=False)
 
725
        new_pack.text_index.set_optimize(combine_backing_indices=False)
 
726
        new_pack.signature_index.set_optimize(combine_backing_indices=False)
 
727
        return new_pack
 
728
 
 
729
    def _copy_revision_texts(self):
 
730
        """Copy revision data to the new pack."""
 
731
        raise NotImplementedError(self._copy_revision_texts)
 
732
 
 
733
    def _copy_inventory_texts(self):
 
734
        """Copy the inventory texts to the new pack.
 
735
 
 
736
        self._revision_keys is used to determine what inventories to copy.
 
737
 
 
738
        Sets self._text_filter appropriately.
 
739
        """
 
740
        raise NotImplementedError(self._copy_inventory_texts)
 
741
 
 
742
    def _copy_text_texts(self):
 
743
        raise NotImplementedError(self._copy_text_texts)
 
744
 
 
745
    def _create_pack_from_packs(self):
 
746
        raise NotImplementedError(self._create_pack_from_packs)
 
747
 
 
748
    def _log_copied_texts(self):
 
749
        if 'pack' in debug.debug_flags:
 
750
            mutter('%s: create_pack: file texts copied: %s%s %d items t+%6.3fs',
 
751
                   time.ctime(), self._pack_collection._upload_transport.base,
 
752
                   self.new_pack.random_name,
 
753
                   self.new_pack.text_index.key_count(),
 
754
                   time.time() - self.new_pack.start_time)
 
755
 
 
756
    def _use_pack(self, new_pack):
 
757
        """Return True if new_pack should be used.
 
758
 
 
759
        :param new_pack: The pack that has just been created.
 
760
        :return: True if the pack should be used.
 
761
        """
 
762
        return new_pack.data_inserted()
 
763
 
 
764
 
 
765
class RepositoryPackCollection(object):
 
766
    """Management of packs within a repository.
 
767
 
 
768
    :ivar _names: map of {pack_name: (index_size,)}
 
769
    """
 
770
 
 
771
    pack_factory = None
 
772
    resumed_pack_factory = None
 
773
    normal_packer_class = None
 
774
    optimising_packer_class = None
 
775
 
 
776
    def __init__(self, repo, transport, index_transport, upload_transport,
 
777
                 pack_transport, index_builder_class, index_class,
 
778
                 use_chk_index):
 
779
        """Create a new RepositoryPackCollection.
 
780
 
 
781
        :param transport: Addresses the repository base directory
 
782
            (typically .bzr/repository/).
 
783
        :param index_transport: Addresses the directory containing indices.
 
784
        :param upload_transport: Addresses the directory into which packs are written
 
785
            while they're being created.
 
786
        :param pack_transport: Addresses the directory of existing complete packs.
 
787
        :param index_builder_class: The index builder class to use.
 
788
        :param index_class: The index class to use.
 
789
        :param use_chk_index: Whether to setup and manage a CHK index.
 
790
        """
 
791
        # XXX: This should call self.reset()
 
792
        self.repo = repo
 
793
        self.transport = transport
 
794
        self._index_transport = index_transport
 
795
        self._upload_transport = upload_transport
 
796
        self._pack_transport = pack_transport
 
797
        self._index_builder_class = index_builder_class
 
798
        self._index_class = index_class
 
799
        self._suffix_offsets = {'.rix': 0, '.iix': 1, '.tix': 2, '.six': 3,
 
800
                                '.cix': 4}
 
801
        self.packs = []
 
802
        # name:Pack mapping
 
803
        self._names = None
 
804
        self._packs_by_name = {}
 
805
        # the previous pack-names content
 
806
        self._packs_at_load = None
 
807
        # when a pack is being created by this object, the state of that pack.
 
808
        self._new_pack = None
 
809
        # aggregated revision index data
 
810
        flush = self._flush_new_pack
 
811
        self.revision_index = AggregateIndex(self.reload_pack_names, flush)
 
812
        self.inventory_index = AggregateIndex(self.reload_pack_names, flush)
 
813
        self.text_index = AggregateIndex(self.reload_pack_names, flush)
 
814
        self.signature_index = AggregateIndex(self.reload_pack_names, flush)
 
815
        all_indices = [self.revision_index, self.inventory_index,
 
816
                       self.text_index, self.signature_index]
 
817
        if use_chk_index:
 
818
            self.chk_index = AggregateIndex(self.reload_pack_names, flush)
 
819
            all_indices.append(self.chk_index)
 
820
        else:
 
821
            # used to determine if we're using a chk_index elsewhere.
 
822
            self.chk_index = None
 
823
        # Tell all the CombinedGraphIndex objects about each other, so they can
 
824
        # share hints about which pack names to search first.
 
825
        all_combined = [agg_idx.combined_index for agg_idx in all_indices]
 
826
        for combined_idx in all_combined:
 
827
            combined_idx.set_sibling_indices(
 
828
                set(all_combined).difference([combined_idx]))
 
829
        # resumed packs
 
830
        self._resumed_packs = []
 
831
        self.config_stack = config.LocationStack(self.transport.base)
 
832
 
 
833
    def __repr__(self):
 
834
        return '%s(%r)' % (self.__class__.__name__, self.repo)
 
835
 
 
836
    def add_pack_to_memory(self, pack):
 
837
        """Make a Pack object available to the repository to satisfy queries.
 
838
 
 
839
        :param pack: A Pack object.
 
840
        """
 
841
        if pack.name in self._packs_by_name:
 
842
            raise AssertionError(
 
843
                'pack %s already in _packs_by_name' % (pack.name,))
 
844
        self.packs.append(pack)
 
845
        self._packs_by_name[pack.name] = pack
 
846
        self.revision_index.add_index(pack.revision_index, pack)
 
847
        self.inventory_index.add_index(pack.inventory_index, pack)
 
848
        self.text_index.add_index(pack.text_index, pack)
 
849
        self.signature_index.add_index(pack.signature_index, pack)
 
850
        if self.chk_index is not None:
 
851
            self.chk_index.add_index(pack.chk_index, pack)
 
852
 
 
853
    def all_packs(self):
 
854
        """Return a list of all the Pack objects this repository has.
 
855
 
 
856
        Note that an in-progress pack being created is not returned.
 
857
 
 
858
        :return: A list of Pack objects for all the packs in the repository.
 
859
        """
 
860
        result = []
 
861
        for name in self.names():
 
862
            result.append(self.get_pack_by_name(name))
 
863
        return result
 
864
 
 
865
    def autopack(self):
 
866
        """Pack the pack collection incrementally.
 
867
 
 
868
        This will not attempt global reorganisation or recompression,
 
869
        rather it will just ensure that the total number of packs does
 
870
        not grow without bound. It uses the _max_pack_count method to
 
871
        determine if autopacking is needed, and the pack_distribution
 
872
        method to determine the number of revisions in each pack.
 
873
 
 
874
        If autopacking takes place then the packs name collection will have
 
875
        been flushed to disk - packing requires updating the name collection
 
876
        in synchronisation with certain steps. Otherwise the names collection
 
877
        is not flushed.
 
878
 
 
879
        :return: Something evaluating true if packing took place.
 
880
        """
 
881
        while True:
 
882
            try:
 
883
                return self._do_autopack()
 
884
            except errors.RetryAutopack:
 
885
                # If we get a RetryAutopack exception, we should abort the
 
886
                # current action, and retry.
 
887
                pass
 
888
 
 
889
    def _do_autopack(self):
 
890
        # XXX: Should not be needed when the management of indices is sane.
 
891
        total_revisions = self.revision_index.combined_index.key_count()
 
892
        total_packs = len(self._names)
 
893
        if self._max_pack_count(total_revisions) >= total_packs:
 
894
            return None
 
895
        # determine which packs need changing
 
896
        pack_distribution = self.pack_distribution(total_revisions)
 
897
        existing_packs = []
 
898
        for pack in self.all_packs():
 
899
            revision_count = pack.get_revision_count()
 
900
            if revision_count == 0:
 
901
                # revision less packs are not generated by normal operation,
 
902
                # only by operations like sign-my-commits, and thus will not
 
903
                # tend to grow rapdily or without bound like commit containing
 
904
                # packs do - leave them alone as packing them really should
 
905
                # group their data with the relevant commit, and that may
 
906
                # involve rewriting ancient history - which autopack tries to
 
907
                # avoid. Alternatively we could not group the data but treat
 
908
                # each of these as having a single revision, and thus add
 
909
                # one revision for each to the total revision count, to get
 
910
                # a matching distribution.
 
911
                continue
 
912
            existing_packs.append((revision_count, pack))
 
913
        pack_operations = self.plan_autopack_combinations(
 
914
            existing_packs, pack_distribution)
 
915
        num_new_packs = len(pack_operations)
 
916
        num_old_packs = sum([len(po[1]) for po in pack_operations])
 
917
        num_revs_affected = sum([po[0] for po in pack_operations])
 
918
        mutter('Auto-packing repository %s, which has %d pack files, '
 
919
               'containing %d revisions. Packing %d files into %d affecting %d'
 
920
               ' revisions', str(
 
921
                   self), total_packs, total_revisions, num_old_packs,
 
922
               num_new_packs, num_revs_affected)
 
923
        result = self._execute_pack_operations(pack_operations, packer_class=self.normal_packer_class,
 
924
                                               reload_func=self._restart_autopack)
 
925
        mutter('Auto-packing repository %s completed', str(self))
 
926
        return result
 
927
 
 
928
    def _execute_pack_operations(self, pack_operations, packer_class,
 
929
                                 reload_func=None):
 
930
        """Execute a series of pack operations.
 
931
 
 
932
        :param pack_operations: A list of [revision_count, packs_to_combine].
 
933
        :param packer_class: The class of packer to use
 
934
        :return: The new pack names.
 
935
        """
 
936
        for revision_count, packs in pack_operations:
 
937
            # we may have no-ops from the setup logic
 
938
            if len(packs) == 0:
 
939
                continue
 
940
            packer = packer_class(self, packs, '.autopack',
 
941
                                  reload_func=reload_func)
 
942
            try:
 
943
                result = packer.pack()
 
944
            except errors.RetryWithNewPacks:
 
945
                # An exception is propagating out of this context, make sure
 
946
                # this packer has cleaned up. Packer() doesn't set its new_pack
 
947
                # state into the RepositoryPackCollection object, so we only
 
948
                # have access to it directly here.
 
949
                if packer.new_pack is not None:
 
950
                    packer.new_pack.abort()
 
951
                raise
 
952
            if result is None:
 
953
                return
 
954
            for pack in packs:
 
955
                self._remove_pack_from_memory(pack)
 
956
        # record the newly available packs and stop advertising the old
 
957
        # packs
 
958
        to_be_obsoleted = []
 
959
        for _, packs in pack_operations:
 
960
            to_be_obsoleted.extend(packs)
 
961
        result = self._save_pack_names(clear_obsolete_packs=True,
 
962
                                       obsolete_packs=to_be_obsoleted)
 
963
        return result
 
964
 
 
965
    def _flush_new_pack(self):
 
966
        if self._new_pack is not None:
 
967
            self._new_pack.flush()
 
968
 
 
969
    def lock_names(self):
 
970
        """Acquire the mutex around the pack-names index.
 
971
 
 
972
        This cannot be used in the middle of a read-only transaction on the
 
973
        repository.
 
974
        """
 
975
        self.repo.control_files.lock_write()
 
976
 
 
977
    def _already_packed(self):
 
978
        """Is the collection already packed?"""
 
979
        return not (self.repo._format.pack_compresses or (len(self._names) > 1))
 
980
 
 
981
    def pack(self, hint=None, clean_obsolete_packs=False):
 
982
        """Pack the pack collection totally."""
 
983
        self.ensure_loaded()
 
984
        total_packs = len(self._names)
 
985
        if self._already_packed():
 
986
            return
 
987
        total_revisions = self.revision_index.combined_index.key_count()
 
988
        # XXX: the following may want to be a class, to pack with a given
 
989
        # policy.
 
990
        mutter('Packing repository %s, which has %d pack files, '
 
991
               'containing %d revisions with hint %r.', str(self), total_packs,
 
992
               total_revisions, hint)
 
993
        while True:
 
994
            try:
 
995
                self._try_pack_operations(hint)
 
996
            except RetryPackOperations:
 
997
                continue
 
998
            break
 
999
 
 
1000
        if clean_obsolete_packs:
 
1001
            self._clear_obsolete_packs()
 
1002
 
 
1003
    def _try_pack_operations(self, hint):
 
1004
        """Calculate the pack operations based on the hint (if any), and
 
1005
        execute them.
 
1006
        """
 
1007
        # determine which packs need changing
 
1008
        pack_operations = [[0, []]]
 
1009
        for pack in self.all_packs():
 
1010
            if hint is None or pack.name in hint:
 
1011
                # Either no hint was provided (so we are packing everything),
 
1012
                # or this pack was included in the hint.
 
1013
                pack_operations[-1][0] += pack.get_revision_count()
 
1014
                pack_operations[-1][1].append(pack)
 
1015
        self._execute_pack_operations(pack_operations,
 
1016
                                      packer_class=self.optimising_packer_class,
 
1017
                                      reload_func=self._restart_pack_operations)
 
1018
 
 
1019
    def plan_autopack_combinations(self, existing_packs, pack_distribution):
 
1020
        """Plan a pack operation.
 
1021
 
 
1022
        :param existing_packs: The packs to pack. (A list of (revcount, Pack)
 
1023
            tuples).
 
1024
        :param pack_distribution: A list with the number of revisions desired
 
1025
            in each pack.
 
1026
        """
 
1027
        if len(existing_packs) <= len(pack_distribution):
 
1028
            return []
 
1029
        existing_packs.sort(reverse=True)
 
1030
        pack_operations = [[0, []]]
 
1031
        # plan out what packs to keep, and what to reorganise
 
1032
        while len(existing_packs):
 
1033
            # take the largest pack, and if it's less than the head of the
 
1034
            # distribution chart we will include its contents in the new pack
 
1035
            # for that position. If it's larger, we remove its size from the
 
1036
            # distribution chart
 
1037
            next_pack_rev_count, next_pack = existing_packs.pop(0)
 
1038
            if next_pack_rev_count >= pack_distribution[0]:
 
1039
                # this is already packed 'better' than this, so we can
 
1040
                # not waste time packing it.
 
1041
                while next_pack_rev_count > 0:
 
1042
                    next_pack_rev_count -= pack_distribution[0]
 
1043
                    if next_pack_rev_count >= 0:
 
1044
                        # more to go
 
1045
                        del pack_distribution[0]
 
1046
                    else:
 
1047
                        # didn't use that entire bucket up
 
1048
                        pack_distribution[0] = -next_pack_rev_count
 
1049
            else:
 
1050
                # add the revisions we're going to add to the next output pack
 
1051
                pack_operations[-1][0] += next_pack_rev_count
 
1052
                # allocate this pack to the next pack sub operation
 
1053
                pack_operations[-1][1].append(next_pack)
 
1054
                if pack_operations[-1][0] >= pack_distribution[0]:
 
1055
                    # this pack is used up, shift left.
 
1056
                    del pack_distribution[0]
 
1057
                    pack_operations.append([0, []])
 
1058
        # Now that we know which pack files we want to move, shove them all
 
1059
        # into a single pack file.
 
1060
        final_rev_count = 0
 
1061
        final_pack_list = []
 
1062
        for num_revs, pack_files in pack_operations:
 
1063
            final_rev_count += num_revs
 
1064
            final_pack_list.extend(pack_files)
 
1065
        if len(final_pack_list) == 1:
 
1066
            raise AssertionError('We somehow generated an autopack with a'
 
1067
                                 ' single pack file being moved.')
 
1068
            return []
 
1069
        return [[final_rev_count, final_pack_list]]
 
1070
 
 
1071
    def ensure_loaded(self):
 
1072
        """Ensure we have read names from disk.
 
1073
 
 
1074
        :return: True if the disk names had not been previously read.
 
1075
        """
 
1076
        # NB: if you see an assertion error here, it's probably access against
 
1077
        # an unlocked repo. Naughty.
 
1078
        if not self.repo.is_locked():
 
1079
            raise errors.ObjectNotLocked(self.repo)
 
1080
        if self._names is None:
 
1081
            self._names = {}
 
1082
            self._packs_at_load = set()
 
1083
            for index, key, value in self._iter_disk_pack_index():
 
1084
                name = key[0].decode('ascii')
 
1085
                self._names[name] = self._parse_index_sizes(value)
 
1086
                self._packs_at_load.add((name, value))
 
1087
            result = True
 
1088
        else:
 
1089
            result = False
 
1090
        # populate all the metadata.
 
1091
        self.all_packs()
 
1092
        return result
 
1093
 
 
1094
    def _parse_index_sizes(self, value):
 
1095
        """Parse a string of index sizes."""
 
1096
        return tuple(int(digits) for digits in value.split(b' '))
 
1097
 
 
1098
    def get_pack_by_name(self, name):
 
1099
        """Get a Pack object by name.
 
1100
 
 
1101
        :param name: The name of the pack - e.g. '123456'
 
1102
        :return: A Pack object.
 
1103
        """
 
1104
        try:
 
1105
            return self._packs_by_name[name]
 
1106
        except KeyError:
 
1107
            rev_index = self._make_index(name, '.rix')
 
1108
            inv_index = self._make_index(name, '.iix')
 
1109
            txt_index = self._make_index(name, '.tix')
 
1110
            sig_index = self._make_index(name, '.six')
 
1111
            if self.chk_index is not None:
 
1112
                chk_index = self._make_index(name, '.cix', is_chk=True)
 
1113
            else:
 
1114
                chk_index = None
 
1115
            result = ExistingPack(self._pack_transport, name, rev_index,
 
1116
                                  inv_index, txt_index, sig_index, chk_index)
 
1117
            self.add_pack_to_memory(result)
 
1118
            return result
 
1119
 
 
1120
    def _resume_pack(self, name):
 
1121
        """Get a suspended Pack object by name.
 
1122
 
 
1123
        :param name: The name of the pack - e.g. '123456'
 
1124
        :return: A Pack object.
 
1125
        """
 
1126
        if not re.match('[a-f0-9]{32}', name):
 
1127
            # Tokens should be md5sums of the suspended pack file, i.e. 32 hex
 
1128
            # digits.
 
1129
            raise errors.UnresumableWriteGroup(
 
1130
                self.repo, [name], 'Malformed write group token')
 
1131
        try:
 
1132
            rev_index = self._make_index(name, '.rix', resume=True)
 
1133
            inv_index = self._make_index(name, '.iix', resume=True)
 
1134
            txt_index = self._make_index(name, '.tix', resume=True)
 
1135
            sig_index = self._make_index(name, '.six', resume=True)
 
1136
            if self.chk_index is not None:
 
1137
                chk_index = self._make_index(name, '.cix', resume=True,
 
1138
                                             is_chk=True)
 
1139
            else:
 
1140
                chk_index = None
 
1141
            result = self.resumed_pack_factory(name, rev_index, inv_index,
 
1142
                                               txt_index, sig_index, self._upload_transport,
 
1143
                                               self._pack_transport, self._index_transport, self,
 
1144
                                               chk_index=chk_index)
 
1145
        except errors.NoSuchFile as e:
 
1146
            raise errors.UnresumableWriteGroup(self.repo, [name], str(e))
 
1147
        self.add_pack_to_memory(result)
 
1148
        self._resumed_packs.append(result)
 
1149
        return result
 
1150
 
 
1151
    def allocate(self, a_new_pack):
 
1152
        """Allocate name in the list of packs.
 
1153
 
 
1154
        :param a_new_pack: A NewPack instance to be added to the collection of
 
1155
            packs for this repository.
 
1156
        """
 
1157
        self.ensure_loaded()
 
1158
        if a_new_pack.name in self._names:
 
1159
            raise errors.BzrError(
 
1160
                'Pack %r already exists in %s' % (a_new_pack.name, self))
 
1161
        self._names[a_new_pack.name] = tuple(a_new_pack.index_sizes)
 
1162
        self.add_pack_to_memory(a_new_pack)
 
1163
 
 
1164
    def _iter_disk_pack_index(self):
 
1165
        """Iterate over the contents of the pack-names index.
 
1166
 
 
1167
        This is used when loading the list from disk, and before writing to
 
1168
        detect updates from others during our write operation.
 
1169
        :return: An iterator of the index contents.
 
1170
        """
 
1171
        return self._index_class(self.transport, 'pack-names', None
 
1172
                                 ).iter_all_entries()
 
1173
 
 
1174
    def _make_index(self, name, suffix, resume=False, is_chk=False):
 
1175
        size_offset = self._suffix_offsets[suffix]
 
1176
        index_name = name + suffix
 
1177
        if resume:
 
1178
            transport = self._upload_transport
 
1179
            index_size = transport.stat(index_name).st_size
 
1180
        else:
 
1181
            transport = self._index_transport
 
1182
            index_size = self._names[name][size_offset]
 
1183
        index = self._index_class(transport, index_name, index_size,
 
1184
                                  unlimited_cache=is_chk)
 
1185
        if is_chk and self._index_class is btree_index.BTreeGraphIndex:
 
1186
            index._leaf_factory = btree_index._gcchk_factory
 
1187
        return index
 
1188
 
 
1189
    def _max_pack_count(self, total_revisions):
 
1190
        """Return the maximum number of packs to use for total revisions.
 
1191
 
 
1192
        :param total_revisions: The total number of revisions in the
 
1193
            repository.
 
1194
        """
 
1195
        if not total_revisions:
 
1196
            return 1
 
1197
        digits = str(total_revisions)
 
1198
        result = 0
 
1199
        for digit in digits:
 
1200
            result += int(digit)
 
1201
        return result
 
1202
 
 
1203
    def names(self):
 
1204
        """Provide an order to the underlying names."""
 
1205
        return sorted(self._names.keys())
 
1206
 
 
1207
    def _obsolete_packs(self, packs):
 
1208
        """Move a number of packs which have been obsoleted out of the way.
 
1209
 
 
1210
        Each pack and its associated indices are moved out of the way.
 
1211
 
 
1212
        Note: for correctness this function should only be called after a new
 
1213
        pack names index has been written without these pack names, and with
 
1214
        the names of packs that contain the data previously available via these
 
1215
        packs.
 
1216
 
 
1217
        :param packs: The packs to obsolete.
 
1218
        :param return: None.
 
1219
        """
 
1220
        for pack in packs:
 
1221
            try:
 
1222
                try:
 
1223
                    pack.pack_transport.move(pack.file_name(),
 
1224
                                             '../obsolete_packs/' + pack.file_name())
 
1225
                except errors.NoSuchFile:
 
1226
                    # perhaps obsolete_packs was removed? Let's create it and
 
1227
                    # try again
 
1228
                    try:
 
1229
                        pack.pack_transport.mkdir('../obsolete_packs/')
 
1230
                    except errors.FileExists:
 
1231
                        pass
 
1232
                    pack.pack_transport.move(pack.file_name(),
 
1233
                                             '../obsolete_packs/' + pack.file_name())
 
1234
            except (errors.PathError, errors.TransportError) as e:
 
1235
                # TODO: Should these be warnings or mutters?
 
1236
                mutter("couldn't rename obsolete pack, skipping it:\n%s"
 
1237
                       % (e,))
 
1238
            # TODO: Probably needs to know all possible indices for this pack
 
1239
            # - or maybe list the directory and move all indices matching this
 
1240
            # name whether we recognize it or not?
 
1241
            suffixes = ['.iix', '.six', '.tix', '.rix']
 
1242
            if self.chk_index is not None:
 
1243
                suffixes.append('.cix')
 
1244
            for suffix in suffixes:
 
1245
                try:
 
1246
                    self._index_transport.move(pack.name + suffix,
 
1247
                                               '../obsolete_packs/' + pack.name + suffix)
 
1248
                except (errors.PathError, errors.TransportError) as e:
 
1249
                    mutter("couldn't rename obsolete index, skipping it:\n%s"
 
1250
                           % (e,))
 
1251
 
 
1252
    def pack_distribution(self, total_revisions):
 
1253
        """Generate a list of the number of revisions to put in each pack.
 
1254
 
 
1255
        :param total_revisions: The total number of revisions in the
 
1256
            repository.
 
1257
        """
 
1258
        if total_revisions == 0:
 
1259
            return [0]
 
1260
        digits = reversed(str(total_revisions))
 
1261
        result = []
 
1262
        for exponent, count in enumerate(digits):
 
1263
            size = 10 ** exponent
 
1264
            for pos in range(int(count)):
 
1265
                result.append(size)
 
1266
        return list(reversed(result))
 
1267
 
 
1268
    def _pack_tuple(self, name):
 
1269
        """Return a tuple with the transport and file name for a pack name."""
 
1270
        return self._pack_transport, name + '.pack'
 
1271
 
 
1272
    def _remove_pack_from_memory(self, pack):
 
1273
        """Remove pack from the packs accessed by this repository.
 
1274
 
 
1275
        Only affects memory state, until self._save_pack_names() is invoked.
 
1276
        """
 
1277
        self._names.pop(pack.name)
 
1278
        self._packs_by_name.pop(pack.name)
 
1279
        self._remove_pack_indices(pack)
 
1280
        self.packs.remove(pack)
 
1281
 
 
1282
    def _remove_pack_indices(self, pack, ignore_missing=False):
 
1283
        """Remove the indices for pack from the aggregated indices.
 
1284
 
 
1285
        :param ignore_missing: Suppress KeyErrors from calling remove_index.
 
1286
        """
 
1287
        for index_type in Pack.index_definitions:
 
1288
            attr_name = index_type + '_index'
 
1289
            aggregate_index = getattr(self, attr_name)
 
1290
            if aggregate_index is not None:
 
1291
                pack_index = getattr(pack, attr_name)
 
1292
                try:
 
1293
                    aggregate_index.remove_index(pack_index)
 
1294
                except KeyError:
 
1295
                    if ignore_missing:
 
1296
                        continue
 
1297
                    raise
 
1298
 
 
1299
    def reset(self):
 
1300
        """Clear all cached data."""
 
1301
        # cached revision data
 
1302
        self.revision_index.clear()
 
1303
        # cached signature data
 
1304
        self.signature_index.clear()
 
1305
        # cached file text data
 
1306
        self.text_index.clear()
 
1307
        # cached inventory data
 
1308
        self.inventory_index.clear()
 
1309
        # cached chk data
 
1310
        if self.chk_index is not None:
 
1311
            self.chk_index.clear()
 
1312
        # remove the open pack
 
1313
        self._new_pack = None
 
1314
        # information about packs.
 
1315
        self._names = None
 
1316
        self.packs = []
 
1317
        self._packs_by_name = {}
 
1318
        self._packs_at_load = None
 
1319
 
 
1320
    def _unlock_names(self):
 
1321
        """Release the mutex around the pack-names index."""
 
1322
        self.repo.control_files.unlock()
 
1323
 
 
1324
    def _diff_pack_names(self):
 
1325
        """Read the pack names from disk, and compare it to the one in memory.
 
1326
 
 
1327
        :return: (disk_nodes, deleted_nodes, new_nodes)
 
1328
            disk_nodes    The final set of nodes that should be referenced
 
1329
            deleted_nodes Nodes which have been removed from when we started
 
1330
            new_nodes     Nodes that are newly introduced
 
1331
        """
 
1332
        # load the disk nodes across
 
1333
        disk_nodes = set()
 
1334
        for index, key, value in self._iter_disk_pack_index():
 
1335
            disk_nodes.add((key[0].decode('ascii'), value))
 
1336
        orig_disk_nodes = set(disk_nodes)
 
1337
 
 
1338
        # do a two-way diff against our original content
 
1339
        current_nodes = set()
 
1340
        for name, sizes in viewitems(self._names):
 
1341
            current_nodes.add(
 
1342
                (name, b' '.join(b'%d' % size for size in sizes)))
 
1343
 
 
1344
        # Packs no longer present in the repository, which were present when we
 
1345
        # locked the repository
 
1346
        deleted_nodes = self._packs_at_load - current_nodes
 
1347
        # Packs which this process is adding
 
1348
        new_nodes = current_nodes - self._packs_at_load
 
1349
 
 
1350
        # Update the disk_nodes set to include the ones we are adding, and
 
1351
        # remove the ones which were removed by someone else
 
1352
        disk_nodes.difference_update(deleted_nodes)
 
1353
        disk_nodes.update(new_nodes)
 
1354
 
 
1355
        return disk_nodes, deleted_nodes, new_nodes, orig_disk_nodes
 
1356
 
 
1357
    def _syncronize_pack_names_from_disk_nodes(self, disk_nodes):
 
1358
        """Given the correct set of pack files, update our saved info.
 
1359
 
 
1360
        :return: (removed, added, modified)
 
1361
            removed     pack names removed from self._names
 
1362
            added       pack names added to self._names
 
1363
            modified    pack names that had changed value
 
1364
        """
 
1365
        removed = []
 
1366
        added = []
 
1367
        modified = []
 
1368
        ## self._packs_at_load = disk_nodes
 
1369
        new_names = dict(disk_nodes)
 
1370
        # drop no longer present nodes
 
1371
        for pack in self.all_packs():
 
1372
            if pack.name not in new_names:
 
1373
                removed.append(pack.name)
 
1374
                self._remove_pack_from_memory(pack)
 
1375
        # add new nodes/refresh existing ones
 
1376
        for name, value in disk_nodes:
 
1377
            sizes = self._parse_index_sizes(value)
 
1378
            if name in self._names:
 
1379
                # existing
 
1380
                if sizes != self._names[name]:
 
1381
                    # the pack for name has had its indices replaced - rare but
 
1382
                    # important to handle. XXX: probably can never happen today
 
1383
                    # because the three-way merge code above does not handle it
 
1384
                    # - you may end up adding the same key twice to the new
 
1385
                    # disk index because the set values are the same, unless
 
1386
                    # the only index shows up as deleted by the set difference
 
1387
                    # - which it may. Until there is a specific test for this,
 
1388
                    # assume it's broken. RBC 20071017.
 
1389
                    self._remove_pack_from_memory(self.get_pack_by_name(name))
 
1390
                    self._names[name] = sizes
 
1391
                    self.get_pack_by_name(name)
 
1392
                    modified.append(name)
 
1393
            else:
 
1394
                # new
 
1395
                self._names[name] = sizes
 
1396
                self.get_pack_by_name(name)
 
1397
                added.append(name)
 
1398
        return removed, added, modified
 
1399
 
 
1400
    def _save_pack_names(self, clear_obsolete_packs=False, obsolete_packs=None):
 
1401
        """Save the list of packs.
 
1402
 
 
1403
        This will take out the mutex around the pack names list for the
 
1404
        duration of the method call. If concurrent updates have been made, a
 
1405
        three-way merge between the current list and the current in memory list
 
1406
        is performed.
 
1407
 
 
1408
        :param clear_obsolete_packs: If True, clear out the contents of the
 
1409
            obsolete_packs directory.
 
1410
        :param obsolete_packs: Packs that are obsolete once the new pack-names
 
1411
            file has been written.
 
1412
        :return: A list of the names saved that were not previously on disk.
 
1413
        """
 
1414
        already_obsolete = []
 
1415
        self.lock_names()
 
1416
        try:
 
1417
            builder = self._index_builder_class()
 
1418
            (disk_nodes, deleted_nodes, new_nodes,
 
1419
             orig_disk_nodes) = self._diff_pack_names()
 
1420
            # TODO: handle same-name, index-size-changes here -
 
1421
            # e.g. use the value from disk, not ours, *unless* we're the one
 
1422
            # changing it.
 
1423
            for name, value in disk_nodes:
 
1424
                builder.add_node((name.encode('ascii'), ), value)
 
1425
            self.transport.put_file('pack-names', builder.finish(),
 
1426
                                    mode=self.repo.controldir._get_file_mode())
 
1427
            self._packs_at_load = disk_nodes
 
1428
            if clear_obsolete_packs:
 
1429
                to_preserve = None
 
1430
                if obsolete_packs:
 
1431
                    to_preserve = {o.name for o in obsolete_packs}
 
1432
                already_obsolete = self._clear_obsolete_packs(to_preserve)
 
1433
        finally:
 
1434
            self._unlock_names()
 
1435
        # synchronise the memory packs list with what we just wrote:
 
1436
        self._syncronize_pack_names_from_disk_nodes(disk_nodes)
 
1437
        if obsolete_packs:
 
1438
            # TODO: We could add one more condition here. "if o.name not in
 
1439
            #       orig_disk_nodes and o != the new_pack we haven't written to
 
1440
            #       disk yet. However, the new pack object is not easily
 
1441
            #       accessible here (it would have to be passed through the
 
1442
            #       autopacking code, etc.)
 
1443
            obsolete_packs = [o for o in obsolete_packs
 
1444
                              if o.name not in already_obsolete]
 
1445
            self._obsolete_packs(obsolete_packs)
 
1446
        return [new_node[0] for new_node in new_nodes]
 
1447
 
 
1448
    def reload_pack_names(self):
 
1449
        """Sync our pack listing with what is present in the repository.
 
1450
 
 
1451
        This should be called when we find out that something we thought was
 
1452
        present is now missing. This happens when another process re-packs the
 
1453
        repository, etc.
 
1454
 
 
1455
        :return: True if the in-memory list of packs has been altered at all.
 
1456
        """
 
1457
        # The ensure_loaded call is to handle the case where the first call
 
1458
        # made involving the collection was to reload_pack_names, where we
 
1459
        # don't have a view of disk contents. It's a bit of a bandaid, and
 
1460
        # causes two reads of pack-names, but it's a rare corner case not
 
1461
        # struck with regular push/pull etc.
 
1462
        first_read = self.ensure_loaded()
 
1463
        if first_read:
 
1464
            return True
 
1465
        # out the new value.
 
1466
        (disk_nodes, deleted_nodes, new_nodes,
 
1467
         orig_disk_nodes) = self._diff_pack_names()
 
1468
        # _packs_at_load is meant to be the explicit list of names in
 
1469
        # 'pack-names' at then start. As such, it should not contain any
 
1470
        # pending names that haven't been written out yet.
 
1471
        self._packs_at_load = orig_disk_nodes
 
1472
        (removed, added,
 
1473
         modified) = self._syncronize_pack_names_from_disk_nodes(disk_nodes)
 
1474
        if removed or added or modified:
 
1475
            return True
 
1476
        return False
 
1477
 
 
1478
    def _restart_autopack(self):
 
1479
        """Reload the pack names list, and restart the autopack code."""
 
1480
        if not self.reload_pack_names():
 
1481
            # Re-raise the original exception, because something went missing
 
1482
            # and a restart didn't find it
 
1483
            raise
 
1484
        raise errors.RetryAutopack(self.repo, False, sys.exc_info())
 
1485
 
 
1486
    def _restart_pack_operations(self):
 
1487
        """Reload the pack names list, and restart the autopack code."""
 
1488
        if not self.reload_pack_names():
 
1489
            # Re-raise the original exception, because something went missing
 
1490
            # and a restart didn't find it
 
1491
            raise
 
1492
        raise RetryPackOperations(self.repo, False, sys.exc_info())
 
1493
 
 
1494
    def _clear_obsolete_packs(self, preserve=None):
 
1495
        """Delete everything from the obsolete-packs directory.
 
1496
 
 
1497
        :return: A list of pack identifiers (the filename without '.pack') that
 
1498
            were found in obsolete_packs.
 
1499
        """
 
1500
        found = []
 
1501
        obsolete_pack_transport = self.transport.clone('obsolete_packs')
 
1502
        if preserve is None:
 
1503
            preserve = set()
 
1504
        try:
 
1505
            obsolete_pack_files = obsolete_pack_transport.list_dir('.')
 
1506
        except errors.NoSuchFile:
 
1507
            return found
 
1508
        for filename in obsolete_pack_files:
 
1509
            name, ext = osutils.splitext(filename)
 
1510
            if ext == '.pack':
 
1511
                found.append(name)
 
1512
            if name in preserve:
 
1513
                continue
 
1514
            try:
 
1515
                obsolete_pack_transport.delete(filename)
 
1516
            except (errors.PathError, errors.TransportError) as e:
 
1517
                warning("couldn't delete obsolete pack, skipping it:\n%s"
 
1518
                        % (e,))
 
1519
        return found
 
1520
 
 
1521
    def _start_write_group(self):
 
1522
        # Do not permit preparation for writing if we're not in a 'write lock'.
 
1523
        if not self.repo.is_write_locked():
 
1524
            raise errors.NotWriteLocked(self)
 
1525
        self._new_pack = self.pack_factory(self, upload_suffix='.pack',
 
1526
                                           file_mode=self.repo.controldir._get_file_mode())
 
1527
        # allow writing: queue writes to a new index
 
1528
        self.revision_index.add_writable_index(self._new_pack.revision_index,
 
1529
                                               self._new_pack)
 
1530
        self.inventory_index.add_writable_index(self._new_pack.inventory_index,
 
1531
                                                self._new_pack)
 
1532
        self.text_index.add_writable_index(self._new_pack.text_index,
 
1533
                                           self._new_pack)
 
1534
        self._new_pack.text_index.set_optimize(combine_backing_indices=False)
 
1535
        self.signature_index.add_writable_index(self._new_pack.signature_index,
 
1536
                                                self._new_pack)
 
1537
        if self.chk_index is not None:
 
1538
            self.chk_index.add_writable_index(self._new_pack.chk_index,
 
1539
                                              self._new_pack)
 
1540
            self.repo.chk_bytes._index._add_callback = self.chk_index.add_callback
 
1541
            self._new_pack.chk_index.set_optimize(
 
1542
                combine_backing_indices=False)
 
1543
 
 
1544
        self.repo.inventories._index._add_callback = self.inventory_index.add_callback
 
1545
        self.repo.revisions._index._add_callback = self.revision_index.add_callback
 
1546
        self.repo.signatures._index._add_callback = self.signature_index.add_callback
 
1547
        self.repo.texts._index._add_callback = self.text_index.add_callback
 
1548
 
 
1549
    def _abort_write_group(self):
 
1550
        # FIXME: just drop the transient index.
 
1551
        # forget what names there are
 
1552
        if self._new_pack is not None:
 
1553
            operation = cleanup.OperationWithCleanups(self._new_pack.abort)
 
1554
            operation.add_cleanup(setattr, self, '_new_pack', None)
 
1555
            # If we aborted while in the middle of finishing the write
 
1556
            # group, _remove_pack_indices could fail because the indexes are
 
1557
            # already gone.  But they're not there we shouldn't fail in this
 
1558
            # case, so we pass ignore_missing=True.
 
1559
            operation.add_cleanup(self._remove_pack_indices, self._new_pack,
 
1560
                                  ignore_missing=True)
 
1561
            operation.run_simple()
 
1562
        for resumed_pack in self._resumed_packs:
 
1563
            operation = cleanup.OperationWithCleanups(resumed_pack.abort)
 
1564
            # See comment in previous finally block.
 
1565
            operation.add_cleanup(self._remove_pack_indices, resumed_pack,
 
1566
                                  ignore_missing=True)
 
1567
            operation.run_simple()
 
1568
        del self._resumed_packs[:]
 
1569
 
 
1570
    def _remove_resumed_pack_indices(self):
 
1571
        for resumed_pack in self._resumed_packs:
 
1572
            self._remove_pack_indices(resumed_pack)
 
1573
        del self._resumed_packs[:]
 
1574
 
 
1575
    def _check_new_inventories(self):
 
1576
        """Detect missing inventories in this write group.
 
1577
 
 
1578
        :returns: list of strs, summarising any problems found.  If the list is
 
1579
            empty no problems were found.
 
1580
        """
 
1581
        # The base implementation does no checks.  GCRepositoryPackCollection
 
1582
        # overrides this.
 
1583
        return []
 
1584
 
 
1585
    def _commit_write_group(self):
 
1586
        all_missing = set()
 
1587
        for prefix, versioned_file in (
 
1588
                ('revisions', self.repo.revisions),
 
1589
                ('inventories', self.repo.inventories),
 
1590
                ('texts', self.repo.texts),
 
1591
                ('signatures', self.repo.signatures),
 
1592
                ):
 
1593
            missing = versioned_file.get_missing_compression_parent_keys()
 
1594
            all_missing.update([(prefix,) + key for key in missing])
 
1595
        if all_missing:
 
1596
            raise errors.BzrCheckError(
 
1597
                "Repository %s has missing compression parent(s) %r "
 
1598
                % (self.repo, sorted(all_missing)))
 
1599
        problems = self._check_new_inventories()
 
1600
        if problems:
 
1601
            problems_summary = '\n'.join(problems)
 
1602
            raise errors.BzrCheckError(
 
1603
                "Cannot add revision(s) to repository: " + problems_summary)
 
1604
        self._remove_pack_indices(self._new_pack)
 
1605
        any_new_content = False
 
1606
        if self._new_pack.data_inserted():
 
1607
            # get all the data to disk and read to use
 
1608
            self._new_pack.finish()
 
1609
            self.allocate(self._new_pack)
 
1610
            self._new_pack = None
 
1611
            any_new_content = True
 
1612
        else:
 
1613
            self._new_pack.abort()
 
1614
            self._new_pack = None
 
1615
        for resumed_pack in self._resumed_packs:
 
1616
            # XXX: this is a pretty ugly way to turn the resumed pack into a
 
1617
            # properly committed pack.
 
1618
            self._names[resumed_pack.name] = None
 
1619
            self._remove_pack_from_memory(resumed_pack)
 
1620
            resumed_pack.finish()
 
1621
            self.allocate(resumed_pack)
 
1622
            any_new_content = True
 
1623
        del self._resumed_packs[:]
 
1624
        if any_new_content:
 
1625
            result = self.autopack()
 
1626
            if not result:
 
1627
                # when autopack takes no steps, the names list is still
 
1628
                # unsaved.
 
1629
                return self._save_pack_names()
 
1630
            return result
 
1631
        return []
 
1632
 
 
1633
    def _suspend_write_group(self):
 
1634
        tokens = [pack.name for pack in self._resumed_packs]
 
1635
        self._remove_pack_indices(self._new_pack)
 
1636
        if self._new_pack.data_inserted():
 
1637
            # get all the data to disk and read to use
 
1638
            self._new_pack.finish(suspend=True)
 
1639
            tokens.append(self._new_pack.name)
 
1640
            self._new_pack = None
 
1641
        else:
 
1642
            self._new_pack.abort()
 
1643
            self._new_pack = None
 
1644
        self._remove_resumed_pack_indices()
 
1645
        return tokens
 
1646
 
 
1647
    def _resume_write_group(self, tokens):
 
1648
        for token in tokens:
 
1649
            self._resume_pack(token)
 
1650
 
 
1651
 
 
1652
class PackRepository(MetaDirVersionedFileRepository):
 
1653
    """Repository with knit objects stored inside pack containers.
 
1654
 
 
1655
    The layering for a KnitPackRepository is:
 
1656
 
 
1657
    Graph        |  HPSS    | Repository public layer |
 
1658
    ===================================================
 
1659
    Tuple based apis below, string based, and key based apis above
 
1660
    ---------------------------------------------------
 
1661
    VersionedFiles
 
1662
      Provides .texts, .revisions etc
 
1663
      This adapts the N-tuple keys to physical knit records which only have a
 
1664
      single string identifier (for historical reasons), which in older formats
 
1665
      was always the revision_id, and in the mapped code for packs is always
 
1666
      the last element of key tuples.
 
1667
    ---------------------------------------------------
 
1668
    GraphIndex
 
1669
      A separate GraphIndex is used for each of the
 
1670
      texts/inventories/revisions/signatures contained within each individual
 
1671
      pack file. The GraphIndex layer works in N-tuples and is unaware of any
 
1672
      semantic value.
 
1673
    ===================================================
 
1674
 
 
1675
    """
 
1676
 
 
1677
    # These attributes are inherited from the Repository base class. Setting
 
1678
    # them to None ensures that if the constructor is changed to not initialize
 
1679
    # them, or a subclass fails to call the constructor, that an error will
 
1680
    # occur rather than the system working but generating incorrect data.
 
1681
    _commit_builder_class = None
 
1682
    _serializer = None
 
1683
 
 
1684
    def __init__(self, _format, a_controldir, control_files, _commit_builder_class,
 
1685
                 _serializer):
 
1686
        MetaDirRepository.__init__(self, _format, a_controldir, control_files)
 
1687
        self._commit_builder_class = _commit_builder_class
 
1688
        self._serializer = _serializer
 
1689
        self._reconcile_fixes_text_parents = True
 
1690
        if self._format.supports_external_lookups:
 
1691
            self._unstacked_provider = graph.CachingParentsProvider(
 
1692
                self._make_parents_provider_unstacked())
 
1693
        else:
 
1694
            self._unstacked_provider = graph.CachingParentsProvider(self)
 
1695
        self._unstacked_provider.disable_cache()
 
1696
 
 
1697
    def _all_revision_ids(self):
 
1698
        """See Repository.all_revision_ids()."""
 
1699
        with self.lock_read():
 
1700
            return [key[0] for key in self.revisions.keys()]
 
1701
 
 
1702
    def _abort_write_group(self):
 
1703
        self.revisions._index._key_dependencies.clear()
 
1704
        self._pack_collection._abort_write_group()
 
1705
 
 
1706
    def _make_parents_provider(self):
 
1707
        if not self._format.supports_external_lookups:
 
1708
            return self._unstacked_provider
 
1709
        return graph.StackedParentsProvider(_LazyListJoin(
 
1710
            [self._unstacked_provider], self._fallback_repositories))
 
1711
 
 
1712
    def _refresh_data(self):
 
1713
        if not self.is_locked():
 
1714
            return
 
1715
        self._pack_collection.reload_pack_names()
 
1716
        self._unstacked_provider.disable_cache()
 
1717
        self._unstacked_provider.enable_cache()
 
1718
 
 
1719
    def _start_write_group(self):
 
1720
        self._pack_collection._start_write_group()
 
1721
 
 
1722
    def _commit_write_group(self):
 
1723
        hint = self._pack_collection._commit_write_group()
 
1724
        self.revisions._index._key_dependencies.clear()
 
1725
        # The commit may have added keys that were previously cached as
 
1726
        # missing, so reset the cache.
 
1727
        self._unstacked_provider.disable_cache()
 
1728
        self._unstacked_provider.enable_cache()
 
1729
        return hint
 
1730
 
 
1731
    def suspend_write_group(self):
 
1732
        # XXX check self._write_group is self.get_transaction()?
 
1733
        tokens = self._pack_collection._suspend_write_group()
 
1734
        self.revisions._index._key_dependencies.clear()
 
1735
        self._write_group = None
 
1736
        return tokens
 
1737
 
 
1738
    def _resume_write_group(self, tokens):
 
1739
        self._start_write_group()
 
1740
        try:
 
1741
            self._pack_collection._resume_write_group(tokens)
 
1742
        except errors.UnresumableWriteGroup:
 
1743
            self._abort_write_group()
 
1744
            raise
 
1745
        for pack in self._pack_collection._resumed_packs:
 
1746
            self.revisions._index.scan_unvalidated_index(pack.revision_index)
 
1747
 
 
1748
    def get_transaction(self):
 
1749
        if self._write_lock_count:
 
1750
            return self._transaction
 
1751
        else:
 
1752
            return self.control_files.get_transaction()
 
1753
 
 
1754
    def is_locked(self):
 
1755
        return self._write_lock_count or self.control_files.is_locked()
 
1756
 
 
1757
    def is_write_locked(self):
 
1758
        return self._write_lock_count
 
1759
 
 
1760
    def lock_write(self, token=None):
 
1761
        """Lock the repository for writes.
 
1762
 
 
1763
        :return: A breezy.repository.RepositoryWriteLockResult.
 
1764
        """
 
1765
        locked = self.is_locked()
 
1766
        if not self._write_lock_count and locked:
 
1767
            raise errors.ReadOnlyError(self)
 
1768
        self._write_lock_count += 1
 
1769
        if self._write_lock_count == 1:
 
1770
            self._transaction = transactions.WriteTransaction()
 
1771
        if not locked:
 
1772
            if 'relock' in debug.debug_flags and self._prev_lock == 'w':
 
1773
                note('%r was write locked again', self)
 
1774
            self._prev_lock = 'w'
 
1775
            self._unstacked_provider.enable_cache()
 
1776
            for repo in self._fallback_repositories:
 
1777
                # Writes don't affect fallback repos
 
1778
                repo.lock_read()
 
1779
            self._refresh_data()
 
1780
        return RepositoryWriteLockResult(self.unlock, None)
 
1781
 
 
1782
    def lock_read(self):
 
1783
        """Lock the repository for reads.
 
1784
 
 
1785
        :return: A breezy.lock.LogicalLockResult.
 
1786
        """
 
1787
        locked = self.is_locked()
 
1788
        if self._write_lock_count:
 
1789
            self._write_lock_count += 1
 
1790
        else:
 
1791
            self.control_files.lock_read()
 
1792
        if not locked:
 
1793
            if 'relock' in debug.debug_flags and self._prev_lock == 'r':
 
1794
                note('%r was read locked again', self)
 
1795
            self._prev_lock = 'r'
 
1796
            self._unstacked_provider.enable_cache()
 
1797
            for repo in self._fallback_repositories:
 
1798
                repo.lock_read()
 
1799
            self._refresh_data()
 
1800
        return LogicalLockResult(self.unlock)
 
1801
 
 
1802
    def leave_lock_in_place(self):
 
1803
        # not supported - raise an error
 
1804
        raise NotImplementedError(self.leave_lock_in_place)
 
1805
 
 
1806
    def dont_leave_lock_in_place(self):
 
1807
        # not supported - raise an error
 
1808
        raise NotImplementedError(self.dont_leave_lock_in_place)
 
1809
 
 
1810
    def pack(self, hint=None, clean_obsolete_packs=False):
 
1811
        """Compress the data within the repository.
 
1812
 
 
1813
        This will pack all the data to a single pack. In future it may
 
1814
        recompress deltas or do other such expensive operations.
 
1815
        """
 
1816
        with self.lock_write():
 
1817
            self._pack_collection.pack(
 
1818
                hint=hint, clean_obsolete_packs=clean_obsolete_packs)
 
1819
 
 
1820
    def reconcile(self, other=None, thorough=False):
 
1821
        """Reconcile this repository."""
 
1822
        from .reconcile import PackReconciler
 
1823
        with self.lock_write():
 
1824
            reconciler = PackReconciler(self, thorough=thorough)
 
1825
            return reconciler.reconcile()
 
1826
 
 
1827
    def _reconcile_pack(self, collection, packs, extension, revs, pb):
 
1828
        raise NotImplementedError(self._reconcile_pack)
 
1829
 
 
1830
    @only_raises(errors.LockNotHeld, errors.LockBroken)
 
1831
    def unlock(self):
 
1832
        if self._write_lock_count == 1 and self._write_group is not None:
 
1833
            self.abort_write_group()
 
1834
            self._unstacked_provider.disable_cache()
 
1835
            self._transaction = None
 
1836
            self._write_lock_count = 0
 
1837
            raise errors.BzrError(
 
1838
                'Must end write group before releasing write lock on %s'
 
1839
                % self)
 
1840
        if self._write_lock_count:
 
1841
            self._write_lock_count -= 1
 
1842
            if not self._write_lock_count:
 
1843
                transaction = self._transaction
 
1844
                self._transaction = None
 
1845
                transaction.finish()
 
1846
        else:
 
1847
            self.control_files.unlock()
 
1848
 
 
1849
        if not self.is_locked():
 
1850
            self._unstacked_provider.disable_cache()
 
1851
            for repo in self._fallback_repositories:
 
1852
                repo.unlock()
 
1853
 
 
1854
 
 
1855
class RepositoryFormatPack(MetaDirVersionedFileRepositoryFormat):
 
1856
    """Format logic for pack structured repositories.
 
1857
 
 
1858
    This repository format has:
 
1859
     - a list of packs in pack-names
 
1860
     - packs in packs/NAME.pack
 
1861
     - indices in indices/NAME.{iix,six,tix,rix}
 
1862
     - knit deltas in the packs, knit indices mapped to the indices.
 
1863
     - thunk objects to support the knits programming API.
 
1864
     - a format marker of its own
 
1865
     - an optional 'shared-storage' flag
 
1866
     - an optional 'no-working-trees' flag
 
1867
     - a LockDir lock
 
1868
    """
 
1869
 
 
1870
    # Set this attribute in derived classes to control the repository class
 
1871
    # created by open and initialize.
 
1872
    repository_class = None
 
1873
    # Set this attribute in derived classes to control the
 
1874
    # _commit_builder_class that the repository objects will have passed to
 
1875
    # their constructor.
 
1876
    _commit_builder_class = None
 
1877
    # Set this attribute in derived clases to control the _serializer that the
 
1878
    # repository objects will have passed to their constructor.
 
1879
    _serializer = None
 
1880
    # Packs are not confused by ghosts.
 
1881
    supports_ghosts = True
 
1882
    # External references are not supported in pack repositories yet.
 
1883
    supports_external_lookups = False
 
1884
    # Most pack formats do not use chk lookups.
 
1885
    supports_chks = False
 
1886
    # What index classes to use
 
1887
    index_builder_class = None
 
1888
    index_class = None
 
1889
    _fetch_uses_deltas = True
 
1890
    fast_deltas = False
 
1891
    supports_funky_characters = True
 
1892
    revision_graph_can_have_wrong_parents = True
 
1893
 
 
1894
    def initialize(self, a_controldir, shared=False):
 
1895
        """Create a pack based repository.
 
1896
 
 
1897
        :param a_controldir: bzrdir to contain the new repository; must already
 
1898
            be initialized.
 
1899
        :param shared: If true the repository will be initialized as a shared
 
1900
                       repository.
 
1901
        """
 
1902
        mutter('creating repository in %s.', a_controldir.transport.base)
 
1903
        dirs = ['indices', 'obsolete_packs', 'packs', 'upload']
 
1904
        builder = self.index_builder_class()
 
1905
        files = [('pack-names', builder.finish())]
 
1906
        utf8_files = [('format', self.get_format_string())]
 
1907
 
 
1908
        self._upload_blank_content(
 
1909
            a_controldir, dirs, files, utf8_files, shared)
 
1910
        repository = self.open(a_controldir=a_controldir, _found=True)
 
1911
        self._run_post_repo_init_hooks(repository, a_controldir, shared)
 
1912
        return repository
 
1913
 
 
1914
    def open(self, a_controldir, _found=False, _override_transport=None):
 
1915
        """See RepositoryFormat.open().
 
1916
 
 
1917
        :param _override_transport: INTERNAL USE ONLY. Allows opening the
 
1918
                                    repository at a slightly different url
 
1919
                                    than normal. I.e. during 'upgrade'.
 
1920
        """
 
1921
        if not _found:
 
1922
            format = RepositoryFormatMetaDir.find_format(a_controldir)
 
1923
        if _override_transport is not None:
 
1924
            repo_transport = _override_transport
 
1925
        else:
 
1926
            repo_transport = a_controldir.get_repository_transport(None)
 
1927
        control_files = lockable_files.LockableFiles(repo_transport,
 
1928
                                                     'lock', lockdir.LockDir)
 
1929
        return self.repository_class(_format=self,
 
1930
                                     a_controldir=a_controldir,
 
1931
                                     control_files=control_files,
 
1932
                                     _commit_builder_class=self._commit_builder_class,
 
1933
                                     _serializer=self._serializer)
 
1934
 
 
1935
 
 
1936
class RetryPackOperations(errors.RetryWithNewPacks):
 
1937
    """Raised when we are packing and we find a missing file.
 
1938
 
 
1939
    Meant as a signaling exception, to tell the RepositoryPackCollection.pack
 
1940
    code it should try again.
 
1941
    """
 
1942
 
 
1943
    internal_error = True
 
1944
 
 
1945
    _fmt = ("Pack files have changed, reload and try pack again."
 
1946
            " context: %(context)s %(orig_error)s")
 
1947
 
 
1948
 
 
1949
class _DirectPackAccess(object):
 
1950
    """Access to data in one or more packs with less translation."""
 
1951
 
 
1952
    def __init__(self, index_to_packs, reload_func=None, flush_func=None):
 
1953
        """Create a _DirectPackAccess object.
 
1954
 
 
1955
        :param index_to_packs: A dict mapping index objects to the transport
 
1956
            and file names for obtaining data.
 
1957
        :param reload_func: A function to call if we determine that the pack
 
1958
            files have moved and we need to reload our caches. See
 
1959
            breezy.repo_fmt.pack_repo.AggregateIndex for more details.
 
1960
        """
 
1961
        self._container_writer = None
 
1962
        self._write_index = None
 
1963
        self._indices = index_to_packs
 
1964
        self._reload_func = reload_func
 
1965
        self._flush_func = flush_func
 
1966
 
 
1967
    def add_raw_records(self, key_sizes, raw_data):
 
1968
        """Add raw knit bytes to a storage area.
 
1969
 
 
1970
        The data is spooled to the container writer in one bytes-record per
 
1971
        raw data item.
 
1972
 
 
1973
        :param sizes: An iterable of tuples containing the key and size of each
 
1974
            raw data segment.
 
1975
        :param raw_data: A bytestring containing the data.
 
1976
        :return: A list of memos to retrieve the record later. Each memo is an
 
1977
            opaque index memo. For _DirectPackAccess the memo is (index, pos,
 
1978
            length), where the index field is the write_index object supplied
 
1979
            to the PackAccess object.
 
1980
        """
 
1981
        if not isinstance(raw_data, bytes):
 
1982
            raise AssertionError(
 
1983
                'data must be plain bytes was %s' % type(raw_data))
 
1984
        result = []
 
1985
        offset = 0
 
1986
        for key, size in key_sizes:
 
1987
            p_offset, p_length = self._container_writer.add_bytes_record(
 
1988
                raw_data[offset:offset + size], [])
 
1989
            offset += size
 
1990
            result.append((self._write_index, p_offset, p_length))
 
1991
        return result
 
1992
 
 
1993
    def flush(self):
 
1994
        """Flush pending writes on this access object.
 
1995
 
 
1996
        This will flush any buffered writes to a NewPack.
 
1997
        """
 
1998
        if self._flush_func is not None:
 
1999
            self._flush_func()
 
2000
 
 
2001
    def get_raw_records(self, memos_for_retrieval):
 
2002
        """Get the raw bytes for a records.
 
2003
 
 
2004
        :param memos_for_retrieval: An iterable containing the (index, pos,
 
2005
            length) memo for retrieving the bytes. The Pack access method
 
2006
            looks up the pack to use for a given record in its index_to_pack
 
2007
            map.
 
2008
        :return: An iterator over the bytes of the records.
 
2009
        """
 
2010
        # first pass, group into same-index requests
 
2011
        request_lists = []
 
2012
        current_index = None
 
2013
        for (index, offset, length) in memos_for_retrieval:
 
2014
            if current_index == index:
 
2015
                current_list.append((offset, length))
 
2016
            else:
 
2017
                if current_index is not None:
 
2018
                    request_lists.append((current_index, current_list))
 
2019
                current_index = index
 
2020
                current_list = [(offset, length)]
 
2021
        # handle the last entry
 
2022
        if current_index is not None:
 
2023
            request_lists.append((current_index, current_list))
 
2024
        for index, offsets in request_lists:
 
2025
            try:
 
2026
                transport, path = self._indices[index]
 
2027
            except KeyError:
 
2028
                # A KeyError here indicates that someone has triggered an index
 
2029
                # reload, and this index has gone missing, we need to start
 
2030
                # over.
 
2031
                if self._reload_func is None:
 
2032
                    # If we don't have a _reload_func there is nothing that can
 
2033
                    # be done
 
2034
                    raise
 
2035
                raise errors.RetryWithNewPacks(index,
 
2036
                                               reload_occurred=True,
 
2037
                                               exc_info=sys.exc_info())
 
2038
            try:
 
2039
                reader = pack.make_readv_reader(transport, path, offsets)
 
2040
                for names, read_func in reader.iter_records():
 
2041
                    yield read_func(None)
 
2042
            except errors.NoSuchFile:
 
2043
                # A NoSuchFile error indicates that a pack file has gone
 
2044
                # missing on disk, we need to trigger a reload, and start over.
 
2045
                if self._reload_func is None:
 
2046
                    raise
 
2047
                raise errors.RetryWithNewPacks(transport.abspath(path),
 
2048
                                               reload_occurred=False,
 
2049
                                               exc_info=sys.exc_info())
 
2050
 
 
2051
    def set_writer(self, writer, index, transport_packname):
 
2052
        """Set a writer to use for adding data."""
 
2053
        if index is not None:
 
2054
            self._indices[index] = transport_packname
 
2055
        self._container_writer = writer
 
2056
        self._write_index = index
 
2057
 
 
2058
    def reload_or_raise(self, retry_exc):
 
2059
        """Try calling the reload function, or re-raise the original exception.
 
2060
 
 
2061
        This should be called after _DirectPackAccess raises a
 
2062
        RetryWithNewPacks exception. This function will handle the common logic
 
2063
        of determining when the error is fatal versus being temporary.
 
2064
        It will also make sure that the original exception is raised, rather
 
2065
        than the RetryWithNewPacks exception.
 
2066
 
 
2067
        If this function returns, then the calling function should retry
 
2068
        whatever operation was being performed. Otherwise an exception will
 
2069
        be raised.
 
2070
 
 
2071
        :param retry_exc: A RetryWithNewPacks exception.
 
2072
        """
 
2073
        is_error = False
 
2074
        if self._reload_func is None:
 
2075
            is_error = True
 
2076
        elif not self._reload_func():
 
2077
            # The reload claimed that nothing changed
 
2078
            if not retry_exc.reload_occurred:
 
2079
                # If there wasn't an earlier reload, then we really were
 
2080
                # expecting to find changes. We didn't find them, so this is a
 
2081
                # hard error
 
2082
                is_error = True
 
2083
        if is_error:
 
2084
            # GZ 2017-03-27: No real reason this needs the original traceback.
 
2085
            reraise(*retry_exc.exc_info)