/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/check.py

  • Committer: Breezy landing bot
  • Author(s): Jelmer Vernooij
  • Date: 2019-01-01 21:23:40 UTC
  • mfrom: (7206.4.1 move-testament)
  • Revision ID: breezy.the.bot@gmail.com-20190101212340-6wmbncvwqal06rif
Move the testament module to breezy.bzr.

Merged from https://code.launchpad.net/~jelmer/brz/move-testament/+merge/359939

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2005, 2006 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
# TODO: Check ancestries are correct for every revision: includes
 
18
# every committed so far, and in a reasonable order.
 
19
 
 
20
# TODO: Also check non-mainline revisions mentioned as parents.
 
21
 
 
22
# TODO: Check for extra files in the control directory.
 
23
 
 
24
# TODO: Check revision, inventory and entry objects have all
 
25
# required fields.
 
26
 
 
27
# TODO: Get every revision in the revision-store even if they're not
 
28
# referenced by history and make sure they're all valid.
 
29
 
 
30
# TODO: Perhaps have a way to record errors other than by raising exceptions;
 
31
# would perhaps be enough to accumulate exception objects in a list without
 
32
# raising them.  If there's more than one exception it'd be good to see them
 
33
# all.
 
34
 
 
35
"""Checking of bzr objects.
 
36
 
 
37
check_refs is a concept used for optimising check. Objects that depend on other
 
38
objects (e.g. tree on repository) can list the objects they would be requesting
 
39
so that when the dependent object is checked, matches can be pulled out and
 
40
evaluated in-line rather than re-reading the same data many times.
 
41
check_refs are tuples (kind, value). Currently defined kinds are:
 
42
 
 
43
* 'trees', where value is a revid and the looked up objects are revision trees.
 
44
* 'lefthand-distance', where value is a revid and the looked up objects are the
 
45
  distance along the lefthand path to NULL for that revid.
 
46
* 'revision-existence', where value is a revid, and the result is True or False
 
47
  indicating that the revision was found/not found.
 
48
"""
 
49
 
 
50
from __future__ import absolute_import
 
51
 
 
52
from .. import (
 
53
    ui,
 
54
    )
 
55
from ..branch import Branch
 
56
from ..check import Check
 
57
from ..revision import NULL_REVISION
 
58
from ..sixish import (
 
59
    viewitems,
 
60
    )
 
61
from ..trace import note
 
62
from ..workingtree import WorkingTree
 
63
from ..i18n import gettext
 
64
 
 
65
 
 
66
class VersionedFileCheck(Check):
 
67
    """Check a versioned file repository"""
 
68
 
 
69
    # The Check object interacts with InventoryEntry.check, etc.
 
70
 
 
71
    def __init__(self, repository, check_repo=True):
 
72
        self.repository = repository
 
73
        self.checked_rev_cnt = 0
 
74
        self.ghosts = set()
 
75
        self.missing_parent_links = {}
 
76
        self.missing_inventory_sha_cnt = 0
 
77
        self.missing_revision_cnt = 0
 
78
        self.checked_weaves = set()
 
79
        self.unreferenced_versions = set()
 
80
        self.inconsistent_parents = []
 
81
        self.rich_roots = repository.supports_rich_root()
 
82
        self.text_key_references = {}
 
83
        self.check_repo = check_repo
 
84
        self.other_results = []
 
85
        # Plain text lines to include in the report
 
86
        self._report_items = []
 
87
        # Keys we are looking for; may be large and need spilling to disk.
 
88
        # key->(type(revision/inventory/text/signature/map), sha1, first-referer)
 
89
        self.pending_keys = {}
 
90
        # Ancestors map for all of revisions being checked; while large helper
 
91
        # functions we call would create it anyway, so better to have once and
 
92
        # keep.
 
93
        self.ancestors = {}
 
94
 
 
95
    def check(self, callback_refs=None, check_repo=True):
 
96
        if callback_refs is None:
 
97
            callback_refs = {}
 
98
        with self.repository.lock_read(), ui.ui_factory.nested_progress_bar() as self.progress:
 
