/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 bzrlib/reconcile.py

  • Committer: Robert Collins
  • Date: 2006-05-02 12:32:40 UTC
  • mto: (1692.4.1 integration)
  • mto: This revision was merged to the branch mainline in revision 1694.
  • Revision ID: robertc@robertcollins.net-20060502123240-525d74f55b034ede
Teach reconcile to check the left-most parent is correct in the revision graph.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
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
 
 
17
"""Reconcilers are able to fix some potential data errors in a branch."""
 
18
 
 
19
 
 
20
__all__ = ['reconcile', 'Reconciler', 'RepoReconciler', 'KnitReconciler']
 
21
 
 
22
 
 
23
import bzrlib.branch
 
24
import bzrlib.errors as errors
 
25
import bzrlib.progress
 
26
from bzrlib.trace import mutter
 
27
from bzrlib.tsort import TopoSorter
 
28
import bzrlib.ui as ui
 
29
 
 
30
 
 
31
def reconcile(dir, other=None):
 
32
    """Reconcile the data in dir.
 
33
 
 
34
    Currently this is limited to a inventory 'reweave'.
 
35
 
 
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.
 
40
 
 
41
    :param other: another bzrdir to reconcile against.
 
42
    """
 
43
    reconciler = Reconciler(dir, other=other)
 
44
    reconciler.reconcile()
 
45
 
 
46
 
 
47
class Reconciler(object):
 
48
    """Reconcilers are used to reconcile existing data."""
 
49
 
 
50
    def __init__(self, dir, other=None):
 
51
        """Create a Reconciler."""
 
52
        self.bzrdir = dir
 
53
 
 
54
    def reconcile(self):
 
55
        """Perform reconciliation.
 
56
        
 
57
        After reconciliation the following attributes document found issues:
 
58
        inconsistent_parents: The number of revisions in the repository whose
 
59
                              ancestry was being reported incorrectly.
 
60
        garbage_inventories: The number of inventory objects without revisions
 
61
                             that were garbage collected.
 
62
        """
 
63
        self.pb = ui.ui_factory.nested_progress_bar()
 
64
        try:
 
65
            self._reconcile()
 
66
        finally:
 
67
            self.pb.finished()
 
68
 
 
69
    def _reconcile(self):
 
70
        """Helper function for performing reconciliation."""
 
71
        self.repo = self.bzrdir.find_repository()
 
72
        self.pb.note('Reconciling repository %s',
 
73
                     self.repo.bzrdir.root_transport.base)
 
74
        repo_reconciler = self.repo.reconcile(thorough=True)
 
75
        self.inconsistent_parents = repo_reconciler.inconsistent_parents
 
76
        self.garbage_inventories = repo_reconciler.garbage_inventories
 
77
        self.pb.note('Reconciliation complete.')
 
78
 
 
79
 
 
80
class RepoReconciler(object):
 
81
    """Reconciler that reconciles a repository.
 
82
 
 
83
    Currently this consists of an inventory reweave with revision cross-checks.
 
84
    """
 
85
 
 
86
    def __init__(self, repo, other=None, thorough=False):
 
87
        """Construct a RepoReconciler.
 
88
 
 
89
        :param thorough: perform a thorough check which may take longer but
 
90
                         will correct non-data loss issues such as incorrect
 
91
                         cached data.
 
92
        """
 
93
        self.garbage_inventories = 0
 
94
        self.inconsistent_parents = 0
 
95
        self.repo = repo
 
96
        self.thorough = thorough
 
97
 
 
98
    def reconcile(self):
 
99
        """Perform reconciliation.
 
100
        
 
101
        After reconciliation the following attributes document found issues:
 
102
        inconsistent_parents: The number of revisions in the repository whose
 
103
                              ancestry was being reported incorrectly.
 
104
        garbage_inventories: The number of inventory objects without revisions
 
105
                             that were garbage collected.
 
106
        """
 
107
        self.repo.lock_write()
 
108
        try:
 
109
            self.pb = ui.ui_factory.nested_progress_bar()
 
110
            try:
 
111
                self._reconcile_steps()
 
112
            finally:
 
113
                self.pb.finished()
 
114
        finally:
 
115
            self.repo.unlock()
 
116
 
 
117
    def _reconcile_steps(self):
 
118
        """Perform the steps to reconcile this repository."""
 
119
        if self.thorough:
 
120
            self._reweave_inventory()
 
121
 
 
122
    def _reweave_inventory(self):
 
123
        """Regenerate the inventory weave for the repository from scratch."""
 
124
        # local because its really a wart we want to hide
 
125
        from bzrlib.weave import WeaveFile, Weave
 
126
        transaction = self.repo.get_transaction()
 
127
        self.pb.update('Reading inventory data.')
 
128
        self.inventory = self.repo.get_inventory_weave()
 
