~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/check.py

  • Committer: Canonical.com Patch Queue Manager
  • Date: 2011-05-04 12:10:51 UTC
  • mfrom: (5819.1.4 777007-developer-doc)
  • Revision ID: pqm@pqm.ubuntu.com-20110504121051-aovlsmqiivjmc4fc
(jelmer) Small fixes to developer documentation. (Jonathan Riddell)

Show diffs side-by-side

added added

removed removed

Lines of Context:
12
12
#
13
13
# You should have received a copy of the GNU General Public License
14
14
# along with this program; if not, write to the Free Software
15
 
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
16
16
 
17
17
# TODO: Check ancestries are correct for every revision: includes
18
18
# every committed so far, and in a reasonable order.
21
21
 
22
22
# TODO: Check for extra files in the control directory.
23
23
 
24
 
# TODO: Check revision, inventory and entry objects have all 
 
24
# TODO: Check revision, inventory and entry objects have all
25
25
# required fields.
26
26
 
27
27
# TODO: Get every revision in the revision-store even if they're not
32
32
# raising them.  If there's more than one exception it'd be good to see them
33
33
# all.
34
34
 
35
 
from bzrlib.errors import BzrCheckError
36
 
import bzrlib.ui
 
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
* 'trees', where value is a revid and the looked up objects are revision trees.
 
43
* 'lefthand-distance', where value is a revid and the looked up objects are the
 
44
  distance along the lefthand path to NULL for that revid.
 
45
* 'revision-existence', where value is a revid, and the result is True or False
 
46
  indicating that the revision was found/not found.
 