99
            self.progress.update(gettext('check'), 0, 4)
 
100
            if self.check_repo:
 
101
                self.progress.update(gettext('checking revisions'), 0)
 
102
                self.check_revisions()
 
103
                self.progress.update(gettext('checking commit contents'), 1)
 
104
                self.repository._check_inventories(self)
 
105
                self.progress.update(gettext('checking file graphs'), 2)
 
106
                # check_weaves is done after the revision scan so that
 
107
                # revision index is known to be valid.
 
108
                self.check_weaves()
 
109
            self.progress.update(gettext('checking branches and trees'), 3)
 
110
            if callback_refs:
 
111
                repo = self.repository
 
112
                # calculate all refs, and callback the objects requesting them.
 
113
                refs = {}
 
114
                wanting_items = set()
 
115
                # Current crude version calculates everything and calls
 
116
                # everything at once. Doing a queue and popping as things are
 
117
                # satisfied would be cheaper on memory [but few people have
 
118
                # huge numbers of working trees today. TODO: fix before
 
119
                # landing].
 
120
                distances = set()
 
121
                existences = set()
 
122
                for ref, wantlist in viewitems(callback_refs):
 
123
                    wanting_items.update(wantlist)
 
124
                    kind, value = ref
 
125
                    if kind == 'trees':
 
126
                        refs[ref] = repo.revision_tree(value)
 
127
                    elif kind == 'lefthand-distance':
 
128
                        distances.add(value)
 
129
                    elif kind == 'revision-existence':
 
130
                        existences.add(value)
 
131
                    else:
 
132
                        raise AssertionError(
 
133
                            'unknown ref kind for ref %s' % ref)
 
134
                node_distances = repo.get_graph().find_lefthand_distances(distances)
 
135
                for key, distance in viewitems(node_distances):
 
136
                    refs[('lefthand-distance', key)] = distance
 
137
                    if key in existences and distance > 0:
 
138
                        refs[('revision-existence', key)] = True
 
139
                        existences.remove(key)
 
140
                parent_map = repo.get_graph().get_parent_map(existences)
 
141
                for key in parent_map:
 
142
                    refs[('revision-existence', key)] = True
 
143
                    existences.remove(key)
 
144
                for key in existences:
 
145
                    refs[('revision-existence', key)] = False
 
146
                for item in wanting_items:
 
147
                    if isinstance(item, WorkingTree):
 
148
                        item._check(refs)
 
149
                    if isinstance(item, Branch):
 
150
                        self.other_results.append(item.check(refs))
 
151
 
 
152
    def _check_revisions(self, revisions_iterator):
 
153
        """Check revision objects by decorating a generator.
 
154
 
 
155
        :param revisions_iterator: An iterator of(revid, Revision-or-None).
 
156
        :return: A generator of the contents of revisions_iterator.
 
157
        """
 
158
        self.planned_revisions = set()
 
159
        for revid, revision in revisions_iterator:
 
160
            yield revid, revision
 
161
            self._check_one_rev(revid, revision)
 
162
        # Flatten the revisions we found to guarantee consistent later
 
163
        # iteration.
 
164
        self.planned_revisions = list(self.planned_revisions)
 
165
        # TODO: extract digital signatures as items to callback on too.
 
166
 
 
167
    def check_revisions(self):
 
168
        """Scan revisions, checking data directly available as we go."""
 
169
        revision_iterator = self.repository.iter_revisions(
 
170
            self.repository.all_revision_ids())
 
171
        revision_iterator = self._check_revisions(revision_iterator)
 
172
        # We read the all revisions here:
 
173
        # - doing this allows later code to depend on the revision index.
 
174
        # - we can fill out existence flags at this point
 
175
        # - we can read the revision inventory sha at this point
 
176
        # - we can check properties and serialisers etc.
 
177
        if not self.repository._format.revision_graph_can_have_wrong_parents:
 
178
            # The check against the index isn't needed.
 
179
            self.revs_with_bad_parents_in_index = None
 
180
            for thing in revision_iterator:
 
181
                pass
 
182
        else:
 
