/brz/remove-bazaar

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

« back to all changes in this revision

Viewing changes to breezy/bzr/reconcile.py

  • Committer: Jelmer Vernooij
  • Date: 2019-06-30 17:02:06 UTC
  • mto: This revision was merged to the branch mainline in revision 7360.
  • Revision ID: jelmer@jelmer.uk-20190630170206-srpoi2w1b130usc2
Fix import.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2006-2010 Canonical Ltd
 
2
#
 
3
# This program is free software; you can redistribute it and/or modify
 
4
# it under the terms of the GNU General Public License as published by
 
5
# the Free Software Foundation; either version 2 of the License, or
 
6
# (at your option) any later version.
 
7
#
 
8
# This program is distributed in the hope that it will be useful,
 
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
 
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
11
# GNU General Public License for more details.
 
12
#
 
13
# You should have received a copy of the GNU General Public License
 
14
# along with this program; if not, write to the Free Software
 
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 
16
 
 
17
"""Reconcilers are able to fix some potential data errors in a branch."""
 
18
 
 
19
from __future__ import absolute_import
 
20
 
 
21
__all__ = [
 
22
    'BranchReconciler',
 
23
    'KnitReconciler',
 
24
    'PackReconciler',
 
25
    'VersionedFileRepoReconciler',
 
26
    ]
 
27
 
 
28
from .. import (
 
29
    cleanup,
 
30
    errors,
 
31
    revision as _mod_revision,
 
32
    ui,
 
33
    )
 
34
from ..reconcile import ReconcileResult
 
35
from ..i18n import gettext
 
36
from ..trace import mutter
 
37
from ..tsort import topo_sort
 
38
from .versionedfile import AdapterFactory, FulltextContentFactory
 
39
 
 
40
 
 
41
class VersionedFileRepoReconciler(object):
 
42
    """Reconciler that reconciles a repository.
 
43
 
 
44
    The goal of repository reconciliation is to make any derived data
 
45
    consistent with the core data committed by a user. This can involve
 
46
    reindexing, or removing unreferenced data if that can interfere with
 
47
    queries in a given repository.
 
48
 
 
49
    Currently this consists of an inventory reweave with revision cross-checks.
 
50
    """
 
51
 
 
52
    def __init__(self, repo, other=None, thorough=False):
 
53
        """Construct a RepoReconciler.
 
54
 
 
55
        :param thorough: perform a thorough check which may take longer but
 
56
                         will correct non-data loss issues such as incorrect
 
57
                         cached data.
 
58
        """
 
59
        self.garbage_inventories = 0
 
60
        self.inconsistent_parents = 0
 
61
        self.aborted = False
 
62
        self.repo = repo
 
63
        self.thorough = thorough
 
64
 
 
65
    def reconcile(self):
 
66
        """Perform reconciliation.
 
67
 
 
68
        After reconciliation the following attributes document found issues:
 
69
 
 
70
        * `inconsistent_parents`: The number of revisions in the repository
 
71
          whose ancestry was being reported incorrectly.
 
72
        * `garbage_inventories`: The number of inventory objects without
 
73
          revisions that were garbage collected.
 
74
        """
 
75
        with self.repo.lock_write(), \
 
76
                ui.ui_factory.nested_progress_bar() as self.pb:
 
77
            self._reconcile_steps()
 
78
            ret = ReconcileResult()
 
79
            ret.aborted = self.aborted
 
80
            ret.garbage_inventories = self.garbage_inventories
 
81
            ret.inconsistent_parents = self.inconsistent_parents
 
82
            return ret
 
83
 
 
84
    def _reconcile_steps(self):
 
85
        """Perform the steps to reconcile this repository."""
 
86
        self._reweave_inventory()
 
87
 
 
88
    def _reweave_inventory(self):
 
89
        """Regenerate the inventory weave for the repository from scratch.
 
90
 
 
91
        This is a smart function: it will only do the reweave if doing it
 
92
        will correct data issues. The self.thorough flag controls whether
 
93
        only data-loss causing issues (!self.thorough) or all issues
 
94
        (self.thorough) are treated as requiring the reweave.
 
95
        """
 
96
        transaction = self.repo.get_transaction()
 
97
        self.pb.update(gettext('Reading inventory data'))
 
98
        self.inventory = self.repo.inventories
 
99
        self.revisions = self.repo.revisions
 
100
        # the total set of revisions to process
 
101
        self.pending = {key[-1] for key in self.revisions.keys()}
 
