/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
1570.1.2 by Robert Collins
Import bzrtools' 'fix' command as 'bzr reconcile.'
1
# (C) 2005, 2006 Canonical Limited.
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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
16
1570.1.7 by Robert Collins
Replace the slow topo_sort routine with a much faster one for non trivial datasets.
17
"""Reconcilers are able to fix some potential data errors in a branch."""
1570.1.2 by Robert Collins
Import bzrtools' 'fix' command as 'bzr reconcile.'
18
19
1570.1.14 by Robert Collins
Enforce repository consistency during 'fetch' operations.
20
__all__ = ['reconcile', 'Reconciler', 'RepoReconciler']
21
22
1570.1.2 by Robert Collins
Import bzrtools' 'fix' command as 'bzr reconcile.'
23
import bzrlib.branch
1570.1.6 by Robert Collins
Update fast topological_sort to be a function and to have the topo_sort tests run against it.
24
import bzrlib.errors as errors
1570.1.2 by Robert Collins
Import bzrtools' 'fix' command as 'bzr reconcile.'
25
import bzrlib.progress
26
from bzrlib.trace import mutter
1570.1.7 by Robert Collins
Replace the slow topo_sort routine with a much faster one for non trivial datasets.
27
from bzrlib.tsort import TopoSorter
1570.1.2 by Robert Collins
Import bzrtools' 'fix' command as 'bzr reconcile.'
28
import bzrlib.ui as ui
29
30
31
def reconcile(dir):
32
    """Reconcile the data in dir.
33
34
    Currently this is limited to a inventory 'reweave'.
35
1570.1.8 by Robert Collins
Only reconcile if doing so will perform gc or correct ancestry.
36
    This is a convenience method, for using a Reconciler object.
37
38
    Directly using Reconciler is recommended for library users that
39
    desire fine grained control or analysis of the found issues.
1570.1.2 by Robert Collins
Import bzrtools' 'fix' command as 'bzr reconcile.'
40
    """
41
    reconciler = Reconciler(dir)
42
    reconciler.reconcile()
43
44
1570.1.6 by Robert Collins
Update fast topological_sort to be a function and to have the topo_sort tests run against it.
45
class Reconciler(object):
1570.1.14 by Robert Collins
Enforce repository consistency during 'fetch' operations.
46
    """Reconcilers are used to reconcile existing data."""
1570.1.6 by Robert Collins
Update fast topological_sort to be a function and to have the topo_sort tests run against it.
47
48
    def __init__(self, dir):
49
        self.bzrdir = dir
50
51
    def reconcile(self):
1570.1.8 by Robert Collins
Only reconcile if doing so will perform gc or correct ancestry.
52
        """Perform reconciliation.
53
        
54
        After reconciliation the following attributes document found issues:
55
        inconsistent_parents: The number of revisions in the repository whose
56
                              ancestry was being reported incorrectly.
57
        garbage_inventories: The number of inventory objects without revisions
58
                             that were garbage collected.
59
        """
1594.1.3 by Robert Collins
Fixup pb usage to use nested_progress_bar.
60
        self.pb = ui.ui_factory.nested_progress_bar()
61
        try:
62
            self._reconcile()
63
        finally:
64
            self.pb.finished()
65
66
    def _reconcile(self):
67
        """Helper function for performing reconciliation."""
1570.1.11 by Robert Collins
Make reconcile work with shared repositories.
68
        self.repo = self.bzrdir.find_repository()
1570.1.14 by Robert Collins
Enforce repository consistency during 'fetch' operations.
69
        self.pb.note('Reconciling repository %s',
70
                     self.repo.bzrdir.root_transport.base)
71
        repo_reconciler = RepoReconciler(self.repo)
72
        repo_reconciler.reconcile()
73
        self.inconsistent_parents = repo_reconciler.inconsistent_parents
74
        self.garbage_inventories = repo_reconciler.garbage_inventories
75
        self.pb.note('Reconciliation complete.')
76
77
78
class RepoReconciler(object):
79
    """Reconciler that reconciles a repository.
80
81
    Currently this consists of an inventory reweave with revision cross-checks.
82
    """
83
84
    def __init__(self, repo):
85
        self.repo = repo
86
87
    def reconcile(self):
88
        """Perform reconciliation.
89
        
90
        After reconciliation the following attributes document found issues:
91
        inconsistent_parents: The number of revisions in the repository whose
92
                              ancestry was being reported incorrectly.
93
        garbage_inventories: The number of inventory objects without revisions
94
                             that were garbage collected.
95
        """