129
        # the total set of revisions to process
 
130
        self.pending = set([rev_id for rev_id in self.repo._revision_store.all_revision_ids(transaction)])
 
131
 
 
132
        # mapping from revision_id to parents
 
133
        self._rev_graph = {}
 
134
        # errors that we detect
 
135
        self.inconsistent_parents = 0
 
136
        # we need the revision id of each revision and its available parents list
 
137
        self._setup_steps(len(self.pending))
 
138
        for rev_id in self.pending:
 
139
            # put a revision into the graph.
 
140
            self._graph_revision(rev_id)
 
141
        self._check_garbage_inventories()
 
142
        if not self.inconsistent_parents and not self.garbage_inventories:
 
143
            self.pb.note('Inventory ok.')
 
144
            return
 
145
        self.pb.update('Backing up inventory...', 0, 0)
 
146
        self.repo.control_weaves.copy(self.inventory, 'inventory.backup', self.repo.get_transaction())
 
147
        self.pb.note('Backup Inventory created.')
 
148
        # asking for '' should never return a non-empty weave
 
149
        new_inventory_vf = self.repo.control_weaves.get_empty('inventory.new',
 
150
            self.repo.get_transaction())
 
151
 
 
152
        # we have topological order of revisions and non ghost parents ready.
 
153
        self._setup_steps(len(self._rev_graph))
 
154
        for rev_id in TopoSorter(self._rev_graph.items()).iter_topo_order():
 
155
            parents = self._rev_graph[rev_id]
 
156
            # double check this really is in topological order.
 
157
            unavailable = [p for p in parents if p not in new_inventory_vf]
 
158
            assert len(unavailable) == 0
 
159
            # this entry has all the non ghost parents in the inventory
 
160
            # file already.
 
161
            self._reweave_step('adding inventories')
 
162
            if isinstance(new_inventory_vf, WeaveFile):
 
163
                # It's really a WeaveFile, but we call straight into the
 
164
                # Weave's add method to disable the auto-write-out behaviour.
 
165
                # This is done to avoid a revision_count * time-to-write additional overhead on 
 
166
                # reconcile.
 
167
                new_inventory_vf._check_write_ok()
 
168
                Weave._add_lines(new_inventory_vf, rev_id, parents, self.inventory.get_lines(rev_id),
 
169
                                 None)
 
170
            else:
 
171
                new_inventory_vf.add_lines(rev_id, parents, self.inventory.get_lines(rev_id))
 
172
 
 
173
        if isinstance(new_inventory_vf, WeaveFile):
 
174
            new_inventory_vf._save()
 
175
        # if this worked, the set of new_inventory_vf.names should equal
 
176
        # self.pending
 
177
        assert set(new_inventory_vf.versions()) == self.pending
 
178
        self.pb.update('Writing weave')
 
179
        self.repo.control_weaves.copy(new_inventory_vf, 'inventory', self.repo.get_transaction())
 
180
        self.repo.control_weaves.delete('inventory.new', self.repo.get_transaction())
 
181
        self.inventory = None
 
182
        self.pb.note('Inventory regenerated.')
 
183
 
 
184
    def _setup_steps(self, new_total):
 
185
        """Setup the markers we need to control the progress bar."""
 
186
        self.total = new_total
 
187
        self.count = 0
 
188
 
 
189
    def _graph_revision(self, rev_id):
 
190
        """Load a revision into the revision graph."""
 
191
        # pick a random revision
 
192
        # analyse revision id rev_id and put it in the stack.
 
193
        self._reweave_step('loading revisions')
 
194
        rev = self.repo.get_revision_reconcile(rev_id)
 
195
        assert rev.revision_id == rev_id
 
196
        parents = []
 
197
        for parent in rev.parent_ids:
 
198
            if self._parent_is_available(parent):
 
199
                parents.append(parent)
 
200
            else:
 
201
                mutter('found ghost %s', parent)
 
202
        self._rev_graph[rev_id] = parents   
 
203
        if (set(self.inventory.get_parents(rev_id)) != set(parents) or
 
204
            (len(self.inventory.get_parents(rev_id)) and len(parents) and
 
205
             parents[0] != self.inventory.get_parents(rev_id)[0])):
 
206
            self.inconsistent_parents += 1
 
207
            mutter('Inconsistent inventory parents: id {%s} '
 
208
                   'inventory claims %r, '
 
209
                   'available parents are %r, '
 
210
                   'unavailable parents are %r',
 
211
                   rev_id, 
 
212
                   set(self.inventory.get_parents(rev_id)),
 
213
                   set(parents),
 
214
                   set(rev.parent_ids).difference(set(parents)))
 
215
 
 
216
    def _check_garbage_inventories(self):
 
217
        """Check for garbage inventories which we cannot trust
 
218
 
 
219
        We cant trust them because their pre-requisite file data may not
 
220
        be present - all we know is that their revision was not installed.
 
221
        """
 