102
 
 
103
        # mapping from revision_id to parents
 
104
        self._rev_graph = {}
 
105
        # errors that we detect
 
106
        self.inconsistent_parents = 0
 
107
        # we need the revision id of each revision and its available parents list
 
108
        self._setup_steps(len(self.pending))
 
109
        for rev_id in self.pending:
 
110
            # put a revision into the graph.
 
111
            self._graph_revision(rev_id)
 
112
        self._check_garbage_inventories()
 
113
        # if there are no inconsistent_parents and
 
114
        # (no garbage inventories or we are not doing a thorough check)
 
115
        if (not self.inconsistent_parents
 
116
                and (not self.garbage_inventories or not self.thorough)):
 
117
            ui.ui_factory.note(gettext('Inventory ok.'))
 
118
            return
 
119
        self.pb.update(gettext('Backing up inventory'), 0, 0)
 
120
        self.repo._backup_inventory()
 
121
        ui.ui_factory.note(gettext('Backup inventory created.'))
 
122
        new_inventories = self.repo._temp_inventories()
 
123
 
 
124
        # we have topological order of revisions and non ghost parents ready.
 
125
        self._setup_steps(len(self._rev_graph))
 
126
        revision_keys = [(rev_id,) for rev_id in topo_sort(self._rev_graph)]
 
127
        stream = self._change_inv_parents(
 
128
            self.inventory.get_record_stream(revision_keys, 'unordered', True),
 
129
            self._new_inv_parents,
 
130
            set(revision_keys))
 
131
        new_inventories.insert_record_stream(stream)
 
132
        # if this worked, the set of new_inventories.keys should equal
 
133
        # self.pending
 
134
        if not (set(new_inventories.keys())
 
135
                == {(revid,) for revid in self.pending}):
 
136
            raise AssertionError()
 
137
        self.pb.update(gettext('Writing weave'))
 
138
        self.repo._activate_new_inventory()
 
139
        self.inventory = None
 
140
        ui.ui_factory.note(gettext('Inventory regenerated.'))
 
141
 
 
142
    def _new_inv_parents(self, revision_key):
 
143
        """Lookup ghost-filtered parents for revision_key."""
 
144
        # Use the filtered ghostless parents list:
 
145
        return tuple([(revid,) for revid in self._rev_graph[revision_key[-1]]])
 
146
 
 
147
    def _change_inv_parents(self, stream, get_parents, all_revision_keys):
 
148
        """Adapt a record stream to reconcile the parents."""
 
149
        for record in stream:
 
150
            wanted_parents = get_parents(record.key)
 
151
            if wanted_parents and wanted_parents[0] not in all_revision_keys:
 
152
                # The check for the left most parent only handles knit
 
153
                # compressors, but this code only applies to knit and weave
 
154
                # repositories anyway.
 
155
                bytes = record.get_bytes_as('fulltext')
 
156
                yield FulltextContentFactory(record.key, wanted_parents, record.sha1, bytes)
 
157
            else:
 
158
                adapted_record = AdapterFactory(
 
159
                    record.key, wanted_parents, record)
 
160
                yield adapted_record
 
161
            self._reweave_step('adding inventories')
 
162
 
 
163
    def _setup_steps(self, new_total):
 
164
        """Setup the markers we need to control the progress bar."""
 
165
        self.total = new_total
 
166
        self.count = 0
 
167
 
 
168
    def _graph_revision(self, rev_id):
 
169
        """Load a revision into the revision graph."""
 
170
        # pick a random revision
 
171
        # analyse revision id rev_id and put it in the stack.
 
172
        self._reweave_step('loading revisions')
 
173
        rev = self.repo.get_revision_reconcile(rev_id)
 
174
        parents = []
 
175
        for parent in rev.parent_ids:
 
176
            if self._parent_is_available(parent):
 
177
                parents.append(parent)
 
178
            else:
 
179
                mutter('found ghost %s', parent)
 
180
        self._rev_graph[rev_id] = parents
 
181
 
 
182
    def _check_garbage_inventories(self):
 
183
        """Check for garbage inventories which we cannot trust
 
184
 
 
185
        We cant trust them because their pre-requisite file data may not
 
186
        be present - all we know is that their revision was not installed.
 
187
        """
 
188
        if not self.thorough:
 
189
            return
 
190
        inventories = set(self.inventory.keys())
 
191
        revisions = set(self.revisions.keys())
 
192
        garbage = inventories.difference(revisions)
 
193
        self.garbage_inventories = len(garbage)
 