1570.1.6 by Robert Collins
Update fast topological_sort to be a function and to have the topo_sort tests run against it.
96
        self.repo.lock_write()
97
        try:
1594.1.3 by Robert Collins
Fixup pb usage to use nested_progress_bar.
98
            self.pb = ui.ui_factory.nested_progress_bar()
99
            try:
1594.2.7 by Robert Collins
Add versionedfile.fix_parents api for correcting data post hoc.
100
                self._reconcile_steps()
1594.1.3 by Robert Collins
Fixup pb usage to use nested_progress_bar.
101
            finally:
102
                self.pb.finished()
1570.1.6 by Robert Collins
Update fast topological_sort to be a function and to have the topo_sort tests run against it.
103
        finally:
104
            self.repo.unlock()
105
1594.2.7 by Robert Collins
Add versionedfile.fix_parents api for correcting data post hoc.
106
    def _reconcile_steps(self):
107
        """Perform the steps to reconcile this repository."""
108
        self._reweave_inventory()
109
1570.1.6 by Robert Collins
Update fast topological_sort to be a function and to have the topo_sort tests run against it.
110
    def _reweave_inventory(self):
111
        """Regenerate the inventory weave for the repository from scratch."""
1563.2.42 by Robert Collins
Stop reconcile on weaves being quadratic.
112
        # local because its really a wart we want to hide
113
        from bzrlib.weave import WeaveFile, Weave
1563.2.29 by Robert Collins
Remove all but fetch references to repository.revision_store.
114
        transaction = self.repo.get_transaction()
1570.1.6 by Robert Collins
Update fast topological_sort to be a function and to have the topo_sort tests run against it.
115
        self.pb.update('Reading inventory data.')
116
        self.inventory = self.repo.get_inventory_weave()
117
        # the total set of revisions to process
1563.2.29 by Robert Collins
Remove all but fetch references to repository.revision_store.
118
        self.pending = set([rev_id for rev_id in self.repo._revision_store.all_revision_ids(transaction)])
1570.1.6 by Robert Collins
Update fast topological_sort to be a function and to have the topo_sort tests run against it.
119
120
        # mapping from revision_id to parents
121
        self._rev_graph = {}
1570.1.8 by Robert Collins
Only reconcile if doing so will perform gc or correct ancestry.
122
        # errors that we detect
123
        self.inconsistent_parents = 0
1570.1.6 by Robert Collins
Update fast topological_sort to be a function and to have the topo_sort tests run against it.
124
        # we need the revision id of each revision and its available parents list
1570.1.10 by Robert Collins
UI tweaks to reconcile - show progress for inventory backup.
125
        self._setup_steps(len(self.pending))
1570.1.6 by Robert Collins
Update fast topological_sort to be a function and to have the topo_sort tests run against it.
126
        for rev_id in self.pending:
127
            # put a revision into the graph.
128
            self._graph_revision(rev_id)
1594.2.2 by Robert Collins
Trivial change to reconcile to mutter the cause of reconciliation to bzr.log
129
        self._check_garbage_inventories()
1570.1.8 by Robert Collins
Only reconcile if doing so will perform gc or correct ancestry.
130
        if not self.inconsistent_parents and not self.garbage_inventories:
131
            self.pb.note('Inventory ok.')
132
            return
1570.1.10 by Robert Collins
UI tweaks to reconcile - show progress for inventory backup.
133
        self.pb.update('Backing up inventory...', 0, 0)
1563.2.25 by Robert Collins
Merge in upstream.
134
        self.repo.control_weaves.copy(self.inventory, 'inventory.backup', self.repo.get_transaction())
1570.1.8 by Robert Collins
Only reconcile if doing so will perform gc or correct ancestry.
135
        self.pb.note('Backup Inventory created.')
136
        # asking for '' should never return a non-empty weave
1616.1.1 by Martin Pool
[merge] robertc
137
        new_inventory_vf = self.repo.control_weaves.get_empty('inventory.new',
1570.1.8 by Robert Collins
Only reconcile if doing so will perform gc or correct ancestry.
138
            self.repo.get_transaction())
1570.1.6 by Robert Collins
Update fast topological_sort to be a function and to have the topo_sort tests run against it.
139
1570.1.4 by Robert Collins
Somewhat optimised version of reconciler.
140
        # we have topological order of revisions and non ghost parents ready.
1570.1.10 by Robert Collins
UI tweaks to reconcile - show progress for inventory backup.
141
        self._setup_steps(len(self._rev_graph))
