1
# Copyright (C) 2005, 2006 Canonical Ltd
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.
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.
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
17
# TODO: Check ancestries are correct for every revision: includes
18
# every committed so far, and in a reasonable order.
20
# TODO: Also check non-mainline revisions mentioned as parents.
22
# TODO: Check for extra files in the control directory.
24
# TODO: Check revision, inventory and entry objects have all
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.
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
35
"""Checking of bzr objects.
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:
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.
50
from __future__ import absolute_import
56
from ..branch import Branch
57
from ..check import Check
58
from ..revision import NULL_REVISION
59
from ..sixish import (
62
from ..trace import note
63
from ..workingtree import WorkingTree
64
from ..i18n import gettext
67
class VersionedFileCheck(Check):
68
"""Check a versioned file repository"""
70
# The Check object interacts with InventoryEntry.check, etc.
72
def __init__(self, repository, check_repo=True):
73
self.repository = repository
74
self.checked_rev_cnt = 0
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
96
def check(self, callback_refs=None, check_repo=True):
97
if callback_refs is None:
99
with self.repository.lock_read(), ui.ui_factory.nested_progress_bar() as self.progress:
100
self.progress.update(gettext('check'), 0, 4)
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.
110
self.progress.update(gettext('checking branches and trees'), 3)
112
repo = self.repository
113
# calculate all refs, and callback the objects requesting them.
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
123
for ref, wantlist in viewitems(callback_refs):
124
wanting_items.update(wantlist)
127
refs[ref] = repo.revision_tree(value)
128
elif kind == 'lefthand-distance':
130
elif kind == 'revision-existence':
131
existences.add(value)
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):
150
if isinstance(item, Branch):
151
self.other_results.append(item.check(refs))
153
def _check_revisions(self, revisions_iterator):
154
"""Check revision objects by decorating a generator.
156
:param revisions_iterator: An iterator of(revid, Revision-or-None).
157
:return: A generator of the contents of revisions_iterator.
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
165
self.planned_revisions = list(self.planned_revisions)
166
# TODO: extract digital signatures as items to callback on too.
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:
184
bad_revisions = self.repository._find_inconsistent_revision_parents(
186
self.revs_with_bad_parents_in_index = list(bad_revisions)
188
def report_results(self, verbose):
190
self._report_repo_results(verbose)
191
for result in self.other_results:
192
result.report_results(verbose)
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))
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(
206
revision_id.decode('utf-8'), file_id.decode('utf-8')))
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)
214
note(gettext('%6d ghost revisions'), len(self.ghosts))
216
for ghost in self.ghosts:
217
note(' %s', ghost.decode('utf-8'))
218
if len(self.missing_parent_links):
219
note(gettext('%6d revisions missing parents in ancestry'),
220
len(self.missing_parent_links))
222
for link, linkers in viewitems(self.missing_parent_links):
223
note(gettext(' %s should be in the ancestry for:'),
224
link.decode('utf-8'))
225
for linker in linkers:
226
note(' * %s', linker.decode('utf-8'))
227
if len(self.inconsistent_parents):
228
note(gettext('%6d inconsistent parents'), len(self.inconsistent_parents))
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:
239
'%6d revisions have incorrect parents in the revision index'),
240
len(self.revs_with_bad_parents_in_index))
242
for item in self.revs_with_bad_parents_in_index:
243
revision_id, index_parents, actual_parents = item
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:
253
def _check_one_rev(self, rev_id, rev):
254
"""Cross-check one revision.
256
:param rev_id: A revision id to check.
257
:param rev: A revision or None to indicate a missing revision.
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
266
self.planned_revisions.add(rev_id)
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 not parent in self.planned_revisions:
272
self.ghosts.add(parent)
274
self.ancestors[rev_id] = tuple(rev.parent_ids) or (NULL_REVISION,)
275
self.add_pending_item(rev_id, ('inventories', rev_id), 'inventory',
277
self.checked_rev_cnt += 1
279
def add_pending_item(self, referer, key, kind, sha1):
280
"""Add a reference to a sha1 to be cross checked against a key.
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.
287
existing = self.pending_keys.get(key)
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]))
294
self.pending_keys[key] = (kind, sha1, referer)
296
def check_weaves(self):
297
"""Check all the weaves we can get our hands on.
300
with ui.ui_factory.nested_progress_bar() as storebar:
301
self._check_weaves(storebar)
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)
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)
327
def _add_entry_to_text_key_references(self, inv, entry):
328
if not self.rich_roots and entry.name == '':
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