194
        for revision_key in garbage:
 
195
            mutter('Garbage inventory {%s} found.', revision_key[-1])
 
196
 
 
197
    def _parent_is_available(self, parent):
 
198
        """True if parent is a fully available revision
 
199
 
 
200
        A fully available revision has a inventory and a revision object in the
 
201
        repository.
 
202
        """
 
203
        if parent in self._rev_graph:
 
204
            return True
 
205
        inv_present = (1 == len(self.inventory.get_parent_map([(parent,)])))
 
206
        return (inv_present and self.repo.has_revision(parent))
 
207
 
 
208
    def _reweave_step(self, message):
 
209
        """Mark a single step of regeneration complete."""
 
210
        self.pb.update(message, self.count, self.total)
 
211
        self.count += 1
 
212
 
 
213
 
 
214
class KnitReconciler(VersionedFileRepoReconciler):
 
215
    """Reconciler that reconciles a knit format repository.
 
216
 
 
217
    This will detect garbage inventories and remove them in thorough mode.
 
218
    """
 
219
 
 
220
    def _reconcile_steps(self):
 
221
        """Perform the steps to reconcile this repository."""
 
222
        if self.thorough:
 
223
            try:
 
224
                self._load_indexes()
 
225
            except errors.BzrCheckError:
 
226
                self.aborted = True
 
227
                return
 
228
            # knits never suffer this
 
229
            self._gc_inventory()
 
230
            self._fix_text_parents()
 
231
 
 
232
    def _load_indexes(self):
 
233
        """Load indexes for the reconciliation."""
 
234
        self.transaction = self.repo.get_transaction()
 
235
        self.pb.update(gettext('Reading indexes'), 0, 2)
 
236
        self.inventory = self.repo.inventories
 
237
        self.pb.update(gettext('Reading indexes'), 1, 2)
 
238
        self.repo._check_for_inconsistent_revision_parents()
 
239
        self.revisions = self.repo.revisions
 
240
        self.pb.update(gettext('Reading indexes'), 2, 2)
 
241
 
 
242
    def _gc_inventory(self):
 
243
        """Remove inventories that are not referenced from the revision store."""
 
244
        self.pb.update(gettext('Checking unused inventories'), 0, 1)
 
245
        self._check_garbage_inventories()
 
246
        self.pb.update(gettext('Checking unused inventories'), 1, 3)
 
247
        if not self.garbage_inventories:
 
248
            ui.ui_factory.note(gettext('Inventory ok.'))
 
249
            return
 
250
        self.pb.update(gettext('Backing up inventory'), 0, 0)
 
251
        self.repo._backup_inventory()
 
252
        ui.ui_factory.note(gettext('Backup Inventory created'))
 
253
        # asking for '' should never return a non-empty weave
 
254
        new_inventories = self.repo._temp_inventories()
 
255
        # we have topological order of revisions and non ghost parents ready.
 
256
        graph = self.revisions.get_parent_map(self.revisions.keys())
 
257
        revision_keys = topo_sort(graph)
 
258
        revision_ids = [key[-1] for key in revision_keys]
 
259
        self._setup_steps(len(revision_keys))
 
260
        stream = self._change_inv_parents(
 
261
            self.inventory.get_record_stream(revision_keys, 'unordered', True),
 
262
            graph.__getitem__,
 
263
            set(revision_keys))
 
264
        new_inventories.insert_record_stream(stream)
 
265
        # if this worked, the set of new_inventory_vf.names should equal
 
266
        # the revisionds list
 
267
        if not(set(new_inventories.keys()) == set(revision_keys)):
 
268
            raise AssertionError()
 
269
        self.pb.update(gettext('Writing weave'))
 
270
        self.repo._activate_new_inventory()
 
271
        self.inventory = None
 
272
        ui.ui_factory.note(gettext('Inventory regenerated.'))
 
273
 
 
274
    def _fix_text_parents(self):
 
275
        """Fix bad versionedfile parent entries.
 
276
 
 
277
        It is possible for the parents entry in a versionedfile entry to be
 
278
        inconsistent with the values in the revision and inventory.
 
279
 
 
280
        This method finds entries with such inconsistencies, corrects their
 
281
        parent lists, and replaces the versionedfile with a corrected version.
 
282
        """
 
283
        transaction = self.repo.get_transaction()
 
284
        versions = [key[-1] for key in self.revisions.keys()]
 
285
        mutter('Prepopulating revision text cache with %d revisions',
 
286
               len(versions))
 