1570.1.7 by Robert Collins
Replace the slow topo_sort routine with a much faster one for non trivial datasets.
142
        for rev_id in TopoSorter(self._rev_graph.items()).iter_topo_order():
143
            parents = self._rev_graph[rev_id]
1570.1.4 by Robert Collins
Somewhat optimised version of reconciler.
144
            # double check this really is in topological order.
1616.1.1 by Martin Pool
[merge] robertc
145
            unavailable = [p for p in parents if p not in new_inventory_vf]
1570.1.4 by Robert Collins
Somewhat optimised version of reconciler.
146
            assert len(unavailable) == 0
147
            # this entry has all the non ghost parents in the inventory
148
            # file already.
149
            self._reweave_step('adding inventories')
1616.1.1 by Martin Pool
[merge] robertc
150
            if isinstance(new_inventory_vf, WeaveFile):
151
                # It's really a WeaveFile, but we call straight into the
152
                # Weave's add method to disable the auto-write-out behaviour.
153
                new_inventory_vf._check_write_ok()
154
                Weave._add_lines(new_inventory_vf, rev_id, parents, self.inventory.get_lines(rev_id),
155
                                 None)
1563.2.42 by Robert Collins
Stop reconcile on weaves being quadratic.
156
            else:
1616.1.1 by Martin Pool
[merge] robertc
157
                new_inventory_vf.add_lines(rev_id, parents, self.inventory.get_lines(rev_id))
1570.1.4 by Robert Collins
Somewhat optimised version of reconciler.
158
1616.1.1 by Martin Pool
[merge] robertc
159
        if isinstance(new_inventory_vf, WeaveFile):
160
            new_inventory_vf._save()
161
        # if this worked, the set of new_inventory_vf.names should equal
1570.1.4 by Robert Collins
Somewhat optimised version of reconciler.
162
        # self.pending
1616.1.1 by Martin Pool
[merge] robertc
163
        assert set(new_inventory_vf.versions()) == self.pending
1570.1.2 by Robert Collins
Import bzrtools' 'fix' command as 'bzr reconcile.'
164
        self.pb.update('Writing weave')
1616.1.1 by Martin Pool
[merge] robertc
165
        self.repo.control_weaves.copy(new_inventory_vf, 'inventory', self.repo.get_transaction())
1563.2.25 by Robert Collins
Merge in upstream.
166
        self.repo.control_weaves.delete('inventory.new', self.repo.get_transaction())
1570.1.3 by Robert Collins
Optimise reconcilation to only hit each revision once.
167
        self.inventory = None
1570.1.2 by Robert Collins
Import bzrtools' 'fix' command as 'bzr reconcile.'
168
        self.pb.note('Inventory regenerated.')
1570.1.3 by Robert Collins
Optimise reconcilation to only hit each revision once.
169
1570.1.10 by Robert Collins
UI tweaks to reconcile - show progress for inventory backup.
170
    def _setup_steps(self, new_total):
171
        """Setup the markers we need to control the progress bar."""
172
        self.total = new_total
173
        self.count = 0
174
1570.1.4 by Robert Collins
Somewhat optimised version of reconciler.
175
    def _graph_revision(self, rev_id):
176
        """Load a revision into the revision graph."""
177
        # pick a random revision
178
        # analyse revision id rev_id and put it in the stack.
179
        self._reweave_step('loading revisions')
1570.1.13 by Robert Collins
Check for incorrect revision parentage in the weave during revision access.
180
        rev = self.repo.get_revision_reconcile(rev_id)
1570.1.3 by Robert Collins
Optimise reconcilation to only hit each revision once.
181
        assert rev.revision_id == rev_id
182
        parents = []
183
        for parent in rev.parent_ids:
1570.1.14 by Robert Collins
Enforce repository consistency during 'fetch' operations.
184
            if self._parent_is_available(parent):
1570.1.3 by Robert Collins
Optimise reconcilation to only hit each revision once.
185
                parents.append(parent)
186
            else:
187
                mutter('found ghost %s', parent)
1570.1.4 by Robert Collins
Somewhat optimised version of reconciler.
188
        self._rev_graph[rev_id] = parents   
1563.2.25 by Robert Collins
Merge in upstream.
189
        if set(self.inventory.get_parents(rev_id)) != set(parents):
1570.1.8 by Robert Collins
Only reconcile if doing so will perform gc or correct ancestry.
190
            self.inconsistent_parents += 1
