1
# Copyright (C) 2006-2010 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
"""Reconcilers are able to fix some potential data errors in a branch."""
19
from __future__ import absolute_import
25
'VersionedFileRepoReconciler',
31
revision as _mod_revision,
34
from ..reconcile import ReconcileResult
35
from ..i18n import gettext
36
from ..trace import mutter
37
from ..tsort import topo_sort
38
from .versionedfile import AdapterFactory, ChunkedContentFactory
41
class VersionedFileRepoReconciler(object):
42
"""Reconciler that reconciles a repository.
44
The goal of repository reconciliation is to make any derived data
45
consistent with the core data committed by a user. This can involve
46
reindexing, or removing unreferenced data if that can interfere with
47
queries in a given repository.
49
Currently this consists of an inventory reweave with revision cross-checks.
52
def __init__(self, repo, other=None, thorough=False):
53
"""Construct a RepoReconciler.
55
:param thorough: perform a thorough check which may take longer but
56
will correct non-data loss issues such as incorrect
59
self.garbage_inventories = 0
60
self.inconsistent_parents = 0
63
self.thorough = thorough
66
"""Perform reconciliation.
68
After reconciliation the following attributes document found issues:
70
* `inconsistent_parents`: The number of revisions in the repository
71
whose ancestry was being reported incorrectly.
72
* `garbage_inventories`: The number of inventory objects without
73
revisions that were garbage collected.
75
with self.repo.lock_write(), \
76
ui.ui_factory.nested_progress_bar() as self.pb:
77
self._reconcile_steps()
78
ret = ReconcileResult()
79
ret.aborted = self.aborted
80
ret.garbage_inventories = self.garbage_inventories
81
ret.inconsistent_parents = self.inconsistent_parents
84
def _reconcile_steps(self):
85
"""Perform the steps to reconcile this repository."""
86
self._reweave_inventory()
88
def _reweave_inventory(self):
89
"""Regenerate the inventory weave for the repository from scratch.
91
This is a smart function: it will only do the reweave if doing it
92
will correct data issues. The self.thorough flag controls whether
93
only data-loss causing issues (!self.thorough) or all issues
94
(self.thorough) are treated as requiring the reweave.
96
transaction = self.repo.get_transaction()
97
self.pb.update(gettext('Reading inventory data'))
98
self.inventory = self.repo.inventories
99
self.revisions = self.repo.revisions
100
# the total set of revisions to process
101
self.pending = {key[-1] for key in self.revisions.keys()}
103
# mapping from revision_id to parents
105
# errors that we detect
106
self.inconsistent_parents = 0
107
# we need the revision id of each revision and its available parents list
108
self._setup_steps(len(self.pending))
109
for rev_id in self.pending:
110
# put a revision into the graph.
111
self._graph_revision(rev_id)
112
self._check_garbage_inventories()
113
# if there are no inconsistent_parents and
114
# (no garbage inventories or we are not doing a thorough check)
115
if (not self.inconsistent_parents
116
and (not self.garbage_inventories or not self.thorough)):
117
ui.ui_factory.note(gettext('Inventory ok.'))
119
self.pb.update(gettext('Backing up inventory'), 0, 0)
120
self.repo._backup_inventory()
121
ui.ui_factory.note(gettext('Backup inventory created.'))
122
new_inventories = self.repo._temp_inventories()
124
# we have topological order of revisions and non ghost parents ready.
125
self._setup_steps(len(self._rev_graph))
126
revision_keys = [(rev_id,) for rev_id in topo_sort(self._rev_graph)]
127
stream = self._change_inv_parents(
128
self.inventory.get_record_stream(revision_keys, 'unordered', True),
129
self._new_inv_parents,
131
new_inventories.insert_record_stream(stream)
132
# if this worked, the set of new_inventories.keys should equal
134
if not (set(new_inventories.keys())
135
== {(revid,) for revid in self.pending}):
136
raise AssertionError()
137
self.pb.update(gettext('Writing weave'))
138
self.repo._activate_new_inventory()
139
self.inventory = None
140
ui.ui_factory.note(gettext('Inventory regenerated.'))
142
def _new_inv_parents(self, revision_key):
143
"""Lookup ghost-filtered parents for revision_key."""
144
# Use the filtered ghostless parents list:
145
return tuple([(revid,) for revid in self._rev_graph[revision_key[-1]]])
147
def _change_inv_parents(self, stream, get_parents, all_revision_keys):
148
"""Adapt a record stream to reconcile the parents."""
149
for record in stream:
150
wanted_parents = get_parents(record.key)
151
if wanted_parents and wanted_parents[0] not in all_revision_keys:
152
# The check for the left most parent only handles knit
153
# compressors, but this code only applies to knit and weave
154
# repositories anyway.
155
chunks = record.get_bytes_as('chunked')
156
yield ChunkedContentFactory(record.key, wanted_parents, record.sha1, chunks)
158
adapted_record = AdapterFactory(
159
record.key, wanted_parents, record)
161
self._reweave_step('adding inventories')
163
def _setup_steps(self, new_total):
164
"""Setup the markers we need to control the progress bar."""
165
self.total = new_total
168
def _graph_revision(self, rev_id):
169
"""Load a revision into the revision graph."""
170
# pick a random revision
171
# analyse revision id rev_id and put it in the stack.
172
self._reweave_step('loading revisions')
173
rev = self.repo.get_revision_reconcile(rev_id)
175
for parent in rev.parent_ids:
176
if self._parent_is_available(parent):
177
parents.append(parent)
179
mutter('found ghost %s', parent)
180
self._rev_graph[rev_id] = parents
182
def _check_garbage_inventories(self):
183
"""Check for garbage inventories which we cannot trust
185
We cant trust them because their pre-requisite file data may not
186
be present - all we know is that their revision was not installed.
188
if not self.thorough:
190
inventories = set(self.inventory.keys())
191
revisions = set(self.revisions.keys())
192
garbage = inventories.difference(revisions)
193
self.garbage_inventories = len(garbage)
194
for revision_key in garbage:
195
mutter('Garbage inventory {%s} found.', revision_key[-1])
197
def _parent_is_available(self, parent):
198
"""True if parent is a fully available revision
200
A fully available revision has a inventory and a revision object in the
203
if parent in self._rev_graph:
205
inv_present = (1 == len(self.inventory.get_parent_map([(parent,)])))
206
return (inv_present and self.repo.has_revision(parent))
208
def _reweave_step(self, message):
209
"""Mark a single step of regeneration complete."""
210
self.pb.update(message, self.count, self.total)
214
class KnitReconciler(VersionedFileRepoReconciler):
215
"""Reconciler that reconciles a knit format repository.
217
This will detect garbage inventories and remove them in thorough mode.
220
def _reconcile_steps(self):
221
"""Perform the steps to reconcile this repository."""
225
except errors.BzrCheckError:
228
# knits never suffer this
230
self._fix_text_parents()
232
def _load_indexes(self):
233
"""Load indexes for the reconciliation."""
234
self.transaction = self.repo.get_transaction()
235
self.pb.update(gettext('Reading indexes'), 0, 2)
236
self.inventory = self.repo.inventories
237
self.pb.update(gettext('Reading indexes'), 1, 2)
238
self.repo._check_for_inconsistent_revision_parents()
239
self.revisions = self.repo.revisions
240
self.pb.update(gettext('Reading indexes'), 2, 2)
242
def _gc_inventory(self):
243
"""Remove inventories that are not referenced from the revision store."""
244
self.pb.update(gettext('Checking unused inventories'), 0, 1)
245
self._check_garbage_inventories()
246
self.pb.update(gettext('Checking unused inventories'), 1, 3)
247
if not self.garbage_inventories:
248
ui.ui_factory.note(gettext('Inventory ok.'))
250
self.pb.update(gettext('Backing up inventory'), 0, 0)
251
self.repo._backup_inventory()
252
ui.ui_factory.note(gettext('Backup Inventory created'))
253
# asking for '' should never return a non-empty weave
254
new_inventories = self.repo._temp_inventories()
255
# we have topological order of revisions and non ghost parents ready.
256
graph = self.revisions.get_parent_map(self.revisions.keys())
257
revision_keys = topo_sort(graph)
258
revision_ids = [key[-1] for key in revision_keys]
259
self._setup_steps(len(revision_keys))
260
stream = self._change_inv_parents(
261
self.inventory.get_record_stream(revision_keys, 'unordered', True),
264
new_inventories.insert_record_stream(stream)
265
# if this worked, the set of new_inventory_vf.names should equal
266
# the revisionds list
267
if not(set(new_inventories.keys()) == set(revision_keys)):
268
raise AssertionError()
269
self.pb.update(gettext('Writing weave'))
270
self.repo._activate_new_inventory()
271
self.inventory = None
272
ui.ui_factory.note(gettext('Inventory regenerated.'))
274
def _fix_text_parents(self):
275
"""Fix bad versionedfile parent entries.
277
It is possible for the parents entry in a versionedfile entry to be
278
inconsistent with the values in the revision and inventory.
280
This method finds entries with such inconsistencies, corrects their
281
parent lists, and replaces the versionedfile with a corrected version.
283
transaction = self.repo.get_transaction()
284
versions = [key[-1] for key in self.revisions.keys()]
285
mutter('Prepopulating revision text cache with %d revisions',
287
vf_checker = self.repo._get_versioned_file_checker()
288
bad_parents, unused_versions = vf_checker.check_file_version_parents(
289
self.repo.texts, self.pb)
290
text_index = vf_checker.text_index
291
per_id_bad_parents = {}
292
for key in unused_versions:
293
# Ensure that every file with unused versions gets rewritten.
294
# NB: This is really not needed, reconcile != pack.
295
per_id_bad_parents[key[0]] = {}
296
# Generate per-knit/weave data.
297
for key, details in bad_parents.items():
300
knit_parents = tuple([parent[-1] for parent in details[0]])
301
correct_parents = tuple([parent[-1] for parent in details[1]])
302
file_details = per_id_bad_parents.setdefault(file_id, {})
303
file_details[rev_id] = (knit_parents, correct_parents)
304
file_id_versions = {}
305
for text_key in text_index:
306
versions_list = file_id_versions.setdefault(text_key[0], [])
307
versions_list.append(text_key[1])
308
# Do the reconcile of individual weaves.
309
for num, file_id in enumerate(per_id_bad_parents):
310
self.pb.update(gettext('Fixing text parents'), num,
311
len(per_id_bad_parents))
312
versions_with_bad_parents = per_id_bad_parents[file_id]
313
id_unused_versions = set(key[-1] for key in unused_versions
314
if key[0] == file_id)
315
if file_id in file_id_versions:
316
file_versions = file_id_versions[file_id]
318
# This id was present in the disk store but is not referenced
319
# by any revision at all.
321
self._fix_text_parent(file_id, versions_with_bad_parents,
322
id_unused_versions, file_versions)
324
def _fix_text_parent(self, file_id, versions_with_bad_parents,
325
unused_versions, all_versions):
326
"""Fix bad versionedfile entries in a single versioned file."""
327
mutter('fixing text parent: %r (%d versions)', file_id,
328
len(versions_with_bad_parents))
329
mutter('(%d are unused)', len(unused_versions))
330
new_file_id = b'temp:%s' % file_id
333
for version in all_versions:
334
if version in unused_versions:
336
elif version in versions_with_bad_parents:
337
parents = versions_with_bad_parents[version][1]
339
pmap = self.repo.texts.get_parent_map([(file_id, version)])
340
parents = [key[-1] for key in pmap[(file_id, version)]]
341
new_parents[(new_file_id, version)] = [
342
(new_file_id, parent) for parent in parents]
343
needed_keys.add((file_id, version))
345
def fix_parents(stream):
346
for record in stream:
347
chunks = record.get_bytes_as('chunked')
348
new_key = (new_file_id, record.key[-1])
349
parents = new_parents[new_key]
350
yield ChunkedContentFactory(new_key, parents, record.sha1, chunks)
351
stream = self.repo.texts.get_record_stream(
352
needed_keys, 'topological', True)
353
self.repo._remove_file_id(new_file_id)
354
self.repo.texts.insert_record_stream(fix_parents(stream))
355
self.repo._remove_file_id(file_id)
357
self.repo._move_file_id(new_file_id, file_id)
360
class PackReconciler(VersionedFileRepoReconciler):
361
"""Reconciler that reconciles a pack based repository.
363
Garbage inventories do not affect ancestry queries, and removal is
364
considerably more expensive as there is no separate versioned file for
365
them, so they are not cleaned. In short it is currently a no-op.
367
In future this may be a good place to hook in annotation cache checking,
368
index recreation etc.
371
# XXX: The index corruption that _fix_text_parents performs is needed for
372
# packs, but not yet implemented. The basic approach is to:
373
# - lock the names list
374
# - perform a customised pack() that regenerates data as needed
375
# - unlock the names list
376
# https://bugs.launchpad.net/bzr/+bug/154173
378
def __init__(self, repo, other=None, thorough=False,
379
canonicalize_chks=False):
380
super(PackReconciler, self).__init__(repo, other=other,
382
self.canonicalize_chks = canonicalize_chks
384
def _reconcile_steps(self):
385
"""Perform the steps to reconcile this repository."""
386
if not self.thorough:
388
collection = self.repo._pack_collection
389
collection.ensure_loaded()
390
collection.lock_names()
392
packs = collection.all_packs()
393
all_revisions = self.repo.all_revision_ids()
394
total_inventories = len(list(
395
collection.inventory_index.combined_index.iter_all_entries()))
396
if len(all_revisions):
397
if self.canonicalize_chks:
398
reconcile_meth = self.repo._canonicalize_chks_pack
400
reconcile_meth = self.repo._reconcile_pack
401
new_pack = reconcile_meth(collection, packs, ".reconcile",
402
all_revisions, self.pb)
403
if new_pack is not None:
404
self._discard_and_save(packs)
406
# only make a new pack when there is data to copy.
407
self._discard_and_save(packs)
408
self.garbage_inventories = total_inventories - len(list(
409
collection.inventory_index.combined_index.iter_all_entries()))
411
collection._unlock_names()
413
def _discard_and_save(self, packs):
414
"""Discard some packs from the repository.
416
This removes them from the memory index, saves the in-memory index
417
which makes the newly reconciled pack visible and hides the packs to be
418
discarded, and finally renames the packs being discarded into the
419
obsolete packs directory.
421
:param packs: The packs to discard.
424
self.repo._pack_collection._remove_pack_from_memory(pack)
425
self.repo._pack_collection._save_pack_names()
426
self.repo._pack_collection._obsolete_packs(packs)
429
class BranchReconciler(object):
430
"""Reconciler that works on a branch."""
432
def __init__(self, a_branch, thorough=False):
433
self.fixed_history = None
434
self.thorough = thorough
435
self.branch = a_branch
438
with self.branch.lock_write(), \
439
ui.ui_factory.nested_progress_bar() as self.pb:
440
ret = ReconcileResult()
441
ret.fixed_history = self._reconcile_steps()
444
def _reconcile_steps(self):
445
return self._reconcile_revision_history()
447
def _reconcile_revision_history(self):
448
last_revno, last_revision_id = self.branch.last_revision_info()
450
graph = self.branch.repository.get_graph()
452
for revid in graph.iter_lefthand_ancestry(
453
last_revision_id, (_mod_revision.NULL_REVISION,)):
454
real_history.append(revid)
455
except errors.RevisionNotPresent:
456
pass # Hit a ghost left hand parent
457
real_history.reverse()
458
if last_revno != len(real_history):
459
# Technically for Branch5 formats, it is more efficient to use
460
# set_revision_history, as this will regenerate it again.
461
# Not really worth a whole BranchReconciler class just for this,
463
ui.ui_factory.note(gettext('Fixing last revision info {0} '
465
last_revno, len(real_history)))
466
self.branch.set_last_revision_info(len(real_history),
470
ui.ui_factory.note(gettext('revision_history ok.'))