diff --git a/operations/claims.py b/operations/claims.py index ebedd279..31820579 100644 --- a/operations/claims.py +++ b/operations/claims.py @@ -88,6 +88,11 @@ def backup_key(uuid): return f"backup:{uuid}" +def verify_key(uuid): + """A backup being verified: one verification at a time writes what it found on it.""" + return f"verify:{uuid}" + + @cache def _node(): """The installation's id (worker.host_identity): the same after a container diff --git a/operations/tests/test_recovery.py b/operations/tests/test_recovery.py index d116f506..2fa4325c 100644 --- a/operations/tests/test_recovery.py +++ b/operations/tests/test_recovery.py @@ -149,6 +149,13 @@ class RecoveryTestCase(TransactionTestCase): self.run_due() self.assertEqual(words(self.reload(op).error), "resource busy: X") + def test_a_finding_that_repeats_the_raised_error_is_stored_once(self): + op = self.orphan({}, worker=self.worker.identity) + self.scheduler.inspect_now(op.pk, error=say("damaged: X")) + with patch.object(fakes.ScriptedKind, "reconcile", return_value=Outcome(Operation.FAILED, error=say("damaged: X"))): + self.run_due() + self.assertEqual(words(self.reload(op).error), "damaged: X") + def test_progress_resets_the_stall_timer(self): op = self.orphan({}) self.run_at(1000, Outcome(Operation.RUNNING, stalled=True)) diff --git a/operations/worker.py b/operations/worker.py index 38d4f313..5abf79d2 100644 --- a/operations/worker.py +++ b/operations/worker.py @@ -478,8 +478,10 @@ class Scheduler: self._done(op.pk) def _error(self, op_id, finding): - """What an unproven end stores: the error the job raised, then what libvirt shows.""" - return [*self.errors.get(op_id, ()), *finding] + """What an unproven end stores: the error the job raised, then what libvirt shows (a message the + raised error has already, once).""" + raised = list(self.errors.get(op_id, ())) + return [*raised, *(message for message in finding if message not in raised)] def _phase(self, op_id, text, progress=None): fields = {"phase": utils.safe_text(text)[:255]} if text else {} diff --git a/vmbackups/jobs.py b/vmbackups/jobs.py index 7f45e3fe..b301bf44 100644 --- a/vmbackups/jobs.py +++ b/vmbackups/jobs.py @@ -719,8 +719,9 @@ class VerifyBackup(Kind): """A ready backup's files read whole from its target, with those of the backups it builds on: each there, a disk at its size, in its format and on the file it builds on, every file with the SHA-256 it had when written or, - for a disk, at its first verification (recorded then). What is wrong goes - on the backup (Backup.damage) and fails the job; a target that cannot be + for a disk, at its first verification (recorded then). Each backup of the + chain is verified with it: what is wrong goes on the backups it reaches + (Backup.damage) and fails the job; a target that cannot be read fails it and leaves the backup as it was. A cancel is seen between two reads of VERIFY_STEP bytes: a read the target holds up waits for it, as any libvirt call.""" @@ -743,6 +744,8 @@ class VerifyBackup(Kind): for compute_id in backup.target.pools.values_list("compute_id", flat=True)} # not deleted while read; backups go on being made into the target meanwhile keys.update({claims.backup_key(b.uuid): Claim.SHARED for b in chain}) + # another verification of a backup of the chain would write over what this one found, or the reverse + keys.update({claims.verify_key(b.uuid): Claim.EXCLUSIVE for b in chain}) return Plan( claims=keys, resource=claims.backup_key(backup.uuid), @@ -760,11 +763,13 @@ class VerifyBackup(Kind): pool.refresh(0) # another compute may have written the files except libvirtError as err: # refused while a volume is copied into the pool here: its list as it is stale = err - files = [(b, f) for b in _chain(backup) for f in b.files.order_by("role", "dev")] - volumes = {f.volume: _volume(pool, f.volume) for _b, f in files} + chain = _chain(backup)[::-1] # its base first + files = {b.pk: list(b.files.order_by("role", "dev")) for b in chain} + volumes = {f.volume: _volume(pool, f.volume) for fs in files.values() for f in fs} if stale is not None and None in volumes.values(): raise stale # a file another compute wrote may be missing from the list only: no damage told - disks = [volumes[f.volume] for _b, f in files if f.role == BackupFile.DISK and volumes[f.volume] is not None] + disks = [volumes[f.volume] for fs in files.values() for f in fs + if f.role == BackupFile.DISK and volumes[f.volume] is not None] total = sum(vol.infoFlags(VIR_STORAGE_VOL_GET_PHYSICAL)[2] for vol in disks) read = {"done": 0, "step": 0} ctx.record_intent(done=0, total=total) @@ -783,15 +788,20 @@ class VerifyBackup(Kind): ctx.record_intent(done=read["done"]) cancelled() - damage = [] - for b, f in files: - cancelled() - damage += self._damage(conn, b, f, volumes[f.volume], on_read) - for b in _chain(backup): + # each backup of the chain read whole: its damage is that of its files and of those it builds on + damage, found = [], {} + for b in chain: + for f in files[b.pk]: + cancelled() + damage += self._damage(conn, b, f, volumes[f.volume], on_read) damage += self._manifest_damage(conn, pool, b) + found[b.pk] = list(damage) cancelled() - Backup.objects.filter(pk=backup.pk).update(verified_at=timezone.now(), damage=damage) - ctx.record_intent(recorded=True) # its own result: recovery tells it from another verification's + now = timezone.now() + with transaction.atomic(): # the rows and its own result together: recovery reads that + for b in reversed(chain): # newest first, as a target check updates them: no deadlock between the two + Backup.objects.filter(pk=b.pk).update(verified_at=now, damage=found[b.pk]) + ctx.record_intent(recorded=True, damage=damage) if damage: raise util.OperationError(_("The backup is damaged: %(damage)s"), damage=damage) return {} @@ -851,13 +861,15 @@ class VerifyBackup(Kind): pass # run stops at its next step def reconcile(self, op): + if op.intent.get("recorded"): # it ended, a cancel asked meanwhile too late: what it found + # a run of the previous version recorded only that it ended: the backup's row tells + damage = op.intent["damage"] if "damage" in op.intent else \ + Backup.objects.filter(uuid=op.params["backup"]).values_list("damage", flat=True).first() + if damage: + return Outcome(Operation.FAILED, error=say(_("The backup is damaged: %(damage)s"), damage=damage)) + return Outcome(Operation.SUCCEEDED) if op.cancel_requested: return Outcome(Operation.CANCELLED) - backup = Backup.objects.filter(uuid=op.params["backup"]).first() - if backup is not None and op.intent.get("recorded"): # it ended: what it found - if backup.damage: - return Outcome(Operation.FAILED, error=say(_("The backup is damaged: %(damage)s"), damage=backup.damage)) - return Outcome(Operation.SUCCEEDED) return Outcome(Operation.FAILED, error=say(_("The verification stopped before it ended; verify the backup again"))) def log_entry(self, op, state): diff --git a/vmbackups/tests/test_verify.py b/vmbackups/tests/test_verify.py index 4519967a..b4215562 100644 --- a/vmbackups/tests/test_verify.py +++ b/vmbackups/tests/test_verify.py @@ -17,9 +17,9 @@ from django.urls import reverse from appsettings.settings import get_settings from computes.models import Compute from instances.models import Instance -from operations import jobs +from operations import claims, jobs from operations.jobs import Cancelled, Context -from operations.models import Operation, acquire +from operations.models import Claim, Operation, acquire from operations.utils import words from vmbackups.jobs import VerifyBackup from vmbackups.models import Backup, BackupFile, BackupTarget, BackupTargetPool @@ -105,7 +105,10 @@ class VerifyBackupTests(TransactionTestCase): acquire(WORKER, "wvc-test") Operation.objects.filter(pk=op.pk).update(state=Operation.RUNNING, worker=WORKER) op.refresh_from_db() - return VerifyBackup().run(op, Context(op, SimpleNamespace(identity=WORKER))) + try: + return VerifyBackup().run(op, Context(op, SimpleNamespace(identity=WORKER))) + finally: # ended as far as the next verification's claims go + Claim.objects.filter(operation=op).delete() def damage(self): with self.assertRaises(OperationError) as raised: @@ -136,6 +139,23 @@ class VerifyBackupTests(TransactionTestCase): self.incremental.refresh_from_db() self.assertEqual(self.incremental.damage, []) + def test_damage_found_in_the_base_goes_on_the_base_too(self): + name = f"{self.full.prefix}-vda.qcow2" + del self.pool.volumes[name] + self.damage() + self.full.refresh_from_db() + self.assertTrue(self.full.verified_at) + self.assertIn(f"The backup's file {name} is missing from the target", words(self.full.damage)) + # restoring the base alone warns too + self.assertEqual(self.full.damaged_in_chain(), self.full) + + def test_damage_of_an_incremental_leaves_its_sound_base_verified_and_sound(self): + del self.pool.volumes[f"{self.incremental.prefix}-vda.qcow2"] + self.damage() + self.full.refresh_from_db() + self.assertTrue(self.full.verified_at) + self.assertEqual(self.full.damage, []) + def test_a_file_missing_from_the_base(self): name = f"{self.full.prefix}-vda.qcow2" del self.pool.volumes[name] @@ -179,15 +199,33 @@ class VerifyBackupTests(TransactionTestCase): self.incremental.refresh_from_db() self.assertEqual(self.incremental.damage, []) + def test_a_verification_of_a_backup_of_the_chain_waits_for_the_one_running(self): + jobs.submit("backup.verify", self.admin, {"backup": str(self.incremental.uuid)}, "key-verify0020") + with self.assertRaises(claims.Busy): + jobs.submit("backup.verify", self.admin, {"backup": str(self.full.uuid)}, "key-verify0021") + def test_recovery_of_a_verification_that_found_damage_adds_nothing_to_it(self): + self.sound_disk = self.pool.volumes[f"{self.full.prefix}-vda.qcow2"] del self.pool.volumes[f"{self.full.prefix}-vda.qcow2"] self.damage() op = Operation.objects.get(kind="backup.verify") outcome = VerifyBackup().reconcile(op) self.assertEqual(outcome.state, Operation.FAILED) self.assertIn("is missing from the target", words(outcome.error)) + # its own result: not what another verification wrote on the backup since, nor a cancel asked too late Backup.objects.filter(pk=self.incremental.pk).update(damage=[]) - self.assertEqual(VerifyBackup().reconcile(op).state, Operation.SUCCEEDED) + Operation.objects.filter(pk=op.pk).update(cancel_requested=True) + op.refresh_from_db() + self.assertEqual(VerifyBackup().reconcile(op).state, Operation.FAILED) + self.pool.volumes[f"{self.full.prefix}-vda.qcow2"] = self.sound_disk + self.verify(self.full) + self.assertEqual(VerifyBackup().reconcile(Operation.objects.exclude(pk=op.pk).latest("created_at")).state, + Operation.SUCCEEDED) + # recorded by the previous version, without its damage: the backup's row tells + Operation.objects.filter(pk=op.pk).update(intent={"recorded": True}) + Backup.objects.filter(pk=self.incremental.pk).update(damage=[{"text": "x", "values": {}}]) + op.refresh_from_db() + self.assertEqual(VerifyBackup().reconcile(op).state, Operation.FAILED) # another verification of the backup that ended: not this one's result other = jobs.submit("backup.verify", self.admin, {"backup": str(self.incremental.uuid)}, "key-verify0010") self.assertEqual(VerifyBackup().reconcile(other).state, Operation.FAILED)