1594.2.2 by Robert Collins
Trivial change to reconcile to mutter the cause of reconciliation to bzr.log
191
            mutter('Inconsistent inventory parents: id {%s} '
192
                   'inventory claims %r, '
193
                   'available parents are %r, '
194
                   'unavailable parents are %r',
195
                   rev_id, 
1563.2.39 by Robert Collins
Merge from integration.
196
                   set(self.inventory.get_parents(rev_id)),
1594.2.2 by Robert Collins
Trivial change to reconcile to mutter the cause of reconciliation to bzr.log
197
                   set(parents),
198
                   set(rev.parent_ids).difference(set(parents)))
199
200
    def _check_garbage_inventories(self):
201
        """Check for garbage inventories which we cannot trust
202
203
        We cant trust them because their pre-requisite file data may not
204
        be present - all we know is that their revision was not installed.
205
        """
1563.2.39 by Robert Collins
Merge from integration.
206
        inventories = set(self.inventory.versions())
1594.2.2 by Robert Collins
Trivial change to reconcile to mutter the cause of reconciliation to bzr.log
207
        revisions = set(self._rev_graph.keys())
208
        garbage = inventories.difference(revisions)
209
        self.garbage_inventories = len(garbage)
210
        for revision_id in garbage:
211
            mutter('Garbage inventory {%s} found.', revision_id)
1570.1.4 by Robert Collins
Somewhat optimised version of reconciler.
212
1570.1.14 by Robert Collins
Enforce repository consistency during 'fetch' operations.
213
    def _parent_is_available(self, parent):
214
        """True if parent is a fully available revision
215
216
        A fully available revision has a inventory and a revision object in the
217
        repository.
218
        """
219
        return (parent in self._rev_graph or 
220
                (parent in self.inventory and self.repo.has_revision(parent)))
221
1570.1.4 by Robert Collins
Somewhat optimised version of reconciler.
222
    def _reweave_step(self, message):
223
        """Mark a single step of regeneration complete."""
224
        self.pb.update(message, self.count, self.total)
225
        self.count += 1
1594.2.7 by Robert Collins
Add versionedfile.fix_parents api for correcting data post hoc.
226
227
228
class KnitReconciler(RepoReconciler):
229
    """Reconciler that reconciles a knit format repository.
230
231
    This will detect garbage inventories and remove them.
232
233
    Inconsistent parentage is checked for in the revision weave.
234
    """
235
236
    def _reconcile_steps(self):
237
        """Perform the steps to reconcile this repository."""
238
        self._load_indexes()
1594.2.9 by Robert Collins
Teach Knit repositories how to handle ghosts without corrupting at all.
239
        # knits never suffer this
240
        self.inconsistent_parents = 0
1594.2.7 by Robert Collins
Add versionedfile.fix_parents api for correcting data post hoc.
241
        self._gc_inventory()
242
243
    def _load_indexes(self):
244
        """Load indexes for the reconciliation."""
245
        self.transaction = self.repo.get_transaction()
246
        self.pb.update('Reading indexes.', 0, 2)
247
        self.inventory = self.repo.get_inventory_weave()
248
        self.pb.update('Reading indexes.', 1, 2)
249
        self.revisions = self.repo._revision_store.get_revision_file(self.transaction)
250
        self.pb.update('Reading indexes.', 2, 2)
251
252
    def _gc_inventory(self):
253
        """Remove inventories that are not referenced from the revision store."""
254
        self.pb.update('Checking unused inventories.', 0, 1)
255
        self._check_garbage_inventories()
256
        self.pb.update('Checking unused inventories.', 1, 3)
257
        if not self.garbage_inventories:
258
            self.pb.note('Inventory ok.')
259
            return
260
        self.pb.update('Backing up inventory...', 0, 0)
261
        self.repo.control_weaves.copy(self.inventory, 'inventory.backup', self.transaction)
262
        self.pb.note('Backup Inventory created.')
263
        # asking for '' should never return a non-empty weave
1616.1.1 by Martin Pool
[merge] robertc
264
        new_inventory_vf = self.repo.control_weaves.get_empty('inventory.new',
1594.2.7 by Robert Collins
Add versionedfile.fix_parents api for correcting data post hoc.
265
            self.transaction)
266
267
        # we have topological order of revisions and non ghost parents ready.
1594.2.9 by Robert Collins
Teach Knit repositories how to handle ghosts without corrupting at all.
268
        self._setup_steps(len(self.revisions))
269
        for rev_id in TopoSorter(self.revisions.get_graph().items()).iter_topo_order():