287
        vf_checker = self.repo._get_versioned_file_checker()
 
288
        bad_parents, unused_versions = vf_checker.check_file_version_parents(
 
289
            self.repo.texts, self.pb)
 
290
        text_index = vf_checker.text_index
 
291
        per_id_bad_parents = {}
 
292
        for key in unused_versions:
 
293
            # Ensure that every file with unused versions gets rewritten.
 
294
            # NB: This is really not needed, reconcile != pack.
 
295
            per_id_bad_parents[key[0]] = {}
 
296
        # Generate per-knit/weave data.
 
297
        for key, details in bad_parents.items():
 
298
            file_id = key[0]
 
299
            rev_id = key[1]
 
300
            knit_parents = tuple([parent[-1] for parent in details[0]])
 
301
            correct_parents = tuple([parent[-1] for parent in details[1]])
 
302
            file_details = per_id_bad_parents.setdefault(file_id, {})
 
303
            file_details[rev_id] = (knit_parents, correct_parents)
 
304
        file_id_versions = {}
 
305
        for text_key in text_index:
 
306
            versions_list = file_id_versions.setdefault(text_key[0], [])
 
307
            versions_list.append(text_key[1])
 
308
        # Do the reconcile of individual weaves.
 
309
        for num, file_id in enumerate(per_id_bad_parents):
 
310
            self.pb.update(gettext('Fixing text parents'), num,
 
311
                           len(per_id_bad_parents))
 
312
            versions_with_bad_parents = per_id_bad_parents[file_id]
 
313
            id_unused_versions = set(key[-1] for key in unused_versions
 
314
                                     if key[0] == file_id)
 
315
            if file_id in file_id_versions:
 
316
                file_versions = file_id_versions[file_id]
 
317
            else:
 
318
                # This id was present in the disk store but is not referenced
 
319
                # by any revision at all.
 
320
                file_versions = []
 
321
            self._fix_text_parent(file_id, versions_with_bad_parents,
 
322
                                  id_unused_versions, file_versions)
 
323
 
 
324
    def _fix_text_parent(self, file_id, versions_with_bad_parents,
 
325
                         unused_versions, all_versions):
 
326
        """Fix bad versionedfile entries in a single versioned file."""
 
327
        mutter('fixing text parent: %r (%d versions)', file_id,
 
328
               len(versions_with_bad_parents))
 
329
        mutter('(%d are unused)', len(unused_versions))
 
330
        new_file_id = b'temp:%s' % file_id
 
331
        new_parents = {}
 
332
        needed_keys = set()
 
333
        for version in all_versions:
 
334
            if version in unused_versions:
 
335
                continue
 
336
            elif version in versions_with_bad_parents:
 
337
                parents = versions_with_bad_parents[version][1]
 
338
            else:
 
339
                pmap = self.repo.texts.get_parent_map([(file_id, version)])
 
340
                parents = [key[-1] for key in pmap[(file_id, version)]]
 
341
            new_parents[(new_file_id, version)] = [
 
342
                (new_file_id, parent) for parent in parents]
 
343
            needed_keys.add((file_id, version))
 
344
 
 
345
        def fix_parents(stream):
 
346
            for record in stream:
 
347
                bytes = record.get_bytes_as('fulltext')
 
348
                new_key = (new_file_id, record.key[-1])
 
349
                parents = new_parents[new_key]
 
350
                yield FulltextContentFactory(new_key, parents, record.sha1, bytes)
 
351
        stream = self.repo.texts.get_record_stream(
 
352
            needed_keys, 'topological', True)
 
353
        self.repo._remove_file_id(new_file_id)
 
354
        self.repo.texts.insert_record_stream(fix_parents(stream))
 
355
        self.repo._remove_file_id(file_id)
 
356
        if len(new_parents):
 
357
            self.repo._move_file_id(new_file_id, file_id)
 
358
 
 
359
 
 
360
class PackReconciler(VersionedFileRepoReconciler):
 
361
    """Reconciler that reconciles a pack based repository.
 
362
 
 
363
    Garbage inventories do not affect ancestry queries, and removal is
 
364
    considerably more expensive as there is no separate versioned file for
 
365
    them, so they are not cleaned. In short it is currently a no-op.
 
366
 
 
367
    In future this may be a good place to hook in annotation cache checking,
 
368
    index recreation etc.
 
369
    """
 
370
 
 
371
    # XXX: The index corruption that _fix_text_parents performs is needed for
 
372
    # packs, but not yet implemented. The basic approach is to:
 
