/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: Jelmer Vernooij
  • Date: 2018-05-22 02:05:12 UTC
  • mto: (6973.12.2 python3-k)
  • mto: This revision was merged to the branch mainline in revision 6992.
  • Revision ID: jelmer@jelmer.uk-20180522020512-btpj2jchdlehi3en
Add more bees.

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