47
"""
 
48
 
 
49
from bzrlib import (
 
50
    errors,
 
51
    ui,
 
52
    )
 
53
from bzrlib.branch import Branch
 
54
from bzrlib.bzrdir import BzrDir
 
55
from bzrlib.revision import NULL_REVISION
 
56
from bzrlib.symbol_versioning import deprecated_function, deprecated_in
37
57
from bzrlib.trace import note
 
58
from bzrlib.workingtree import WorkingTree
38
59
 
39
60
class Check(object):
40
61
    """Check a repository"""
41
62
 
42
63
    # The Check object interacts with InventoryEntry.check, etc.
43
64
 
44
 
    def __init__(self, repository):
 
65
    def __init__(self, repository, check_repo=True):
45
66
        self.repository = repository
46
 
        self.checked_text_cnt = 0
47
67
        self.checked_rev_cnt = 0
48
 
        self.ghosts = []
49
 
        self.repeated_text_cnt = 0
 
68
        self.ghosts = set()
50
69
        self.missing_parent_links = {}
51
70
        self.missing_inventory_sha_cnt = 0
52
71
        self.missing_revision_cnt = 0
53
 
        # maps (file-id, version) -> sha1; used by InventoryFile._check
54
 
        self.checked_texts = {}
55
 
        self.checked_weaves = {}
 
72
        self.checked_weaves = set()
 
73
        self.unreferenced_versions = set()
 
74
        self.inconsistent_parents = []
 
75
        self.rich_roots = repository.supports_rich_root()
 
76
        self.text_key_references = {}
 
77
        self.check_repo = check_repo
 
78
        self.other_results = []
 
79
        # Plain text lines to include in the report
 
80
        self._report_items = []
 
81
        # Keys we are looking for; may be large and need spilling to disk.
 
82
        # key->(type(revision/inventory/text/signature/map), sha1, first-referer)
 
83
        self.pending_keys = {}
 
84
        # Ancestors map for all of revisions being checked; while large helper
 
85
        # functions we call would create it anyway, so better to have once and
 
86
        # keep.
 
87
        self.ancestors = {}
56
88
 
57
 
    def check(self):
 
89
    def check(self, callback_refs=None, check_repo=True):
 
90
        if callback_refs is None:
 
91
            callback_refs = {}
58
92
        self.repository.lock_read()
59
 
        self.progress = bzrlib.ui.ui_factory.nested_progress_bar()
 
93
        self.progress = ui.ui_factory.nested_progress_bar()
60
94
        try:
61
 
            self.progress.update('retrieving inventory', 0, 0)
62
 
            # do not put in init, as it should be done with progess,
63
 
            # and inside the lock.
64
 
            self.inventory_weave = self.repository.get_inventory_weave()
65
 
            self.plan_revisions()
66
 
            revno = 0
67
 
            self.check_weaves()
68
 
            while revno < len(self.planned_revisions):
69
 
                rev_id = self.planned_revisions[revno]
70
 
                self.progress.update('checking revision', revno,
71
 
                                     len(self.planned_revisions))
72
 
                revno += 1
73
 
                self.check_one_rev(rev_id)
 
95
            self.progress.update('check', 0, 4)
 
96
            if self.check_repo:
 
97
                self.progress.update('checking revisions', 0)
 
98
                self.check_revisions()
 
99
                self.progress.update('checking commit contents', 1)
 
100
                self.repository._check_inventories(self)
 
101
                self.progress.update('checking file graphs', 2)
 
102
                # check_weaves is done after the revision scan so that
 
103
                # revision index is known to be valid.
 
104
                self.check_weaves()
 
105
            self.progress.update('checking branches and trees', 3)
 
106
            if callback_refs:
 
107
                repo = self.repository
 
108
                # calculate all refs, and callback the objects requesting them.
 
109
                refs = {}
 
110
                wanting_items = set()
 
111
                # Current crude version calculates everything and calls
 
112
                # everything at once. Doing a queue and popping as things are
 
113
                # satisfied would be cheaper on memory [but few people have
 
114
                # huge numbers of working trees today. TODO: fix before
 
115
                # landing].
 
116
                distances = set()
 
117
                existences = set()
 
118
                for ref, wantlist in callback_refs.iteritems():
 
119
                    wanting_items.update(wantlist)
 
120
                    kind, value = ref
 
121
                    if kind == 'trees':
 
122
                        refs[ref] = repo.revision_tree(value)
 
123
                    elif kind == 'lefthand-distance':
 
124
                        distances.add(value)
 
125
                    elif kind == 'revision-existence':
 
126
                        existences.add(value)
 
127
                    else:
 
128
                        raise AssertionError(
 
129
                            'unknown ref kind for ref %s' % ref)
 
130
                node_distances = repo.get_graph().find_lefthand_distances(distances)
 
131
                for key, distance in node_distances.iteritems():
 
132
                    refs[('lefthand-distance', key)] = distance
 
133
                    if key in existences and distance > 0:
 
134
                        refs[('revision-existence', key)] = True
 
135
                        existences.remove(key)
 
136
                parent_map = repo.get_graph().get_parent_map(existences)
 
137
                for key in parent_map:
 
138
                    refs[('revision-existence', key)] = True
 
139
                    existences.remove(key)
 
140
                for key in existences:
 
141
                    refs[('revision-existence', key)] = False
 
142
                for item in wanting_items:
 
143
                    if isinstance(item, WorkingTree):
 
144
                        item._check(refs)
 
145
                    if isinstance(item, Branch):
 
146
                        self.other_results.append(item.check(refs))
74
147
        finally:
75
148
            self.progress.finished()
76
149
            self.repository.unlock()
77
150
 
78
 
    def plan_revisions(self):
79
 
        repository = self.repository
80
 
        self.planned_revisions = set(repository.all_revision_ids())
81
 
        self.progress.clear()
82
 
        inventoried = set(self.inventory_weave.versions())
83
 
        awol = self.planned_revisions - inventoried
84
 
        if len(awol) > 0:
85
 
            raise BzrCheckError('Stored revisions missing from inventory'
86
 
                '{%s}' % ','.join([f for f in awol]))
 
151
    def _check_revisions(self, revisions_iterator):
 
152
        """Check revision objects by decorating a generator.
 
153
 
 
154
        :param revisions_iterator: An iterator of(revid, Revision-or-None).
 