270
            parents = self.revisions.get_parents(rev_id)
1594.2.7 by Robert Collins
Add versionedfile.fix_parents api for correcting data post hoc.
271
            # double check this really is in topological order.
1616.1.1 by Martin Pool
[merge] robertc
272
            unavailable = [p for p in parents if p not in new_inventory_vf]
1594.2.7 by Robert Collins
Add versionedfile.fix_parents api for correcting data post hoc.
273
            assert len(unavailable) == 0
274
            # this entry has all the non ghost parents in the inventory
275
            # file already.
276
            self._reweave_step('adding inventories')
277
            # ugly but needed, weaves are just way tooooo slow else.
1616.1.1 by Martin Pool
[merge] robertc
278
            new_inventory_vf.add_lines(rev_id, parents, self.inventory.get_lines(rev_id))
1594.2.7 by Robert Collins
Add versionedfile.fix_parents api for correcting data post hoc.
279
1616.1.1 by Martin Pool
[merge] robertc
280
        # if this worked, the set of new_inventory_vf.names should equal
1594.2.7 by Robert Collins
Add versionedfile.fix_parents api for correcting data post hoc.
281
        # self.pending
1616.1.1 by Martin Pool
[merge] robertc
282
        assert set(new_inventory_vf.versions()) == set(self.revisions.versions())
1594.2.7 by Robert Collins
Add versionedfile.fix_parents api for correcting data post hoc.
283
        self.pb.update('Writing weave')
1616.1.1 by Martin Pool
[merge] robertc
284
        self.repo.control_weaves.copy(new_inventory_vf, 'inventory', self.transaction)
1594.2.7 by Robert Collins
Add versionedfile.fix_parents api for correcting data post hoc.
285
        self.repo.control_weaves.delete('inventory.new', self.transaction)
286
        self.inventory = None
287
        self.pb.note('Inventory regenerated.')
288
289
    def _reinsert_revisions(self):
290
        """Correct the revision history for revisions in the revision knit."""
291
        # the total set of revisions to process
292
        self.pending = set(self.revisions.versions())
293
294
        # mapping from revision_id to parents
295
        self._rev_graph = {}
296
        # errors that we detect
297
        self.inconsistent_parents = 0
298
        # we need the revision id of each revision and its available parents list
299
        self._setup_steps(len(self.pending))
300
        for rev_id in self.pending:
301
            # put a revision into the graph.
302
            self._graph_revision(rev_id)
303
304
        if not self.inconsistent_parents:
305
            self.pb.note('Revision history accurate.')
306
            return
307
        self._setup_steps(len(self._rev_graph))
308
        for rev_id, parents in self._rev_graph.items():
309
            if parents != self.revisions.get_parents(rev_id):
310
                self.revisions.fix_parents(rev_id, parents)
311
            self._reweave_step('Fixing parents')
312
        self.pb.note('Ancestry corrected.')
313
314
    def _graph_revision(self, rev_id):
315
        """Load a revision into the revision graph."""
316
        # pick a random revision
317
        # analyse revision id rev_id and put it in the stack.
318
        self._reweave_step('loading revisions')
319
        rev = self.repo._revision_store.get_revision(rev_id, self.transaction)
320
        assert rev.revision_id == rev_id
321
        parents = []
322
        for parent in rev.parent_ids:
323
            if self.revisions.has_version(parent):
324
                parents.append(parent)
325
            else:
326
                mutter('found ghost %s', parent)
327
        self._rev_graph[rev_id] = parents   
328
        if set(self.inventory.get_parents(rev_id)) != set(parents):
329
            self.inconsistent_parents += 1
330
            mutter('Inconsistent inventory parents: id {%s} '
331
                   'inventory claims %r, '
332
                   'available parents are %r, '
333
                   'unavailable parents are %r',
334
                   rev_id, 
335
                   set(self.inventory.get_parents(rev_id)),
336
                   set(parents),
337
                   set(rev.parent_ids).difference(set(parents)))
338
339
    def _check_garbage_inventories(self):
340
        """Check for garbage inventories which we cannot trust
341
342
        We cant trust them because their pre-requisite file data may not
343
        be present - all we know is that their revision was not installed.
344
        """
345
        inventories = set(self.inventory.versions())
346
        revisions = set(self.revisions.versions())
347
        garbage = inventories.difference(revisions)
348
        self.garbage_inventories = len(garbage)
349
        for revision_id in garbage:
350
            mutter('Garbage inventory {%s} found.', revision_id)