/brz/remove-bazaar

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