155
        :return: A generator of the contents of revisions_iterator.
 
156
        """
 
157
        self.planned_revisions = set()
 
158
        for revid, revision in revisions_iterator:
 
159
            yield revid, revision
 
160
            self._check_one_rev(revid, revision)
 
161
        # Flatten the revisions we found to guarantee consistent later
 
162
        # iteration.
87
163
        self.planned_revisions = list(self.planned_revisions)
 
164
        # TODO: extract digital signatures as items to callback on too.
 
165
 
 
166
    def check_revisions(self):
 
167
        """Scan revisions, checking data directly available as we go."""
 
168
        revision_iterator = self.repository._iter_revisions(None)
 
169
        revision_iterator = self._check_revisions(revision_iterator)
 
170
        # We read the all revisions here:
 
171
        # - doing this allows later code to depend on the revision index.
 
172
        # - we can fill out existence flags at this point
 
173
        # - we can read the revision inventory sha at this point
 
174
        # - we can check properties and serialisers etc.
 
175
        if not self.repository._format.revision_graph_can_have_wrong_parents:
 
176
            # The check against the index isn't needed.
 
177
            self.revs_with_bad_parents_in_index = None
 
178
            for thing in revision_iterator:
 
179
                pass
 
180
        else:
 
181
            bad_revisions = self.repository._find_inconsistent_revision_parents(
 
182
                revision_iterator)
 
183
            self.revs_with_bad_parents_in_index = list(bad_revisions)
88
184
 
89
185
    def report_results(self, verbose):
 
186
        if self.check_repo:
 
187
            self._report_repo_results(verbose)
 
188
        for result in self.other_results:
 
189
            result.report_results(verbose)
 
190
 
 
191
    def _report_repo_results(self, verbose):
90
192
        note('checked repository %s format %s',
91
 
             self.repository.bzrdir.root_transport,
92
 
             self.repository._format)
 
193
            self.repository.user_url,
 
194
            self.repository._format)
93
195
        note('%6d revisions', self.checked_rev_cnt)
94
 
        note('%6d unique file texts', self.checked_text_cnt)
95
 
        note('%6d repeated file texts', self.repeated_text_cnt)
96
 
        note('%6d weaves', len(self.checked_weaves))
 
196
        note('%6d file-ids', len(self.checked_weaves))
 
197
        if verbose:
 
198
            note('%6d unreferenced text versions',
 
199
                len(self.unreferenced_versions))
 
200
        if verbose and len(self.unreferenced_versions):
 
201
                for file_id, revision_id in self.unreferenced_versions:
 
202
                    note('unreferenced version: {%s} in %s', revision_id,
 
203
                        file_id)
97
204
        if self.missing_inventory_sha_cnt:
98
205
            note('%6d revisions are missing inventory_sha1',
99
206
                 self.missing_inventory_sha_cnt)
113
220
                    note('      %s should be in the ancestry for:', link)
114
221
                    for linker in linkers:
115
222
                        note('       * %s', linker)
116
 
 
117
 
    def check_one_rev(self, rev_id):
118
 
        """Check one revision.
119
 
 
120
 
        rev_id - the one to check
 
223
        if len(self.inconsistent_parents):
 
224
            note('%6d inconsistent parents', len(self.inconsistent_parents))
 
225
            if verbose:
 
226
                for info in self.inconsistent_parents:
 
227
                    revision_id, file_id, found_parents, correct_parents = info
 
228
                    note('      * %s version %s has parents %r '
 
229
                         'but should have %r'
 
230
                         % (file_id, revision_id, found_parents,
 
231
                             correct_parents))
 
232
        if self.revs_with_bad_parents_in_index:
 
233
            note('%6d revisions have incorrect parents in the revision index',
 
234
                 len(self.revs_with_bad_parents_in_index))
 
235
            if verbose:
 
236
                for item in self.revs_with_bad_parents_in_index:
 
