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