373
    #  - lock the names list
 
374
    #  - perform a customised pack() that regenerates data as needed
 
375
    #  - unlock the names list
 
376
    # https://bugs.launchpad.net/bzr/+bug/154173
 
377
 
 
378
    def __init__(self, repo, other=None, thorough=False,
 
379
                 canonicalize_chks=False):
 
380
        super(PackReconciler, self).__init__(repo, other=other,
 
381
                                             thorough=thorough)
 
382
        self.canonicalize_chks = canonicalize_chks
 
383
 
 
384
    def _reconcile_steps(self):
 
385
        """Perform the steps to reconcile this repository."""
 
386
        if not self.thorough:
 
387
            return
 
388
        collection = self.repo._pack_collection
 
389
        collection.ensure_loaded()
 
390
        collection.lock_names()
 
391
        try:
 
392
            packs = collection.all_packs()
 
393
            all_revisions = self.repo.all_revision_ids()
 
394
            total_inventories = len(list(
 
395
                collection.inventory_index.combined_index.iter_all_entries()))
 
396
            if len(all_revisions):
 
397
                if self.canonicalize_chks:
 
398
                    reconcile_meth = self.repo._canonicalize_chks_pack
 
399
                else:
 
400
                    reconcile_meth = self.repo._reconcile_pack
 
401
                new_pack = reconcile_meth(collection, packs, ".reconcile",
 
402
                                          all_revisions, self.pb)
 
403
                if new_pack is not None:
 
404
                    self._discard_and_save(packs)
 
405
            else:
 
406
                # only make a new pack when there is data to copy.
 
407
                self._discard_and_save(packs)
 
408
            self.garbage_inventories = total_inventories - len(list(
 
409
                collection.inventory_index.combined_index.iter_all_entries()))
 
410
        finally:
 
411
            collection._unlock_names()
 
412
 
 
413
    def _discard_and_save(self, packs):
 
414
        """Discard some packs from the repository.
 
415
 
 
416
        This removes them from the memory index, saves the in-memory index
 
417
        which makes the newly reconciled pack visible and hides the packs to be
 
418
        discarded, and finally renames the packs being discarded into the
 
419
        obsolete packs directory.
 
420
 
 
421
        :param packs: The packs to discard.
 
422
        """
 
423
        for pack in packs:
 
424
            self.repo._pack_collection._remove_pack_from_memory(pack)
 
425
        self.repo._pack_collection._save_pack_names()
 
426
        self.repo._pack_collection._obsolete_packs(packs)
 
427
 
 
428
 
 
429
class BranchReconciler(object):
 
430
    """Reconciler that works on a branch."""
 
431
 
 
432
    def __init__(self, a_branch, thorough=False):
 
433
        self.fixed_history = None
 
434
        self.thorough = thorough
 
435
        self.branch = a_branch
 
436
 
 
437
    def reconcile(self):
 
438
        with self.branch.lock_write(), \
 
439
                ui.ui_factory.nested_progress_bar() as self.pb:
 
440
            ret = ReconcileResult()
 
441
            ret.fixed_history = self._reconcile_steps()
 
442
            return ret
 
443
 
 
444
    def _reconcile_steps(self):
 
445
        return self._reconcile_revision_history()
 
446
 
 
447
    def _reconcile_revision_history(self):
 
448
        last_revno, last_revision_id = self.branch.last_revision_info()
 
449
        real_history = []
 
450
        graph = self.branch.repository.get_graph()
 
451
        try:
 
452
            for revid in graph.iter_lefthand_ancestry(
 
453
                    last_revision_id, (_mod_revision.NULL_REVISION,)):
 
454
                real_history.append(revid)
 
455
        except errors.RevisionNotPresent:
 
456
            pass  # Hit a ghost left hand parent
 
457
        real_history.reverse()
 
458
        if last_revno != len(real_history):
 
459
            # Technically for Branch5 formats, it is more efficient to use
 
460
            # set_revision_history, as this will regenerate it again.
 
461
            # Not really worth a whole BranchReconciler class just for this,
 
462
            # though.
 
463
            ui.ui_factory.note(gettext('Fixing last revision info {0} '
 
464
                                       ' => {1}').format(
 
465
                last_revno, len(real_history)))
 
466
            self.branch.set_last_revision_info(len(real_history),
 
467
                                               last_revision_id)
 
468
            return True
 
469
        else:
 
470
            ui.ui_factory.note(gettext('revision_history ok.'))
 
471
            return False