237
                    revision_id, index_parents, actual_parents = item
 
238
                    note(
 
239
                        '       %s has wrong parents in index: '
 
240
                        '%r should be %r',
 
241
                        revision_id, index_parents, actual_parents)
 
242
        for item in self._report_items:
 
243
            note(item)
 
244
 
 
245
    def _check_one_rev(self, rev_id, rev):
 
246
        """Cross-check one revision.
 
247
 
 
248
        :param rev_id: A revision id to check.
 
249
        :param rev: A revision or None to indicate a missing revision.
121
250
        """
122
 
        rev = self.repository.get_revision(rev_id)
123
 
                
124
251
        if rev.revision_id != rev_id:
125
 
            raise BzrCheckError('wrong internal revision id in revision {%s}'
126
 
                                % rev_id)
127
 
 
 
252
            self._report_items.append(
 
253
                'Mismatched internal revid {%s} and index revid {%s}' % (
 
254
                rev.revision_id, rev_id))
 
255
            rev_id = rev.revision_id
 
256
        # Check this revision tree etc, and count as seen when we encounter a
 
257
        # reference to it.
 
258
        self.planned_revisions.add(rev_id)
 
259
        # It is not a ghost
 
260
        self.ghosts.discard(rev_id)
 
261
        # Count all parents as ghosts if we haven't seen them yet.
128
262
        for parent in rev.parent_ids:
129
263
            if not parent in self.planned_revisions:
130
 
                missing_links = self.missing_parent_links.get(parent, [])
131
 
                missing_links.append(rev_id)
132
 
                self.missing_parent_links[parent] = missing_links
133
 
                # list based so somewhat slow,
134
 
                # TODO have a planned_revisions list and set.
135
 
                if self.repository.has_revision(parent):
136
 
                    missing_ancestry = self.repository.get_ancestry(parent)
137
 
                    for missing in missing_ancestry:
138
 
                        if (missing is not None 
139
 
                            and missing not in self.planned_revisions):
140
 
                            self.planned_revisions.append(missing)
141
 
                else:
142
 
                    self.ghosts.append(rev_id)
143
 
 
144
 
        if rev.inventory_sha1:
145
 
            inv_sha1 = self.repository.get_inventory_sha1(rev_id)
146
 
            if inv_sha1 != rev.inventory_sha1:
147
 
                raise BzrCheckError('Inventory sha1 hash doesn\'t match'
148
 
                    ' value in revision {%s}' % rev_id)
149
 
        self._check_revision_tree(rev_id)
 
264
                self.ghosts.add(parent)
 
265
        
 
266
        self.ancestors[rev_id] = tuple(rev.parent_ids) or (NULL_REVISION,)
 
267
        self.add_pending_item(rev_id, ('inventories', rev_id), 'inventory',
 
268
            rev.inventory_sha1)
150
269
        self.checked_rev_cnt += 1
151
270
 
 
271
    def add_pending_item(self, referer, key, kind, sha1):
 
272
        """Add a reference to a sha1 to be cross checked against a key.
 
273
 
 
274
        :param referer: The referer that expects key to have sha1.
 
275
        :param key: A storage key e.g. ('texts', 'foo@bar-20040504-1234')
 
276
        :param kind: revision/inventory/text/map/signature
 
277
        :param sha1: A hex sha1 or None if no sha1 is known.
 
278
        """
 
279
        existing = self.pending_keys.get(key)
 
280
        if existing:
 
281
            if sha1 != existing[1]:
 
282
                self._report_items.append('Multiple expected sha1s for %s. {%s}'
 
283
                    ' expects {%s}, {%s} expects {%s}', (
 
284
                    key, referer, sha1, existing[1], existing[0]))
 
285
        else:
 
286
            self.pending_keys[key] = (kind, sha1, referer)
 
287
 
152
288
    def check_weaves(self):
153
289
        """Check all the weaves we can get our hands on.
154
290
        """
155
 
        n_weaves = 1
156
291
        weave_ids = []