183
            bad_revisions = self.repository._find_inconsistent_revision_parents(
 
184
                revision_iterator)
 
185
            self.revs_with_bad_parents_in_index = list(bad_revisions)
 
186
 
 
187
    def report_results(self, verbose):
 
188
        if self.check_repo:
 
189
            self._report_repo_results(verbose)
 
190
        for result in self.other_results:
 
191
            result.report_results(verbose)
 
192
 
 
193
    def _report_repo_results(self, verbose):
 
194
        note(gettext('checked repository {0} format {1}').format(
 
195
            self.repository.user_url,
 
196
            self.repository._format))
 
197
        note(gettext('%6d revisions'), self.checked_rev_cnt)
 
198
        note(gettext('%6d file-ids'), len(self.checked_weaves))
 
199
        if verbose:
 
200
            note(gettext('%6d unreferenced text versions'),
 
201
                 len(self.unreferenced_versions))
 
202
        if verbose and len(self.unreferenced_versions):
 
203
            for file_id, revision_id in self.unreferenced_versions:
 
204
                note(gettext('unreferenced version: {{{0}}} in {1}').format(
 
205
                    revision_id.decode('utf-8'), file_id.decode('utf-8')))
 
206
        if self.missing_inventory_sha_cnt:
 
207
            note(gettext('%6d revisions are missing inventory_sha1'),
 
208
                 self.missing_inventory_sha_cnt)
 
209
        if self.missing_revision_cnt:
 
210
            note(gettext('%6d revisions are mentioned but not present'),
 
211
                 self.missing_revision_cnt)
 
212
        if len(self.ghosts):
 
213
            note(gettext('%6d ghost revisions'), len(self.ghosts))
 
214
            if verbose:
 
215
                for ghost in self.ghosts:
 
216
                    note('      %s', ghost.decode('utf-8'))
 
217
        if len(self.missing_parent_links):
 
218
            note(gettext('%6d revisions missing parents in ancestry'),
 
219
                 len(self.missing_parent_links))
 
220
            if verbose:
 
221
                for link, linkers in viewitems(self.missing_parent_links):
 
222
                    note(gettext('      %s should be in the ancestry for:'),
 
223
                         link.decode('utf-8'))
 
224
                    for linker in linkers:
 
225
                        note('       * %s', linker.decode('utf-8'))
 
226
        if len(self.inconsistent_parents):
 
227
            note(gettext('%6d inconsistent parents'),
 
228
                 len(self.inconsistent_parents))
 
229
            if verbose:
 
230
                for info in self.inconsistent_parents:
 
231
                    revision_id, file_id, found_parents, correct_parents = info
 
232
                    note(gettext('      * {0} version {1} has parents ({2}) '
 
233
                                 'but should have ({3})').format(
 
234
                         file_id.decode('utf-8'), revision_id.decode('utf-8'),
 
235
                         ', '.join(p.decode('utf-8') for p in found_parents),
 
236
                         ', '.join(p.decode('utf-8') for p in correct_parents)))
 
237
        if self.revs_with_bad_parents_in_index:
 
238
            note(gettext(
 
239
                 '%6d revisions have incorrect parents in the revision index'),
 
240
                 len(self.revs_with_bad_parents_in_index))
 
241
            if verbose:
 
242
                for item in self.revs_with_bad_parents_in_index:
 
243
                    revision_id, index_parents, actual_parents = item
 
244
                    note(gettext(
 
245
                        '       {0} has wrong parents in index: '
 
246
                        '({1}) should be ({2})').format(
 
247
                        revision_id.decode('utf-8'),
 
248
                        ', '.join(p.decode('utf-8') for p in index_parents),
 
249
                        ', '.join(p.decode('utf-8') for p in actual_parents)))
 
250
        for item in self._report_items:
 
251
            note(item)
 
252
 
 
253
    def _check_one_rev(self, rev_id, rev):
 
254
        """Cross-check one revision.
 
255
 
 
256
        :param rev_id: A revision id to check.
 
257
        :param rev: A revision or None to indicate a missing revision.
 
258
        """
 