222
        inventories = set(self.inventory.versions())
 
223
        revisions = set(self._rev_graph.keys())
 
224
        garbage = inventories.difference(revisions)
 
225
        self.garbage_inventories = len(garbage)
 
226
        for revision_id in garbage:
 
227
            mutter('Garbage inventory {%s} found.', revision_id)
 
228
 
 
229
    def _parent_is_available(self, parent):
 
230
        """True if parent is a fully available revision
 
231
 
 
232
        A fully available revision has a inventory and a revision object in the
 
233
        repository.
 
234
        """
 
235
        return (parent in self._rev_graph or 
 
236
                (parent in self.inventory and self.repo.has_revision(parent)))
 
237
 
 
238
    def _reweave_step(self, message):
 
239
        """Mark a single step of regeneration complete."""
 
240
        self.pb.update(message, self.count, self.total)
 
241
        self.count += 1
 
242
 
 
243
 
 
244
class KnitReconciler(RepoReconciler):
 
245
    """Reconciler that reconciles a knit format repository.
 
246
 
 
247
    This will detect garbage inventories and remove them.
 
248
 
 
249
    Inconsistent parentage is checked for in the revision weave.
 
250
    """
 
251
 
 
252
    def _reconcile_steps(self):
 
253
        """Perform the steps to reconcile this repository."""
 
254
        if self.thorough:
 
255
            self._load_indexes()
 
256
            # knits never suffer this
 
257
            self._gc_inventory()
 
258
 
 
259
    def _load_indexes(self):
 
260
        """Load indexes for the reconciliation."""
 
261
        self.transaction = self.repo.get_transaction()
 
262
        self.pb.update('Reading indexes.', 0, 2)
 
263
        self.inventory = self.repo.get_inventory_weave()
 
264
        self.pb.update('Reading indexes.', 1, 2)
 
265
        self.revisions = self.repo._revision_store.get_revision_file(self.transaction)
 
266
        self.pb.update('Reading indexes.', 2, 2)
 
267
 
 
268
    def _gc_inventory(self):
 
269
        """Remove inventories that are not referenced from the revision store."""
 
270
        self.pb.update('Checking unused inventories.', 0, 1)
 
271
        self._check_garbage_inventories()
 
272
        self.pb.update('Checking unused inventories.', 1, 3)
 
273
        if not self.garbage_inventories:
 
274
            self.pb.note('Inventory ok.')
 
275
            return
 
276
        self.pb.update('Backing up inventory...', 0, 0)
 
277
        self.repo.control_weaves.copy(self.inventory, 'inventory.backup', self.transaction)
 
278
        self.pb.note('Backup Inventory created.')
 
279
        # asking for '' should never return a non-empty weave
 
280
        new_inventory_vf = self.repo.control_weaves.get_empty('inventory.new',
 
281
            self.transaction)
 
282
 
 
283
        # we have topological order of revisions and non ghost parents ready.
 
284
        self._setup_steps(len(self.revisions))
 
285
        for rev_id in TopoSorter(self.revisions.get_graph().items()).iter_topo_order():
 
286
            parents = self.revisions.get_parents(rev_id)
 
287
            # double check this really is in topological order.
 
288
            unavailable = [p for p in parents if p not in new_inventory_vf]
 
289
            assert len(unavailable) == 0
 
290
            # this entry has all the non ghost parents in the inventory
 
291
            # file already.
 
292
            self._reweave_step('adding inventories')
 
293
            # ugly but needed, weaves are just way tooooo slow else.
 
294
            new_inventory_vf.add_lines(rev_id, parents, self.inventory.get_lines(rev_id))
 
295
 
 
296
        # if this worked, the set of new_inventory_vf.names should equal
 
297
        # self.pending
 
298
        assert set(new_inventory_vf.versions()) == set(self.revisions.versions())
 
299
        self.pb.update('Writing weave')
 
300
        self.repo.control_weaves.copy(new_inventory_vf, 'inventory', self.transaction)
 
301
        self.repo.control_weaves.delete('inventory.new', self.transaction)
 
302
        self.inventory = None
 
303
        self.pb.note('Inventory regenerated.')
 
304
 
 
305
    def _check_garbage_inventories(self):
 
306
        """Check for garbage inventories which we cannot trust
 
307
 
 
308
        We cant trust them because their pre-requisite file data may not
 
309
        be present - all we know is that their revision was not installed.
 
310
        """
 
311
        inventories = set(self.inventory.versions())
 
312
        revisions = set(self.revisions.versions())
 
313
        garbage = inventories.difference(revisions)
 
314
        self.garbage_inventories = len(garbage)
 
315
        for revision_id in garbage:
 
316
            mutter('Garbage inventory {%s} found.', revision_id)