157
 
        if self.repository.weave_store.listable():
158
 
            weave_ids = list(self.repository.weave_store)
159
 
            n_weaves = len(weave_ids)
160
 
        self.progress.update('checking weave', 0, n_weaves)
161
 
        self.inventory_weave.check(progress_bar=self.progress)
162
 
        for i, weave_id in enumerate(weave_ids):
163
 
            self.progress.update('checking weave', i, n_weaves)
164
 
            w = self.repository.weave_store.get_weave(weave_id,
165
 
                    self.repository.get_transaction())
166
 
            # No progress here, because it looks ugly.
167
 
            w.check()
168
 
            self.checked_weaves[weave_id] = True
169
 
 
170
 
    def _check_revision_tree(self, rev_id):
171
 
        tree = self.repository.revision_tree(rev_id)
172
 
        inv = tree.inventory
173
 
        seen_ids = {}
174
 
        for file_id in inv:
175
 
            if file_id in seen_ids:
176
 
                raise BzrCheckError('duplicated file_id {%s} '
177
 
                                    'in inventory for revision {%s}'
178
 
                                    % (file_id, rev_id))
179
 
            seen_ids[file_id] = True
180
 
        for file_id in inv:
181
 
            ie = inv[file_id]
182
 
            ie.check(self, rev_id, inv, tree)
183
 
        seen_names = {}
184
 
        for path, ie in inv.iter_entries():
185
 
            if path in seen_names:
186
 
                raise BzrCheckError('duplicated path %s '
187
 
                                    'in inventory for revision {%s}'
188
 
                                    % (path, rev_id))
189
 
            seen_names[path] = True
190
 
 
191
 
 
192
 
def check(branch, verbose):
193
 
    """Run consistency checks on a branch.
194
 
    
195
 
    Results are reported through logging.
196
 
    
197
 
    :raise BzrCheckError: if there's a consistency error.
 
292
        storebar = ui.ui_factory.nested_progress_bar()
 
293
        try:
 
294
            self._check_weaves(storebar)
 
295
        finally:
 
296
            storebar.finished()
 
297
 
 
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)
 
304
        else:
 
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
        result = weave_checker.check_file_version_parents(
 
310
            self.repository.texts)
 
311
        self.checked_weaves = weave_checker.file_ids
 
312
        bad_parents, unused_versions = result
 
313
        bad_parents = bad_parents.items()
 
314
        for text_key, (stored_parents, correct_parents) in bad_parents:
 
315
            # XXX not ready for id join/split operations.
 
316
            weave_id = text_key[0]
 
317
            revision_id = text_key[-1]
 
318
            weave_parents = tuple([parent[-1] for parent in stored_parents])
 
319
            correct_parents = tuple([parent[-1] for parent in correct_parents])
 
320
            self.inconsistent_parents.append(
 
321
                (revision_id, weave_id, weave_parents, correct_parents))
 
322
        self.unreferenced_versions.update(unused_versions)
 
323
 
 
324
    def _add_entry_to_text_key_references(self, inv, entry):
 
325
        if not self.rich_roots and entry.name == '':
 
326
            return
 
327
        key = (entry.file_id, entry.revision)
 
328
        self.text_key_references.setdefault(key, False)
 
329
        if entry.revision == inv.revision_id:
 
330
            self.text_key_references[key] = True
 
331
 
 
332
 
 
333
def scan_branch(branch, needed_refs, to_unlock):
 
334
    """Scan a branch for refs.
 
335
 
 
336
    :param branch:  The branch to schedule for checking.
 
337
    :param needed_refs: Refs we are accumulating.
 
338
    :param to_unlock: The unlock list accumulating.