259
        if rev.revision_id != rev_id:
 
260
            self._report_items.append(gettext(
 
261
                'Mismatched internal revid {{{0}}} and index revid {{{1}}}').format(
 
262
                rev.revision_id.decode('utf-8'), rev_id.decode('utf-8')))
 
263
            rev_id = rev.revision_id
 
264
        # Check this revision tree etc, and count as seen when we encounter a
 
265
        # reference to it.
 
266
        self.planned_revisions.add(rev_id)
 
267
        # It is not a ghost
 
268
        self.ghosts.discard(rev_id)
 
269
        # Count all parents as ghosts if we haven't seen them yet.
 
270
        for parent in rev.parent_ids:
 
271
            if parent not in self.planned_revisions:
 
272
                self.ghosts.add(parent)
 
273
 
 
274
        self.ancestors[rev_id] = tuple(rev.parent_ids) or (NULL_REVISION,)
 
275
        self.add_pending_item(rev_id, ('inventories', rev_id), 'inventory',
 
276
                              rev.inventory_sha1)
 
277
        self.checked_rev_cnt += 1
 
278
 
 
279
    def add_pending_item(self, referer, key, kind, sha1):
 
280
        """Add a reference to a sha1 to be cross checked against a key.
 
281
 
 
282
        :param referer: The referer that expects key to have sha1.
 
283
        :param key: A storage key e.g. ('texts', 'foo@bar-20040504-1234')
 
284
        :param kind: revision/inventory/text/map/signature
 
285
        :param sha1: A hex sha1 or None if no sha1 is known.
 
286
        """
 
287
        existing = self.pending_keys.get(key)
 
288
        if existing:
 
289
            if sha1 != existing[1]:
 
290
                self._report_items.append(gettext('Multiple expected sha1s for {0}. {{{1}}}'
 
291
                                                  ' expects {{{2}}}, {{{3}}} expects {{{4}}}').format(
 
292
                    key, referer, sha1, existing[1], existing[0]))
 
293
        else:
 
294
            self.pending_keys[key] = (kind, sha1, referer)
 
295
 
 
296
    def check_weaves(self):
 
297
        """Check all the weaves we can get our hands on.
 
298
        """
 
299
        weave_ids = []
 
300
        with ui.ui_factory.nested_progress_bar() as storebar:
 
301
            self._check_weaves(storebar)
 
302
 
 
303
    def _check_weaves(self, storebar):
 
304
        storebar.update('text-index', 0, 2)
 
305
        if self.repository._format.fast_deltas:
 
306
            # We haven't considered every fileid instance so far.
 
307
            weave_checker = self.repository._get_versioned_file_checker(
 
308
                ancestors=self.ancestors)
 
309
        else:
 
310
            weave_checker = self.repository._get_versioned_file_checker(
 
311
                text_key_references=self.text_key_references,
 
312
                ancestors=self.ancestors)
 
313
        storebar.update('file-graph', 1)
 
314
        wrongs, unused_versions = weave_checker.check_file_version_parents(
 
315
            self.repository.texts)
 
316
        self.checked_weaves = weave_checker.file_ids
 
317
        for text_key, (stored_parents, correct_parents) in viewitems(wrongs):
 
318
            # XXX not ready for id join/split operations.
 
319
            weave_id = text_key[0]
 
320
            revision_id = text_key[-1]
 
321
            weave_parents = tuple([parent[-1] for parent in stored_parents])
 
322
            correct_parents = tuple([parent[-1] for parent in correct_parents])
 
323
            self.inconsistent_parents.append(
 
324
                (revision_id, weave_id, weave_parents, correct_parents))
 
325
        self.unreferenced_versions.update(unused_versions)
 
326
 
 
327
    def _add_entry_to_text_key_references(self, inv, entry):
 
328
        if not self.rich_roots and entry.name == '':
 
329
            return
 
330
        key = (entry.file_id, entry.revision)
 
331
        self.text_key_references.setdefault(key, False)
 
332
        if entry.revision == inv.revision_id:
 
333
            self.text_key_references[key] = True