/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: 2020-05-06 02:13:25 UTC
  • mfrom: (7490.7.21 work)
  • mto: This revision was merged to the branch mainline in revision 7501.
  • Revision ID: jelmer@jelmer.uk-20200506021325-awbmmqu1zyorz7sj
Merge 3.1 branch.

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