198
339
    """
 
340
    note("Checking branch at '%s'." % (branch.base,))
199
341
    branch.lock_read()
200
 
    try:
201
 
        branch_result = branch.check()
202
 
        repo_result = branch.repository.check([branch.last_revision()])
 
342
    to_unlock.append(branch)
 
343
    branch_refs = branch._get_check_refs()
 
344
    for ref in branch_refs:
 
345
        reflist = needed_refs.setdefault(ref, [])
 
346
        reflist.append(branch)
 
347
 
 
348
 
 
349
def scan_tree(base_tree, tree, needed_refs, to_unlock):
 
350
    """Scan a tree for refs.
 
351
 
 
352
    :param base_tree: The original tree check opened, used to detect duplicate
 
353
        tree checks.
 
354
    :param tree:  The tree to schedule for checking.
 
355
    :param needed_refs: Refs we are accumulating.
 
356
    :param to_unlock: The unlock list accumulating.
 
357
    """
 
358
    if base_tree is not None and tree.basedir == base_tree.basedir:
 
359
        return
 
360
    note("Checking working tree at '%s'." % (tree.basedir,))
 
361
    tree.lock_read()
 
362
    to_unlock.append(tree)
 
363
    tree_refs = tree._get_check_refs()
 
364
    for ref in tree_refs:
 
365
        reflist = needed_refs.setdefault(ref, [])
 
366
        reflist.append(tree)
 
367
 
 
368
 
 
369
def check_dwim(path, verbose, do_branch=False, do_repo=False, do_tree=False):
 
370
    """Check multiple objects.
 
371
 
 
372
    If errors occur they are accumulated and reported as far as possible, and
 
373
    an exception raised at the end of the process.
 
374
    """
 
375
    try:
 
376
        base_tree, branch, repo, relpath = \
 
377
                        BzrDir.open_containing_tree_branch_or_repository(path)
 
378
    except errors.NotBranchError:
 
379
        base_tree = branch = repo = None
 
380
 
 
381
    to_unlock = []
 
382
    needed_refs= {}
 
383
    try:
 
384
        if base_tree is not None:
 
385
            # If the tree is a lightweight checkout we won't see it in
 
386
            # repo.find_branches - add now.
 
387
            if do_tree:
 
388
                scan_tree(None, base_tree, needed_refs, to_unlock)
 
389
            branch = base_tree.branch
 
390
        if branch is not None:
 
391
            # We have a branch
 
392
            if repo is None:
 
393
                # The branch is in a shared repository
 
394
                repo = branch.repository
 
395
        if repo is not None:
 
396
            repo.lock_read()
 
397
            to_unlock.append(repo)
 
398
            branches = repo.find_branches(using=True)
 
399
            saw_tree = False
 
400
            if do_branch or do_tree:
 
401
                for branch in branches:
 
402
                    if do_tree:
 
403
                        try:
 
404
                            tree = branch.bzrdir.open_workingtree()
 
405
                            saw_tree = True
 
406
                        except (errors.NotLocalUrl, errors.NoWorkingTree):
 
407
                            pass
 
408
                        else:
 
409
                            scan_tree(base_tree, tree, needed_refs, to_unlock)
 
410
                    if do_branch:
 
411
                        scan_branch(branch, needed_refs, to_unlock)
 
412
            if do_branch and not branches:
 
413
                note("No branch found at specified location.")
 
414
            if do_tree and base_tree is None and not saw_tree:
 
415
                note("No working tree found at specified location.")
 
416
            if do_repo or do_branch or do_tree:
 
417
                if do_repo:
 
418
                    note("Checking repository at '%s'."
 
419
                         % (repo.user_url,))
 
420
                result = repo.check(None, callback_refs=needed_refs,
 
421
                    check_repo=do_repo)
 
422
                result.report_results(verbose)
 
423
        else:
 
424
            if do_tree:
 
425
                note("No working tree found at specified location.")
 
426
            if do_branch:
 
427
                note("No branch found at specified location.")
 
428
            if do_repo:
 
429
                note("No repository found at specified location.")
203
430
    finally:
204
 
        branch.unlock()
205
 
    branch_result.report_results(verbose)
206
 
    repo_result.report_results(verbose)
 
431
        for thing in to_unlock:
 
432
            thing.unlock()