mirror of
https://github.com/retspen/webvirtcloud
synced 2026-12-03 09:26:03 +00:00
feat(backups): verify a backup's files on demand
The daily target check only finds files that are gone. Verify (a ready backup's Restore menu, superusers) runs backup.verify: it reads the backup's files and those of the backups it builds on whole from the target through a libvirt stream: each there, a disk at its size and in its format on its base's file, the small files with their SHA-256, and a disk with the SHA-256 recorded at its first verification. What is wrong is kept on the backup and shown as Damaged; a target that cannot be read fails the job and leaves the backup as it was. Progress in bytes, cancellable.
This commit is contained in:
parent
eeae606d08
commit
2cf7dbe577
14 changed files with 891 additions and 231 deletions
|
|
@ -18,7 +18,8 @@ from django.utils import timezone
|
|||
from django.utils.dateparse import parse_datetime
|
||||
from django.utils.translation import gettext_noop as _
|
||||
from lxml import etree
|
||||
from libvirt import VIR_DOMAIN_PAUSED, VIR_DOMAIN_RUNNING, VIR_DOMAIN_SHUTOFF, VIR_ERR_NO_DOMAIN, VIR_ERR_NO_STORAGE_VOL, libvirtError
|
||||
from libvirt import (VIR_DOMAIN_PAUSED, VIR_DOMAIN_RUNNING, VIR_DOMAIN_SHUTOFF, VIR_ERR_NO_DOMAIN, VIR_ERR_NO_STORAGE_VOL,
|
||||
VIR_STORAGE_VOL_GET_PHYSICAL, libvirtError)
|
||||
|
||||
from accounts.models import UserAttributes
|
||||
from appsettings.settings import app_settings
|
||||
|
|
@ -31,7 +32,7 @@ from operations.jobs import Cancelled, Kind, Outcome, Plan, register, register_p
|
|||
from operations.models import Claim, Operation
|
||||
from operations.utils import safe_text, say
|
||||
from vrtManager import util
|
||||
from vrtManager.backup import (backup_file_names, backup_prefix, check_restore_host, check_target_space, get_file, manifest_names, put_file,
|
||||
from vrtManager.backup import (backup_file_names, backup_prefix, check_restore_host, check_target_space, get_file, manifest_names, put_file, read_sha256,
|
||||
remove_files, restore_definition, restore_over_definition, target_pool, volume_exists,
|
||||
wvmBackup)
|
||||
from vrtManager.connection import NVRAM_DIR, wvmConnect
|
||||
|
|
@ -199,7 +200,8 @@ def _chain_parent(policy, instance, target, plan, proxy, pool):
|
|||
while backup is not None:
|
||||
chain.append(backup)
|
||||
backup = backup.parent
|
||||
if not chain or len(chain) >= policy.full_every or any(b.state != Backup.READY for b in chain):
|
||||
# a verification found damage: the next one is full
|
||||
if not chain or len(chain) >= policy.full_every or any(b.state != Backup.READY or b.damage for b in chain):
|
||||
return None, None
|
||||
if chain[-1].manifest.get("parent"): # its base's row is gone: the chain cannot be read whole
|
||||
return None, None
|
||||
|
|
@ -696,6 +698,183 @@ class DeleteBackup(Kind):
|
|||
return op.intent["compute"], op.intent["vm"], op.intent["uuid"], message
|
||||
|
||||
|
||||
VERIFY_STEP = 64 << 20 # bytes read between two progress writes and cancel checks
|
||||
MANIFEST_LIMIT = 16 << 20 # a manifest is a few kB
|
||||
|
||||
|
||||
def _chain(backup):
|
||||
"""The backup and those it builds on, itself first; a chain whose base's row is gone is refused."""
|
||||
chain = [backup]
|
||||
while backup.parent_id is not None:
|
||||
backup = backup.parent
|
||||
chain.append(backup)
|
||||
if backup.manifest.get("parent"):
|
||||
raise util.OperationError(_("The backup taken %(time)s builds on a backup that is gone"),
|
||||
time=timezone.localtime(backup.created_at).strftime("%Y-%m-%d %H:%M"))
|
||||
return chain
|
||||
|
||||
|
||||
@register
|
||||
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
|
||||
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."""
|
||||
|
||||
name = "backup.verify"
|
||||
label = _("Verify backup")
|
||||
cancellable = True
|
||||
progress_bytes = True
|
||||
|
||||
def normalize(self, raw):
|
||||
return {"backup": str(UUID(str(raw["backup"])))}
|
||||
|
||||
def plan(self, user, params):
|
||||
_superuser(user)
|
||||
backup = _backup(params)
|
||||
if backup.state != Backup.READY:
|
||||
raise util.OperationError(_("Only a ready backup can be verified"))
|
||||
chain = _chain(backup)
|
||||
keys = {claims.compute_key(compute_id): Claim.SHARED
|
||||
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})
|
||||
return Plan(
|
||||
claims=keys,
|
||||
resource=claims.backup_key(backup.uuid),
|
||||
label=f"{backup.vm_name} {timezone.localtime(backup.created_at):%Y-%m-%d %H:%M}",
|
||||
intent={"compute": backup.compute_name, "vm": backup.vm_name, "uuid": backup.vm_uuid,
|
||||
"time": timezone.localtime(backup.created_at).strftime("%Y-%m-%d %H:%M")},
|
||||
)
|
||||
|
||||
def run(self, op, ctx):
|
||||
_superuser(op.user)
|
||||
backup = _backup(op.params)
|
||||
conn, pool = _target_pool(backup.target)
|
||||
stale = None
|
||||
try:
|
||||
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}
|
||||
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]
|
||||
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)
|
||||
ctx.set_phase(_("Reading the backup's files"))
|
||||
|
||||
def cancelled():
|
||||
op.refresh_from_db(fields=["cancel_requested"])
|
||||
if op.cancel_requested:
|
||||
raise Cancelled
|
||||
|
||||
def on_read(size):
|
||||
read["done"] += size
|
||||
read["step"] += size
|
||||
if read["step"] >= VERIFY_STEP:
|
||||
read["step"] = 0
|
||||
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):
|
||||
damage += self._manifest_damage(conn, pool, b)
|
||||
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
|
||||
if damage:
|
||||
raise util.OperationError(_("The backup is damaged: %(damage)s"), damage=damage)
|
||||
return {}
|
||||
|
||||
@staticmethod
|
||||
def _damage(conn, backup, f, vol, on_read):
|
||||
"""What is wrong with the file f of backup (vol: its volume, None when missing): messages."""
|
||||
if vol is None:
|
||||
return say(_("The backup's file %(name)s is missing from the target"), name=f.volume)
|
||||
if f.role != BackupFile.DISK:
|
||||
# its length first: another file in its place is not read into memory
|
||||
if vol.infoFlags(VIR_STORAGE_VOL_GET_PHYSICAL)[2] != f.capacity:
|
||||
return say(_("The backup's file %(name)s differs from the one written"), name=f.volume)
|
||||
if hashlib.sha256(conn.download_volume(vol)).hexdigest() != f.sha256:
|
||||
return say(_("The backup's file %(name)s differs from the one written"), name=f.volume)
|
||||
return []
|
||||
tree = etree.fromstring(vol.XMLDesc(0))
|
||||
if vol.info()[1] != f.capacity:
|
||||
return say(_("The backup's file %(name)s differs from the one written"), name=f.volume)
|
||||
fmt = tree.find("target/format") # as libvirt reads it from the file's header
|
||||
if f.format and fmt is not None and fmt.get("type") != f.format:
|
||||
return say(_("The backup's file %(name)s is not a %(format)s file"), name=f.volume, format=f.format)
|
||||
base = backup.parent.files.filter(role=BackupFile.DISK, dev=f.dev).first() if backup.parent_id else None
|
||||
# the file beside it in the target, as libvirt resolves the backing file it names; a full backup's none
|
||||
below = os.path.normpath(tree.findtext("backingStore/path") or "")
|
||||
expected = os.path.join(os.path.dirname(vol.path()), base.volume) if base is not None else "."
|
||||
if below != expected:
|
||||
if base is None:
|
||||
return say(_("The backup's file %(name)s builds on another file"), name=f.volume)
|
||||
return say(_("The backup's file %(name)s does not build on %(base)s"), name=f.volume, base=base.volume)
|
||||
sha256 = read_sha256(conn, vol, on_read)
|
||||
# its first verification records it, unless another one did meanwhile: then that one's counts
|
||||
if not BackupFile.objects.filter(pk=f.pk, sha256="").update(sha256=sha256) \
|
||||
and sha256 != BackupFile.objects.get(pk=f.pk).sha256:
|
||||
return say(_("The backup's file %(name)s changed since its first verification"), name=f.volume)
|
||||
return []
|
||||
|
||||
@staticmethod
|
||||
def _manifest_damage(conn, pool, backup):
|
||||
"""What is wrong with the backup's manifest in the target, which an import reads."""
|
||||
name = f"{backup.prefix}-manifest.json"
|
||||
vol = _volume(pool, name)
|
||||
if vol is None:
|
||||
return say(_("The backup's file %(name)s is missing from the target"), name=name)
|
||||
if vol.infoFlags(VIR_STORAGE_VOL_GET_PHYSICAL)[2] > MANIFEST_LIMIT: # another file in its place: not read
|
||||
return say(_("The backup's file %(name)s differs from the one written"), name=name)
|
||||
try:
|
||||
same = json.loads(conn.download_volume(vol)) == backup.manifest
|
||||
except ValueError:
|
||||
same = False
|
||||
return [] if same else say(_("The backup's file %(name)s differs from the one written"), name=name)
|
||||
|
||||
def progress(self, op):
|
||||
return (op.intent["done"], op.intent["total"]) if "total" in op.intent else None
|
||||
|
||||
def cancel(self, op):
|
||||
pass # run stops at its next step
|
||||
|
||||
def reconcile(self, op):
|
||||
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):
|
||||
backup = f"Backup {op.intent['time']} of {op.intent['vm']}"
|
||||
message = f"{backup} verified" if state == Operation.SUCCEEDED else f"{backup}: verify ({state})"
|
||||
return op.intent["compute"], op.intent["vm"], op.intent["uuid"], message
|
||||
|
||||
|
||||
def _volume(pool, name):
|
||||
try:
|
||||
return pool.storageVolLookupByName(name)
|
||||
except libvirtError as err:
|
||||
if err.get_error_code() != VIR_ERR_NO_STORAGE_VOL:
|
||||
raise
|
||||
return None
|
||||
|
||||
|
||||
def _connect(compute):
|
||||
return wvmConnect(compute.hostname, compute.login, compute.password, compute.type)
|
||||
|
||||
|
|
|
|||
23
vmbackups/migrations/0009_backup_verify.py
Normal file
23
vmbackups/migrations/0009_backup_verify.py
Normal file
|
|
@ -0,0 +1,23 @@
|
|||
# Generated by Django 5.2.18 on 2026-11-19 12:21
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('vmbackups', '0008_policy_tag'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AddField(
|
||||
model_name='backup',
|
||||
name='damage',
|
||||
field=models.JSONField(default=list),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='backup',
|
||||
name='verified_at',
|
||||
field=models.DateTimeField(null=True),
|
||||
),
|
||||
]
|
||||
|
|
@ -122,6 +122,10 @@ class Backup(models.Model):
|
|||
# whose job made it: a VM owner's own backups count in their backup quota
|
||||
taken_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, related_name="+")
|
||||
prefix = models.CharField(max_length=128) # every file of the backup in the target begins with it and "-"
|
||||
# its last verification (backup.verify) that read the files: when, and what it found wrong with them or
|
||||
# with those of the backups it builds on (messages, operations.utils.say); empty: nothing
|
||||
verified_at = models.DateTimeField(null=True)
|
||||
damage = models.JSONField(default=list)
|
||||
|
||||
class Meta:
|
||||
ordering = ["-created_at"]
|
||||
|
|
|
|||
|
|
@ -5,7 +5,11 @@
|
|||
<ul class="dropdown-menu dropdown-menu-end shadow">
|
||||
<li><a class="dropdown-item" href="{% url 'vmbackups:restore' backup.uuid %}">{% trans "As a new VM" %}</a></li>
|
||||
{% if backup.instance_id %}<li><a class="dropdown-item" href="{% url 'vmbackups:restore_over' backup.uuid %}">{% trans "Over the VM" %}</a></li>{% endif %}
|
||||
{% if user.is_superuser %}<li><a class="dropdown-item" href="{% url 'vmbackups:restore_disk' backup.uuid %}">{% trans "One disk" %}</a></li>{% endif %}
|
||||
{% if user.is_superuser %}<li><a class="dropdown-item" href="{% url 'vmbackups:restore_disk' backup.uuid %}">{% trans "One disk" %}</a></li>
|
||||
<li><hr class="dropdown-divider"></li>
|
||||
{# reads its files whole: they are there and as written #}
|
||||
<li><form method="post" action="{% url 'vmbackups:verify' backup.uuid %}">{% csrf_token %}{% submission_key %}
|
||||
<button type="submit" class="dropdown-item">{% bs_icon 'check-circle' %} {% trans "Verify" %}</button></form></li>{% endif %}
|
||||
</ul>
|
||||
</div>{% endif %}{% if not backup.being_made %}{% if user.is_superuser or backup.taken_by_id == user.id and not backup.policy_id %}<form method="post" action="{% url 'vmbackups:delete' backup.uuid %}" class="d-inline">{% csrf_token %}{% submission_key %}
|
||||
<button type="submit" class="btn btn-sm btn-outline-danger" aria-label="{% trans "Delete backup" %}" title="{% trans "Delete backup" %}"
|
||||
|
|
|
|||
|
|
@ -1 +1 @@
|
|||
{% load i18n %}{% if backup.uuid|stringformat:"s" in pending_deletes %}<span class="badge text-bg-warning" data-backup-pending>{% trans "Deleting" %}</span>{% elif backup.state == "deleting" %}<span class="badge text-bg-warning" title="{% trans "Its deletion did not end; delete it again" %}">{% trans "Deleting" %}</span>{% elif backup.state == "ready" %}<span class="badge text-bg-success">{% trans "Ready" %}</span>{% elif backup.being_made %}<span class="badge text-bg-info" data-backup-pending>{% trans "Creating" %}</span>{% if backup.operation_id %}{% if user.is_superuser or backup.operation.user_id == user.id %} <a class="small" href="{% url 'operations:job' backup.operation_id %}">{% trans "Progress" %}</a>{% endif %}{% endif %}{% elif backup.state == "missing" %}<span class="badge text-bg-danger" title="{% trans "Files of the backup are missing from the target" %}">{% trans "Missing" %}</span>{% else %}<span class="badge text-bg-danger">{% trans "Failed" %}</span>{% if backup.operation_id %}{% if user.is_superuser or backup.operation.user_id == user.id %} <a class="small" href="{% url 'operations:job' backup.operation_id %}">{% trans "Why?" %}</a>{% endif %}{% endif %}{% endif %}
|
||||
{% load i18n %}{% load operations %}{% if backup.uuid|stringformat:"s" in pending_deletes %}<span class="badge text-bg-warning" data-backup-pending>{% trans "Deleting" %}</span>{% elif backup.state == "deleting" %}<span class="badge text-bg-warning" title="{% trans "Its deletion did not end; delete it again" %}">{% trans "Deleting" %}</span>{% elif backup.state == "ready" and backup.damage %}<span class="badge text-bg-danger" title="{{ backup.damage|words }}">{% trans "Damaged" %}</span>{% elif backup.state == "ready" %}<span class="badge text-bg-success"{% if backup.verified_at %} title="{% blocktrans with time=backup.verified_at|date:"Y-m-d H:i" %}Verified {{ time }}{% endblocktrans %}"{% endif %}>{% trans "Ready" %}</span>{% if backup.verified_at %} <span class="small text-body-secondary">{% trans "verified" %}</span>{% endif %}{% elif backup.being_made %}<span class="badge text-bg-info" data-backup-pending>{% trans "Creating" %}</span>{% if backup.operation_id %}{% if user.is_superuser or backup.operation.user_id == user.id %} <a class="small" href="{% url 'operations:job' backup.operation_id %}">{% trans "Progress" %}</a>{% endif %}{% endif %}{% elif backup.state == "missing" %}<span class="badge text-bg-danger" title="{% trans "Files of the backup are missing from the target" %}">{% trans "Missing" %}</span>{% else %}<span class="badge text-bg-danger">{% trans "Failed" %}</span>{% if backup.operation_id %}{% if user.is_superuser or backup.operation.user_id == user.id %} <a class="small" href="{% url 'operations:job' backup.operation_id %}">{% trans "Why?" %}</a>{% endif %}{% endif %}{% endif %}
|
||||
|
|
|
|||
291
vmbackups/tests/test_verify.py
Normal file
291
vmbackups/tests/test_verify.py
Normal file
|
|
@ -0,0 +1,291 @@
|
|||
"""backup.verify: a backup's files and those of the backups it builds on read
|
||||
whole from the target; what is wrong goes on the backup and fails the job."""
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
from datetime import timedelta
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import MagicMock, patch
|
||||
from uuid import uuid4
|
||||
|
||||
import libvirt
|
||||
from django.contrib.auth import get_user_model
|
||||
from django.core.exceptions import PermissionDenied
|
||||
from django.test import TransactionTestCase
|
||||
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.jobs import Cancelled, Context
|
||||
from operations.models import Operation, acquire
|
||||
from operations.utils import words
|
||||
from vmbackups.jobs import VerifyBackup
|
||||
from vmbackups.models import Backup, BackupFile, BackupTarget, BackupTargetPool
|
||||
from vrtManager.util import OperationError
|
||||
|
||||
WORKER = "wvc-test:1:v"
|
||||
DOMAIN = b"<domain/>"
|
||||
|
||||
|
||||
def missing(name):
|
||||
err = libvirt.libvirtError(f"Storage volume not found: {name}")
|
||||
err.err = (libvirt.VIR_ERR_NO_STORAGE_VOL, 0, str(err), 2, None, None, None, 0, 0)
|
||||
return err
|
||||
|
||||
|
||||
class FakePool:
|
||||
"""The target's volumes: {name: (capacity, format, backing file name, bytes)}."""
|
||||
|
||||
def __init__(self):
|
||||
self.volumes = {}
|
||||
|
||||
def refresh(self, flags):
|
||||
pass
|
||||
|
||||
def storageVolLookupByName(self, name):
|
||||
if name not in self.volumes:
|
||||
raise missing(name)
|
||||
capacity, fmt, backing, data = self.volumes[name]
|
||||
vol = MagicMock()
|
||||
vol.name.return_value = name
|
||||
vol.path.return_value = f"/backups/{name}"
|
||||
vol.info.return_value = [0, capacity, len(data)]
|
||||
vol.infoFlags.return_value = [0, capacity, len(data)] # physical: the file's length
|
||||
below = f"<backingStore><path>/backups/{backing}</path></backingStore>" if backing else ""
|
||||
vol.XMLDesc.return_value = f"<volume><target><format type='{fmt}'/></target>{below}</volume>"
|
||||
vol.data = data
|
||||
return vol
|
||||
|
||||
|
||||
def read_sha256(conn, vol, on_read):
|
||||
on_read(len(vol.data))
|
||||
return hashlib.sha256(vol.data).hexdigest()
|
||||
|
||||
|
||||
class VerifyBackupTests(TransactionTestCase):
|
||||
def setUp(self):
|
||||
get_settings()
|
||||
self.admin = get_user_model().objects.create_superuser("ver_admin", "v@example.com", "pw")
|
||||
compute = Compute.objects.create(name="h1", hostname="192.0.2.41", login="u", password="p", type=1)
|
||||
self.vm = Instance.objects.create(compute=compute, name="vm1", uuid="41414141-0000-4000-8000-000000000001")
|
||||
self.target = BackupTarget.objects.create(name="nfs1")
|
||||
BackupTargetPool.objects.create(target=self.target, compute=compute, pool="b1", pool_uuid="u")
|
||||
self.pool = FakePool()
|
||||
self.full = self.backup()
|
||||
self.incremental = self.backup(parent=self.full)
|
||||
conn = MagicMock()
|
||||
conn.download_volume.side_effect = lambda vol: vol.data
|
||||
for name, value in (("vmbackups.jobs.wvmConnect", MagicMock(return_value=conn)),
|
||||
("vmbackups.jobs.target_pool", MagicMock(return_value=self.pool)),
|
||||
("vmbackups.jobs.read_sha256", read_sha256)):
|
||||
patcher = patch(name, value)
|
||||
patcher.start()
|
||||
self.addCleanup(patcher.stop)
|
||||
|
||||
def backup(self, parent=None):
|
||||
backup = Backup.objects.create(target=self.target, instance=self.vm, vm_uuid=self.vm.uuid, vm_name="vm1",
|
||||
compute_name="h1", state=Backup.READY, parent=parent,
|
||||
manifest={"parent": str(parent.uuid)} if parent else {})
|
||||
disk = f"{backup.prefix}-vda.qcow2"
|
||||
self.pool.volumes[disk] = (1 << 20, "qcow2", f"{parent.prefix}-vda.qcow2" if parent else None, b"disk " + disk.encode())
|
||||
BackupFile.objects.create(backup=backup, role=BackupFile.DISK, dev="vda", volume=disk, format="qcow2", capacity=1 << 20)
|
||||
domain = f"{backup.prefix}-domain.xml"
|
||||
self.pool.volumes[domain] = (len(DOMAIN), "raw", None, DOMAIN)
|
||||
BackupFile.objects.create(backup=backup, role=BackupFile.DOMAIN, volume=domain, capacity=len(DOMAIN),
|
||||
sha256=hashlib.sha256(DOMAIN).hexdigest())
|
||||
manifest = json.dumps(backup.manifest).encode()
|
||||
self.pool.volumes[f"{backup.prefix}-manifest.json"] = (len(manifest), "raw", None, manifest)
|
||||
return backup
|
||||
|
||||
def verify(self, backup=None):
|
||||
backup = backup or self.incremental
|
||||
op = jobs.submit("backup.verify", self.admin, {"backup": str(backup.uuid)}, f"key-{uuid4().hex[:12]}")
|
||||
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)))
|
||||
|
||||
def damage(self):
|
||||
with self.assertRaises(OperationError) as raised:
|
||||
self.verify()
|
||||
self.incremental.refresh_from_db()
|
||||
self.assertTrue(self.incremental.verified_at)
|
||||
return str(raised.exception), self.incremental.damage
|
||||
|
||||
def test_a_sound_chain_is_verified_and_its_disks_hashes_are_recorded(self):
|
||||
self.verify()
|
||||
self.incremental.refresh_from_db()
|
||||
self.assertTrue(self.incremental.verified_at)
|
||||
self.assertEqual(self.incremental.damage, [])
|
||||
for backup in (self.full, self.incremental):
|
||||
disk = backup.files.get(role=BackupFile.DISK)
|
||||
self.assertEqual(disk.sha256, hashlib.sha256(self.pool.volumes[disk.volume][3]).hexdigest())
|
||||
|
||||
def test_a_disk_changed_since_its_first_verification(self):
|
||||
self.verify()
|
||||
name = f"{self.full.prefix}-vda.qcow2"
|
||||
self.pool.volumes[name] = (*self.pool.volumes[name][:3], b"bit rot")
|
||||
text, damage = self.damage()
|
||||
self.assertIn(f"The backup's file {name} changed since its first verification", text)
|
||||
self.assertEqual(len(damage), 1)
|
||||
# verified again once it is sound: the damage goes
|
||||
self.pool.volumes[name] = (*self.pool.volumes[name][:3], b"disk " + name.encode())
|
||||
self.verify()
|
||||
self.incremental.refresh_from_db()
|
||||
self.assertEqual(self.incremental.damage, [])
|
||||
|
||||
def test_a_file_missing_from_the_base(self):
|
||||
name = f"{self.full.prefix}-vda.qcow2"
|
||||
del self.pool.volumes[name]
|
||||
text, _damage = self.damage()
|
||||
self.assertIn(f"The backup's file {name} is missing from the target", text)
|
||||
|
||||
def test_an_incremental_disk_on_another_file(self):
|
||||
name = f"{self.incremental.prefix}-vda.qcow2"
|
||||
self.pool.volumes[name] = (1 << 20, "qcow2", "other.qcow2", b"x")
|
||||
text, _damage = self.damage()
|
||||
self.assertIn(f"The backup's file {name} does not build on {self.full.prefix}-vda.qcow2", text)
|
||||
|
||||
def test_a_disk_of_another_size_or_format(self):
|
||||
name = f"{self.incremental.prefix}-vda.qcow2"
|
||||
backing = f"{self.full.prefix}-vda.qcow2"
|
||||
self.pool.volumes[name] = (1 << 20, "raw", backing, b"x")
|
||||
self.assertIn(f"The backup's file {name} is not a qcow2 file", self.damage()[0])
|
||||
self.pool.volumes[name] = (2 << 20, "qcow2", backing, b"x")
|
||||
self.assertIn(f"The backup's file {name} differs from the one written", self.damage()[0])
|
||||
|
||||
def test_an_incremental_disk_on_a_file_of_another_directory(self):
|
||||
name = f"{self.incremental.prefix}-vda.qcow2"
|
||||
self.pool.volumes[name] = (1 << 20, "qcow2", f"../elsewhere/{self.full.prefix}-vda.qcow2", b"x")
|
||||
self.assertIn(f"The backup's file {name} does not build on", self.damage()[0])
|
||||
|
||||
def test_a_full_backup_s_disk_on_a_backing_file(self):
|
||||
name = f"{self.full.prefix}-vda.qcow2"
|
||||
self.pool.volumes[name] = (1 << 20, "qcow2", "unrelated.qcow2", b"x")
|
||||
self.assertIn(f"The backup's file {name} builds on another file", self.damage()[0])
|
||||
|
||||
def test_a_pool_refresh_refused_meanwhile_does_not_stop_it_nor_tell_a_file_missing(self):
|
||||
busy = libvirt.libvirtError("pool has asynchronous jobs running")
|
||||
with patch.object(FakePool, "refresh", side_effect=busy):
|
||||
self.verify()
|
||||
self.incremental.refresh_from_db()
|
||||
self.assertEqual(self.incremental.damage, [])
|
||||
# a file the list does not have yet: perhaps written through another compute
|
||||
del self.pool.volumes[f"{self.full.prefix}-vda.qcow2"]
|
||||
with self.assertRaises(libvirt.libvirtError):
|
||||
self.verify()
|
||||
self.incremental.refresh_from_db()
|
||||
self.assertEqual(self.incremental.damage, [])
|
||||
|
||||
def test_recovery_of_a_verification_that_found_damage_adds_nothing_to_it(self):
|
||||
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))
|
||||
Backup.objects.filter(pk=self.incremental.pk).update(damage=[])
|
||||
self.assertEqual(VerifyBackup().reconcile(op).state, Operation.SUCCEEDED)
|
||||
# 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)
|
||||
|
||||
def test_a_small_file_of_another_length_is_not_read(self):
|
||||
name = f"{self.full.prefix}-domain.xml"
|
||||
self.pool.volumes[name] = (len(DOMAIN), "raw", None, b"x" * 100)
|
||||
conn_reads = []
|
||||
with patch("vmbackups.jobs.wvmConnect") as connect:
|
||||
connect.return_value.download_volume.side_effect = lambda vol: conn_reads.append(vol.name()) or vol.data
|
||||
self.assertIn(f"The backup's file {name} differs from the one written", self.damage()[0])
|
||||
self.assertNotIn(name, conn_reads)
|
||||
|
||||
def test_a_manifest_missing_or_changed(self):
|
||||
name = f"{self.full.prefix}-manifest.json"
|
||||
self.pool.volumes[name] = (8, "raw", None, b"{\"x\": 1}")
|
||||
self.assertIn(f"The backup's file {name} differs from the one written", self.damage()[0])
|
||||
del self.pool.volumes[name]
|
||||
self.assertIn(f"The backup's file {name} is missing from the target", self.damage()[0])
|
||||
|
||||
def test_another_verification_s_first_hash_counts(self):
|
||||
disk = self.full.files.get(role=BackupFile.DISK)
|
||||
|
||||
def other_first(conn, vol, on_read):
|
||||
BackupFile.objects.filter(pk=disk.pk).update(sha256="0" * 64) # recorded meanwhile, of another read
|
||||
return read_sha256(conn, vol, on_read)
|
||||
|
||||
with patch("vmbackups.jobs.read_sha256", other_first):
|
||||
text, _damage = self.damage()
|
||||
self.assertIn(f"The backup's file {disk.volume} changed since its first verification", text)
|
||||
disk.refresh_from_db()
|
||||
self.assertEqual(disk.sha256, "0" * 64)
|
||||
|
||||
def test_a_small_file_that_differs(self):
|
||||
name = f"{self.full.prefix}-domain.xml"
|
||||
self.pool.volumes[name] = (9, "raw", None, b"<changed/>")
|
||||
self.assertIn(f"The backup's file {name} differs from the one written", self.damage()[0])
|
||||
|
||||
def test_a_target_that_cannot_be_read_leaves_the_backup_as_it_was(self):
|
||||
with patch("vmbackups.jobs.read_sha256", side_effect=libvirt.libvirtError("stream broke")):
|
||||
with self.assertRaises(libvirt.libvirtError):
|
||||
self.verify()
|
||||
self.incremental.refresh_from_db()
|
||||
self.assertIsNone(self.incremental.verified_at)
|
||||
|
||||
def test_a_cancel_stops_the_read_also_of_a_small_backup_and_after_a_crash(self):
|
||||
def cancel_then_read(conn, vol, on_read):
|
||||
Operation.objects.filter(kind="backup.verify").update(cancel_requested=True)
|
||||
return read_sha256(conn, vol, on_read)
|
||||
|
||||
for step in (1, 64 << 20): # within a file, or between files
|
||||
with self.subTest(step=step), patch("vmbackups.jobs.VERIFY_STEP", step), \
|
||||
patch("vmbackups.jobs.read_sha256", cancel_then_read), self.assertRaises(Cancelled):
|
||||
self.verify()
|
||||
self.incremental.refresh_from_db()
|
||||
self.assertIsNone(self.incremental.verified_at)
|
||||
op = Operation.objects.filter(kind="backup.verify").first()
|
||||
self.assertEqual(VerifyBackup().reconcile(op).state, Operation.CANCELLED)
|
||||
|
||||
def test_a_superuser_demoted_while_it_waited(self):
|
||||
op = jobs.submit("backup.verify", self.admin, {"backup": str(self.full.uuid)}, "key-verify0009")
|
||||
get_user_model().objects.filter(pk=self.admin.pk).update(is_superuser=False)
|
||||
op.refresh_from_db()
|
||||
with self.assertRaises(PermissionDenied):
|
||||
VerifyBackup().run(op, Context(op, SimpleNamespace(identity=WORKER)))
|
||||
|
||||
def test_a_damaged_backup_is_no_base_of_the_next_scheduled_one(self):
|
||||
from vmbackups.jobs import _chain_parent
|
||||
from vmbackups.models import BackupPolicy
|
||||
policy = BackupPolicy.objects.create(name="n", target=self.target, time="02:00", keep=5, full_every=7, owner=self.admin)
|
||||
Backup.objects.filter(pk__in=[self.full.pk, self.incremental.pk]).update(policy=policy, checkpoint="c")
|
||||
Backup.objects.filter(pk=self.incremental.pk).update(created_at=self.full.created_at + timedelta(minutes=1))
|
||||
plan = {"disks": [{"dev": "vda"}]}
|
||||
proxy = MagicMock()
|
||||
proxy.checkpoint_sizes.return_value = {"vda": 1}
|
||||
pool = MagicMock()
|
||||
pool.listVolumes.return_value = list(self.pool.volumes)
|
||||
self.assertEqual(_chain_parent(policy, self.vm, self.target, plan, proxy, pool)[0], self.incremental)
|
||||
Backup.objects.filter(pk=self.full.pk).update(damage=[{"text": "x", "values": {}}])
|
||||
self.assertEqual(_chain_parent(policy, self.vm, self.target, plan, proxy, pool), (None, None))
|
||||
|
||||
def test_only_a_superuser_verifies_and_only_a_ready_backup(self):
|
||||
owner = get_user_model().objects.create_user("ver_owner", password="pw")
|
||||
with self.assertRaises(PermissionDenied):
|
||||
jobs.submit("backup.verify", owner, {"backup": str(self.full.uuid)}, "key-verify0001")
|
||||
Backup.objects.filter(pk=self.full.pk).update(state=Backup.MISSING)
|
||||
with self.assertRaisesRegex(OperationError, "Only a ready backup can be verified"):
|
||||
jobs.submit("backup.verify", self.admin, {"backup": str(self.full.uuid)}, "key-verify0002")
|
||||
|
||||
def test_the_page_offers_it_and_shows_what_was_found(self):
|
||||
self.client.force_login(self.admin)
|
||||
page = self.client.get(reverse("vmbackups:index"))
|
||||
self.assertContains(page, reverse("vmbackups:verify", args=[self.full.uuid]))
|
||||
response = self.client.post(reverse("vmbackups:verify", args=[self.full.uuid]), {"submission_key": "key-verify0003"})
|
||||
op = Operation.objects.get(kind="backup.verify")
|
||||
self.assertRedirects(response, reverse("operations:job", args=[op.pk]), fetch_redirect_response=False)
|
||||
Backup.objects.filter(pk=self.full.pk).update(
|
||||
damage=[{"text": "The backup's file %(name)s is missing from the target", "values": {"name": "f"}}])
|
||||
page = self.client.get(reverse("vmbackups:index"))
|
||||
self.assertContains(page, "Damaged")
|
||||
self.assertContains(page, "The backup's file f is missing from the target")
|
||||
|
|
@ -7,6 +7,7 @@ app_name = "vmbackups"
|
|||
urlpatterns = [
|
||||
path("", views.index, name="index"),
|
||||
path("<uuid:uuid>/delete/", views.delete, name="delete"),
|
||||
path("<uuid:uuid>/verify/", views.verify, name="verify"),
|
||||
path("<uuid:uuid>/restore/", views.restore, name="restore"),
|
||||
path("<uuid:uuid>/restore-over/", views.restore_over, name="restore_over"),
|
||||
path("<uuid:uuid>/restore-disk/", views.restore_disk, name="restore_disk"),
|
||||
|
|
|
|||
|
|
@ -231,6 +231,22 @@ def delete(request, uuid):
|
|||
return redirect(same_origin_referer(request, reverse("vmbackups:index")))
|
||||
|
||||
|
||||
@require_POST
|
||||
@superuser_only
|
||||
def verify(request, uuid):
|
||||
"""Verify a backup: a backup.verify job, followed on its page."""
|
||||
backup = get_object_or_404(Backup, uuid=uuid)
|
||||
try:
|
||||
op = jobs.submit("backup.verify", request.user, {"backup": str(backup.uuid)}, request.POST.get("submission_key", ""))
|
||||
except claims.Busy as busy:
|
||||
messages.error(request, busy_message(busy, request.user))
|
||||
except (jobs.SubmissionConflict, libvirtError) as err:
|
||||
messages.error(request, error_text(request, err))
|
||||
else:
|
||||
return redirect("operations:job", op.pk)
|
||||
return redirect(same_origin_referer(request, reverse("vmbackups:index")))
|
||||
|
||||
|
||||
@login_required
|
||||
def restore(request, uuid):
|
||||
"""Restore a ready backup as a new VM: a backup.restore job, followed on
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue