1
0
Fork 0
mirror of https://github.com/retspen/webvirtcloud synced 2026-12-02 17:06:09 +00:00

feat(vmbackups): incremental scheduled backups of running VMs

A schedule with 'a full backup every N backups' above one makes a
checkpoint with each running VM's backup. The next builds on the
schedule's newest ready backup: the changed blocks are pushed into qcow2
volumes made with the base's file as backing file, by its name, as the
target pool's directory differs per host. The base is used only when its
chain is shorter than N, its disks are the VM's, every file of the chain
is in the target, and its checkpoint has a sized bitmap for every disk;
otherwise the backup is full and starts a chain.

Before each scheduled backup of a running VM, the VM's backup
checkpoints are pruned to each schedule's newest base. A checkpoint
libvirt no longer lists, as after a migration, is redefined first so
that its bitmap goes too.

A shut-off VM's backup checkpoints are forgotten before its external
snapshot: libvirt 11.10 makes no offline external snapshot while a
checkpoint exists. The next scheduled backup is then full.
This commit is contained in:
catborise 2026-11-17 17:00:01 +03:00
parent 5f7555f348
commit 72e270a87e
9 changed files with 479 additions and 15 deletions

View file

@ -126,6 +126,44 @@ def _nvram(op, proxy):
raise util.OperationError(_("The VM's NVRAM file changed while it was backed up; back the VM up again"))
def _chain_parent(policy, instance, target, plan, proxy, pool):
"""The backup a scheduled backup of the VM builds on, or None for a full
one: the schedule's newest ready backup with a checkpoint, in a chain
shorter than full_every, of the same disks, every file of its chain in
the target, and its checkpoint's bitmaps whole on the VM."""
last = (Backup.objects.filter(instance=instance, policy=policy, target=target, state=Backup.READY)
.exclude(checkpoint="").order_by("-created_at").first())
chain, backup = [], last
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):
return None
if chain[-1].manifest.get("parent"): # its base's row is gone: the chain cannot be read whole
return None
devs = sorted(d["dev"] for d in plan["disks"])
if sorted(last.files.filter(role=BackupFile.DISK).values_list("dev", flat=True)) != devs:
return None
pool.refresh(0)
files = set(BackupFile.objects.filter(backup__in=chain, role=BackupFile.DISK).values_list("volume", flat=True))
if not files <= set(pool.listVolumes()):
return None
return last if proxy.checkpoint_usable(last.checkpoint, devs) else None
def _prune_checkpoints(op, proxy, plan):
"""The VM's backup checkpoints deleted but each schedule's newest ready
one, the base of its next incremental backup."""
backups = Backup.objects.filter(vm_uuid=op.intent["uuid"]).exclude(checkpoint="").exclude(uuid=op.intent["backup"])
keep = set()
for policy_id in backups.filter(policy__full_every__gt=1).values_list("policy", flat=True).distinct():
newest = backups.filter(policy=policy_id, state=Backup.READY).order_by("-created_at").first()
if newest is not None:
keep.add(newest.checkpoint)
known = {b.checkpoint: int(b.created_at.timestamp()) for b in backups}
proxy.prune_checkpoints(keep=keep, known=known, devs=[d["dev"] for d in plan["disks"]])
def _publish(op, proxy, pool):
"""The copied disks are complete: the NVRAM file, the definition and the
manifest written and read back, then the row ready with its files.
@ -159,6 +197,8 @@ def _publish(op, proxy, pool):
"created_at": backup.created_at.isoformat(),
"consistency": op.intent["consistency"],
"nvram": "copied" if nvram is not None else ("never written" if plan["nvram"] else "none"),
"parent": str(backup.parent.uuid) if backup.parent else None,
"checkpoint": backup.checkpoint,
"tpm": "copied" if tpm else ("never written" if tpm == {} else "none"),
"files": files,
"left_out": plan["left_out"],
@ -235,12 +275,19 @@ class CreateBackup(Kind):
status = proxy.get_status()
live = status != VIR_DOMAIN_SHUTOFF
names = backup_file_names(op.intent["backup"], plan["disks"], bool(plan["nvram"]))
ctx.record_intent(live=live, plan=plan, names=names, pool=row.pool, pool_uuid=row.pool_uuid,
consistency=Backup.OFFLINE if not live else Backup.CRASH)
# a schedule deleted since the job was queued: the backup is kept, without it
policy = BackupPolicy.objects.filter(pk=op.params.get("policy")).first() if op.params.get("policy") else None
# a running VM's scheduled backup makes a checkpoint the next one builds on (bitmaps need qcow2 disks)
checkpoint = (f"wvc-{op.intent['backup']}" if live and policy and policy.full_every > 1
and all(d["format"] == "qcow2" for d in plan["disks"]) else "")
parent = _chain_parent(policy, instance, target, plan, proxy, pool) if checkpoint else None
backing = {f.dev: f.volume for f in parent.files.filter(role=BackupFile.DISK)} if parent else {}
ctx.record_intent(live=live, plan=plan, names=names, pool=row.pool, pool_uuid=row.pool_uuid,
consistency=Backup.OFFLINE if not live else Backup.CRASH, checkpoint=checkpoint,
parent=parent.checkpoint if parent else None, backing=backing)
Backup.objects.create(uuid=op.intent["backup"], target=target, instance=instance, vm_uuid=instance.uuid,
vm_name=instance.name, compute_name=instance.compute.name, operation=op, policy=policy)
vm_name=instance.name, compute_name=instance.compute.name, operation=op, policy=policy,
parent=parent, checkpoint=checkpoint)
ctx.set_phase(_("Copying disks"))
if live:
return self._run_live(op, ctx, proxy, pool, status)
@ -265,8 +312,11 @@ class CreateBackup(Kind):
if plan["nvram"]:
data = proxy.read_nvram(plan["nvram"])
ctx.record_intent(nvram_before=hashlib.sha256(data).hexdigest() if data is not None else None)
if op.params.get("policy"): # before the backup begins: a stopped worker leaves nothing undone
_prune_checkpoints(op, proxy, plan)
ctx.record_intent(made=True)
targets = proxy.make_live_targets(plan["disks"], op.intent["pool"], names["disks"], *_owner())
targets = proxy.make_live_targets(plan["disks"], op.intent["pool"], names["disks"], *_owner(),
backing=op.intent["backing"])
ctx.record_intent(paths=[t["path"] for t in targets])
# a completed result libvirt still holds is of an earlier job
proxy.discard_backup_result()
@ -292,7 +342,8 @@ class CreateBackup(Kind):
# frozen some file systems: frozen stays recorded, so the guest is thawed as frozen
else:
ctx.record_intent(consistency=Backup.FROZEN)
proxy.begin_clone_backup(targets)
proxy.begin_clone_backup(targets, incremental=op.intent["parent"],
checkpoint=op.intent["checkpoint"] or None)
finally:
if op.intent.get("frozen"):
thaw_error = self._thaw(op, ctx, proxy)

View file

@ -0,0 +1,29 @@
# Generated by Django 5.2.18 on 2026-11-17 13:56
import django.db.models.deletion
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('vmbackups', '0003_tpm_files'),
]
operations = [
migrations.AddField(
model_name='backup',
name='checkpoint',
field=models.CharField(blank=True, max_length=64),
),
migrations.AddField(
model_name='backup',
name='parent',
field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='children', to='vmbackups.backup'),
),
migrations.AddField(
model_name='backuppolicy',
name='full_every',
field=models.PositiveSmallIntegerField(default=1),
),
]

View file

@ -47,6 +47,7 @@ class BackupPolicy(models.Model):
instances = models.ManyToManyField(Instance, blank=True, related_name="backup_policies")
time = models.TimeField() # in the panel's time zone
keep = models.PositiveSmallIntegerField()
full_every = models.PositiveSmallIntegerField(default=1) # a full backup every N; the others incremental
frozen = models.BooleanField(default=False)
enabled = models.BooleanField(default=True)
owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True)
@ -104,6 +105,9 @@ class Backup(models.Model):
manifest = models.JSONField(default=dict)
operation = models.ForeignKey(Operation, on_delete=models.SET_NULL, null=True)
policy = models.ForeignKey(BackupPolicy, on_delete=models.SET_NULL, null=True, related_name="backups")
# an incremental backup's base; its disk files have the parent's as backing files
parent = models.ForeignKey("self", on_delete=models.SET_NULL, null=True, related_name="children")
checkpoint = models.CharField(max_length=64, blank=True) # the VM's checkpoint made with it
class Meta:
ordering = ["-created_at"]

View file

@ -48,7 +48,7 @@ def proxy(status=libvirt.VIR_DOMAIN_SHUTOFF, nvram=None):
p.wvm.getLibVersion.return_value = 11_010_000
p.wvm.getVersion.return_value = 10_001_000
p.is_agent_ready.return_value = True
p.make_live_targets.side_effect = lambda disks, pool, names, uid, gid: [
p.make_live_targets.side_effect = lambda disks, pool, names, uid, gid, backing=None: [
{"dev": d["dev"], "path": f"/b1/{names[d['dev']]}", "format": d["format"]} for d in disks]
p.backup_targets.return_value = None
p.backup_progress.return_value = None
@ -437,6 +437,100 @@ class CreateBackupTests(TransactionTestCase):
self.run_job(op)
self.assertIsNone(self.backup(op).policy)
def chain(self, full_every=3, links=1):
"""A schedule whose last backups of the VM form a chain of links points."""
import datetime
from vmbackups.models import BackupPolicy
self.policy = BackupPolicy.objects.create(name="nightly", target=self.target, time=datetime.time(2), keep=7,
full_every=full_every, owner=self.admin)
parent = None
for _n in range(links):
parent = Backup.objects.create(target=self.target, instance=self.vm, vm_uuid=self.vm.uuid, vm_name="vm1",
compute_name="h1", state=Backup.READY, policy=self.policy, parent=parent)
parent.checkpoint = f"wvc-{parent.uuid}"
parent.save()
BackupFile.objects.create(backup=parent, role=BackupFile.DISK, dev="vda", volume=f"{parent.prefix}-vda.qcow2",
format="qcow2", capacity=GIB)
self.pool.listVolumes.return_value = [f.volume for f in BackupFile.objects.all()]
self.proxy.get_status.return_value = libvirt.VIR_DOMAIN_RUNNING
self.proxy.checkpoint_usable.return_value = True
return parent
def scheduled(self):
op = jobs.submit("backup.create", self.admin, {"instance": self.vm.pk, "target": self.target.pk,
"policy": self.policy.pk}, 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 op
def test_a_schedules_backup_builds_on_its_last_one(self):
parent = self.chain()
op = self.scheduled()
self.run_job(op)
backup = self.backup(op)
self.assertEqual((backup.parent, backup.checkpoint), (parent, f"wvc-{backup.uuid}"))
self.assertEqual(self.proxy.make_live_targets.call_args.kwargs["backing"], {"vda": f"{parent.prefix}-vda.qcow2"})
self.assertEqual(self.proxy.begin_clone_backup.call_args.kwargs,
{"incremental": parent.checkpoint, "checkpoint": backup.checkpoint})
self.proxy.checkpoint_usable.assert_called_with(parent.checkpoint, ["vda"])
self.assertEqual((backup.manifest["parent"], backup.manifest["checkpoint"]), (str(parent.uuid), backup.checkpoint))
# the checkpoints pruned before the backup began: the anchor stays
keep = self.proxy.prune_checkpoints.call_args.kwargs["keep"]
self.assertEqual(keep, {parent.checkpoint})
self.assertIn(parent.checkpoint, self.proxy.prune_checkpoints.call_args.kwargs["known"])
def test_a_chain_as_long_as_full_every_starts_again(self):
self.chain(full_every=3, links=3)
op = self.scheduled()
self.run_job(op)
backup = self.backup(op)
self.assertIsNone(backup.parent)
self.assertEqual(backup.checkpoint, f"wvc-{backup.uuid}") # the next one builds on it
self.assertEqual(self.proxy.begin_clone_backup.call_args.kwargs, {"incremental": None, "checkpoint": backup.checkpoint})
self.assertEqual(self.proxy.make_live_targets.call_args.kwargs["backing"], {})
def test_a_base_that_cannot_be_used_gives_a_full_backup(self):
for name, broken in (
("lost bitmap", lambda: setattr(self.proxy.checkpoint_usable, "return_value", False)),
("file gone", lambda: setattr(self.pool.listVolumes, "return_value", [])),
("disk added", lambda: self.proxy.backup_plan.return_value["disks"].append(
{"dev": "vdb", "path": "/pool/b.qcow2", "pool": "default", "format": "qcow2", "capacity": GIB})),
):
with self.subTest(name):
Backup.objects.all().delete()
from vmbackups.models import BackupPolicy
BackupPolicy.objects.all().delete()
self.proxy.backup_plan.return_value = plan()
self.chain()
broken()
Operation.objects.update(state=Operation.SUCCEEDED)
from operations.models import Claim
Claim.objects.all().delete()
op = self.scheduled()
self.run_job(op)
self.assertIsNone(self.backup(op).parent)
def test_full_every_one_and_backups_by_hand_make_no_checkpoint(self):
self.chain(full_every=1)
op = self.scheduled()
self.run_job(op)
self.assertEqual((self.backup(op).parent, self.backup(op).checkpoint), (None, ""))
self.assertEqual(self.proxy.begin_clone_backup.call_args.kwargs, {"incremental": None, "checkpoint": None})
# a schedule changed to full backups only: the checkpoints it left go
self.assertEqual(self.proxy.prune_checkpoints.call_args.kwargs["keep"], set())
def test_a_raw_disk_or_a_shut_off_vm_makes_no_checkpoint(self):
self.chain()
self.proxy.backup_plan.return_value["disks"][0]["format"] = "raw" # no bitmaps in a raw file
op = self.scheduled()
self.run_job(op)
self.assertEqual(self.backup(op).checkpoint, "")
def test_the_log_names_the_target_and_consistency(self):
op = self.submit()
self.run_job(op)

View file

@ -128,13 +128,14 @@ class wvmBackup(wvmInstance):
disk_owner_uid=owner_uid, disk_owner_gid=owner_gid,
)
def make_live_targets(self, disks, pool, names, owner_uid, owner_gid):
def make_live_targets(self, disks, pool, names, owner_uid, owner_gid, backing=None):
"""The empty volumes a running VM's push backup writes into, in the
target pool; the targets begin_clone_backup takes."""
target pool, each on its backing file of backing ({dev: file name},
an incremental backup's); the targets begin_clone_backup takes."""
targets = []
for disk in disks:
target = {"dev": disk["dev"], "pool": pool, "name": names[disk["dev"]],
"capacity": disk["capacity"], "format": disk["format"]}
"capacity": disk["capacity"], "format": disk["format"], "backing": (backing or {}).get(disk["dev"])}
target["path"] = self.create_clone_target(target, owner_uid, owner_gid)
targets.append(target)
return targets
@ -146,6 +147,40 @@ class wvmBackup(wvmInstance):
vol = self._find_volume(pool, os.path.basename(path))
return None if vol is None else self.download_volume(vol)
def checkpoint_usable(self, name, devs):
"""Whether the checkpoint name can be an incremental backup's base:
on this host, with a bitmap of known size for each disk of devs
(libvirt leaves the size out for a lost or invalid bitmap)."""
try:
xml = self.instance.checkpointLookupByName(name).getXMLDesc(libvirt.VIR_DOMAIN_CHECKPOINT_XML_SIZE)
except libvirt.libvirtError as err:
if err.get_error_code() != libvirt.VIR_ERR_NO_DOMAIN_CHECKPOINT:
raise
return False
sized = set(etree.fromstring(xml).xpath("disks/disk[@checkpoint='bitmap' and @size]/@name"))
return set(devs) <= sized
def prune_checkpoints(self, keep, known, devs):
"""Deletes the backups' checkpoints (wvc-) of a running VM but those
of keep, and their bitmaps. known: {name: creation time} of the
checkpoints the panel made; one libvirt no longer lists (after a
migration) is redefined first so that its bitmap goes too."""
listed = {cp.getName() for cp in self.instance.listAllCheckpoints(0)}
for name in sorted(({n for n in listed if n.startswith("wvc-")} | set(known)) - set(keep)):
if name not in listed:
disks = "".join(f"<disk name='{dev}' checkpoint='bitmap' bitmap='{name}'/>" for dev in devs)
try:
self.instance.checkpointCreateXML(
f"<domaincheckpoint><name>{name}</name><creationTime>{known[name]}</creationTime>"
f"<disks>{disks}</disks></domaincheckpoint>", libvirt.VIR_DOMAIN_CHECKPOINT_CREATE_REDEFINE)
except libvirt.libvirtError:
continue # nothing of it is left to delete
checkpoint = self.instance.checkpointLookupByName(name)
try:
checkpoint.delete(0)
except libvirt.libvirtError: # its bitmap is gone: only the record is left
checkpoint.delete(libvirt.VIR_DOMAIN_CHECKPOINT_DELETE_METADATA_ONLY)
def read_tpm(self):
"""The shut-off VM's TPM state files: {name: bytes}, {} when it never
started. swtpm's .lock is not state."""

View file

@ -25,6 +25,7 @@ from libvirt import (
VIR_DOMAIN_XML_SECURE,
VIR_DOMAIN_XML_INACTIVE,
VIR_DOMAIN_XML_MIGRATABLE,
VIR_DOMAIN_CHECKPOINT_DELETE_METADATA_ONLY,
VIR_DOMAIN_UNDEFINE_CHECKPOINTS_METADATA,
VIR_DOMAIN_UNDEFINE_KEEP_NVRAM,
VIR_ERR_NO_DOMAIN,
@ -2104,6 +2105,8 @@ class wvmInstance(wvmConnect):
if quiesce:
self.ping_agent()
flags |= VIR_DOMAIN_SNAPSHOT_CREATE_QUIESCE
if not self.instance.isActive(): # libvirt 11.10 makes no offline external snapshot while a checkpoint exists
self.drop_checkpoint_metadata()
self.instance.snapshotCreateXML(xml, flags)
self._refresh_pools_after_snapshot()
@ -2756,23 +2759,46 @@ class wvmInstance(wvmConnect):
self._refuse_taken(vol.storagePoolLookupByVolume(), clone_data["disk-" + dev])
def create_clone_target(self, target, owner_uid, owner_gid):
"""An empty volume for a copied disk; libvirt refuses one that exists.
Returns its path."""
"""An empty volume for a copied disk, with target["backing"] (a file
name in the same pool) as its backing file when given; libvirt
refuses one that exists. Returns its path."""
pool = self.wvm.storagePoolLookupByName(target["pool"])
xml = self._clone_volume_xml(target["name"], target["capacity"], target["format"], owner_uid, owner_gid)
if target.get("backing"): # an incremental backup's: the file of the backup it builds on, in its directory
tree = etree.fromstring(xml)
store = etree.SubElement(tree, "backingStore")
etree.SubElement(store, "path").text = target["backing"]
etree.SubElement(store, "format", type="qcow2")
xml = etree.tostring(tree).decode()
return pool.createXML(xml, 0).path()
def begin_clone_backup(self, targets):
def drop_checkpoint_metadata(self):
"""The backups' checkpoints (wvc-) of a shut-off VM forgotten, as
libvirt deletes bitmaps only of a running one: the next scheduled
backup is full, and removes the bitmaps left (prune_checkpoints)."""
for checkpoint in self.instance.listAllCheckpoints(0):
if checkpoint.getName().startswith("wvc-"):
checkpoint.delete(VIR_DOMAIN_CHECKPOINT_DELETE_METADATA_ONLY)
def begin_clone_backup(self, targets, incremental=None, checkpoint=None):
"""Starts libvirt's push backup of the targets' disks into their
volumes. The VM keeps running when the guest shuts down meanwhile."""
volumes: of the blocks changed since the checkpoint incremental only,
when given, and making the checkpoint checkpoint of the disks, when
given. The VM keeps running when the guest shuts down meanwhile."""
disks = "".join(
f"<disk name='{util.xml_escape(t['dev'])}' backup='yes' type='file'>"
f"<target file='{util.xml_escape(t['path'])}'/><driver type='{util.xml_escape(t['format'])}'/></disk>"
for t in targets
)
since = f"<incremental>{util.xml_escape(incremental)}</incremental>" if incremental else ""
checkpoint_xml = None
if checkpoint:
checkpoint_xml = (f"<domaincheckpoint><name>{util.xml_escape(checkpoint)}</name><disks>"
+ "".join(f"<disk name='{util.xml_escape(t['dev'])}'/>" for t in targets)
+ "</disks></domaincheckpoint>")
self.instance.backupBegin(
f"<domainbackup mode='push'><disks>{disks}</disks></domainbackup>",
None,
f"<domainbackup mode='push'>{since}<disks>{disks}</disks></domainbackup>",
checkpoint_xml,
VIR_DOMAIN_BACKUP_BEGIN_REUSE_EXTERNAL | VIR_DOMAIN_BACKUP_BEGIN_PRESERVE_SHUTDOWN_DOMAIN,
)

View file

@ -6,6 +6,7 @@ from contextlib import nullcontext
from unittest.mock import MagicMock
import libvirt
from lxml import etree
from vrtManager import util
from vrtManager.backup import backup_file_names, check_target_space, put_file, wvmBackup
@ -433,3 +434,97 @@ class RestoreHostTestCase(unittest.TestCase):
self.check(conn, "swtpm", definition=with_tpm)
offers("<value>tpm-tis</value><value>tpm-crb</value>")
self.check(conn, definition=with_tpm)
class CheckpointTestCase(unittest.TestCase):
"""The checkpoints an incremental backup builds on (wvmBackup)."""
def proxy(self, checkpoints):
p = wvmBackup.__new__(wvmBackup)
p.instance = MagicMock()
p.wvm = MagicMock()
self.deleted, self.redefined = [], []
objs = {}
def lookup(name):
if name not in checkpoints:
raise error(libvirt.VIR_ERR_NO_DOMAIN_CHECKPOINT)
if name not in objs:
cp = MagicMock()
cp.getName.return_value = name
cp.getXMLDesc.return_value = checkpoints[name]
cp.delete.side_effect = lambda flags, n=name: self.on_delete(n, flags, checkpoints)
objs[name] = cp
return objs[name]
p.instance.checkpointLookupByName.side_effect = lookup
p.instance.listAllCheckpoints.side_effect = lambda flags=0: [lookup(n) for n in list(checkpoints)]
def redefine(xml, flags):
name = etree.fromstring(xml).findtext("name")
self.redefined.append((name, flags, xml))
checkpoints[name] = "<domaincheckpoint/>"
p.instance.checkpointCreateXML.side_effect = redefine
return p
gone = set()
def on_delete(self, name, flags, checkpoints):
if flags == 0 and name in self.gone:
raise error(libvirt.VIR_ERR_INTERNAL_ERROR) # its bitmap is not in the disk
self.deleted.append((name, flags))
checkpoints.pop(name)
def test_a_checkpoint_is_usable_only_with_a_size_for_every_disk(self):
sized = ("<domaincheckpoint><disks><disk name='vda' checkpoint='bitmap' size='0'/>"
"<disk name='vdb' checkpoint='bitmap' size='4096'/></disks></domaincheckpoint>")
lost = sized.replace(" size='4096'", "") # libvirt leaves size out for a lost or invalid bitmap
p = self.proxy({"wvc-a": sized, "wvc-b": lost})
self.assertTrue(p.checkpoint_usable("wvc-a", ["vda", "vdb"]))
self.assertFalse(p.checkpoint_usable("wvc-b", ["vda", "vdb"]))
self.assertFalse(p.checkpoint_usable("wvc-a", ["vda", "vdb", "vdc"]))
self.assertFalse(p.checkpoint_usable("wvc-x", ["vda"])) # not on this host (after a migration)
p.instance.checkpointLookupByName("wvc-a").getXMLDesc.assert_called_with(libvirt.VIR_DOMAIN_CHECKPOINT_XML_SIZE)
def test_pruning_keeps_the_anchors_and_removes_orphan_bitmaps(self):
p = self.proxy({"wvc-keep": "<x/>", "wvc-old": "<x/>", "other": "<x/>"})
self.gone = {"wvc-lost"}
p.prune_checkpoints(keep={"wvc-keep"}, known={"wvc-keep": 1, "wvc-old": 2, "wvc-orphan": 3, "wvc-lost": 4},
devs=["vda"])
self.assertEqual(sorted(self.deleted), [("wvc-lost", libvirt.VIR_DOMAIN_CHECKPOINT_DELETE_METADATA_ONLY),
("wvc-old", 0), ("wvc-orphan", 0)])
# a name libvirt does not list is redefined first, so its bitmap goes with it
self.assertEqual([(n, f) for n, f, _x in self.redefined], [("wvc-lost", libvirt.VIR_DOMAIN_CHECKPOINT_CREATE_REDEFINE),
("wvc-orphan", libvirt.VIR_DOMAIN_CHECKPOINT_CREATE_REDEFINE)])
xml = etree.fromstring(dict((n, x) for n, _f, x in self.redefined)["wvc-orphan"])
self.assertEqual((xml.findtext("creationTime"), xml.xpath("disks/disk/@bitmap")), ("3", ["wvc-orphan"]))
def test_metadata_only_drop_offline(self):
p = self.proxy({"wvc-a": "<x/>", "wvc-b": "<x/>", "other": "<x/>"})
p.drop_checkpoint_metadata()
self.assertEqual(sorted(self.deleted), [("wvc-a", libvirt.VIR_DOMAIN_CHECKPOINT_DELETE_METADATA_ONLY),
("wvc-b", libvirt.VIR_DOMAIN_CHECKPOINT_DELETE_METADATA_ONLY)])
def test_an_incremental_backup_names_its_base_and_checkpoint(self):
p = wvmBackup.__new__(wvmBackup)
p.instance = MagicMock()
p.begin_clone_backup([{"dev": "vda", "path": "/b/x.qcow2", "format": "qcow2"}], incremental="wvc-a",
checkpoint="wvc-b")
backup_xml, checkpoint_xml, _flags = p.instance.backupBegin.call_args.args
self.assertEqual(etree.fromstring(backup_xml).findtext("incremental"), "wvc-a")
cp = etree.fromstring(checkpoint_xml)
self.assertEqual((cp.findtext("name"), cp.xpath("disks/disk/@name")), ("wvc-b", ["vda"]))
p.begin_clone_backup([{"dev": "vda", "path": "/b/x.qcow2", "format": "qcow2"}])
self.assertIsNone(etree.fromstring(p.instance.backupBegin.call_args.args[0]).find("incremental"))
self.assertIsNone(p.instance.backupBegin.call_args.args[1])
def test_an_incremental_target_has_its_base_as_backing_file(self):
p = wvmBackup.__new__(wvmBackup)
p.wvm = MagicMock()
p.make_live_targets([{"dev": "vda", "capacity": GIB, "format": "qcow2"}], "b1", {"vda": "wvc-n-vda.qcow2"}, 107, 107,
backing={"vda": "wvc-p-vda.qcow2"})
vol = etree.fromstring(p.wvm.storagePoolLookupByName.return_value.createXML.call_args.args[0])
# relative: the target pool's directory may differ per host
self.assertEqual((vol.findtext("backingStore/path"), vol.xpath("string(backingStore/format/@type)")),
("wvc-p-vda.qcow2", "qcow2"))

View file

@ -272,6 +272,18 @@ class CreateTestCase(unittest.TestCase):
# before, for the free space; after, for the new overlays
self.assertEqual(p.refresh_instance_pools.call_count, 2)
def test_a_shut_off_vms_backup_checkpoints_are_forgotten_first(self):
# libvirt 11.10 refuses an offline external snapshot while a checkpoint exists
p = proxy(status=5)
events = []
checkpoints = [MagicMock(**{"getName.return_value": n}) for n in ("wvc-a", "other")]
for cp in checkpoints:
cp.delete.side_effect = lambda flags, n=cp.getName(): events.append(("delete", n, flags))
p.instance.listAllCheckpoints.return_value = checkpoints
p.instance.snapshotCreateXML.side_effect = lambda xml, flags: events.append(("snapshot",))
p.create_external_snapshot("snap-1")
self.assertEqual(events, [("delete", "wvc-a", libvirt.VIR_DOMAIN_CHECKPOINT_DELETE_METADATA_ONLY), ("snapshot",)])
def test_description_is_escaped(self):
p = proxy()
p.create_external_snapshot("s", "<x> & 'y'")

View file

@ -0,0 +1,118 @@
"""Live check of incremental backups: a full push backup with a checkpoint,
then backups of the changed blocks into volumes whose backing file is the
previous backup (by its name), copied flat by createXMLFrom equal to the
guest's disk; and the checkpoints pruned to the newest.
Runs only with TEST_LIBVIRT_HOST set (see vrtManager/tests/livetest.py).
"""
import json
import os
import time
import unittest
import libvirt
import libvirt_qemu
from django.test import SimpleTestCase
from lxml import etree
from vrtManager.backup import wvmBackup
from vrtManager.connection import connection_manager, wvmConnect
from vrtManager.tests import livetest
NAME = livetest.PREFIX + "incremental"
MIB = 1024 * 1024
class LiveIncrementalTestCase(SimpleTestCase):
@classmethod
def setUpClass(cls):
if not livetest.enabled():
raise unittest.SkipTest("Set TEST_LIBVIRT_HOST to run the live libvirt tests")
cls.args = (
os.environ["TEST_LIBVIRT_HOST"],
os.environ.get("TEST_LIBVIRT_LOGIN", ""),
os.environ.get("TEST_LIBVIRT_PASSWORD", ""),
int(os.environ.get("TEST_LIBVIRT_TYPE", 4)),
)
cls.conn = connection_manager.get_connection(*cls.args)
livetest.cleanup(cls.conn)
cls.inventory = livetest.inventory(cls.conn)
super().setUpClass()
@classmethod
def tearDownClass(cls):
livetest.cleanup(cls.conn)
super().tearDownClass()
if livetest.inventory(cls.conn) != cls.inventory:
raise AssertionError("Live tests changed objects outside the test namespace")
def tearDown(self):
for dom in self.conn.listAllDomains():
if dom.name() == NAME:
if dom.isActive():
dom.destroy()
dom.undefineFlags(livetest.UNDEFINE_FLAGS | libvirt.VIR_DOMAIN_UNDEFINE_CHECKPOINTS_METADATA)
livetest.cleanup(self.conn)
def write(self, dom, pattern, offset):
"""A guest write, through the disk device's own block backend."""
libvirt_qemu.qemuMonitorCommand(
dom, f'qemu-io -d /machine/peripheral/virtio-disk0/virtio-backend "write -P {pattern} {offset} 1M"',
libvirt_qemu.VIR_DOMAIN_QEMU_MONITOR_COMMAND_HMP)
def backup(self, proxy, name, incremental=None, checkpoint=None, backing=None):
disks = [{"dev": "vda", "capacity": 64 * MIB, "format": "qcow2"}]
targets = proxy.make_live_targets(disks, livetest.POOL, {"vda": name}, 0, 0,
backing={"vda": backing} if backing else None)
proxy.begin_clone_backup(targets, incremental=incremental, checkpoint=checkpoint)
while proxy.backup_progress() is not None:
time.sleep(0.2)
self.assertEqual(proxy.backup_result()[0], True)
def test_a_chain_copies_flat_to_the_guests_disk(self):
pool = livetest.ensure_pool(self.conn)
disk = livetest.create_volume(self.conn, NAME + ".qcow2")
dom = livetest.define_vm(self.conn, NAME, [disk])
dom.create()
proxy = wvmBackup(*self.args, NAME, uuid=dom.UUIDString())
self.write(dom, "0xaa", 0)
for offset in range(8, 16):
self.write(dom, "0xdd", offset * MIB)
self.backup(proxy, NAME + "-full.qcow2", checkpoint="wvc-1")
self.write(dom, "0xbb", 2 * MIB)
self.assertTrue(proxy.checkpoint_usable("wvc-1", ["vda"]))
self.backup(proxy, NAME + "-inc1.qcow2", incremental="wvc-1", checkpoint="wvc-2", backing=NAME + "-full.qcow2")
self.write(dom, "0xcc", 4 * MIB)
self.backup(proxy, NAME + "-inc2.qcow2", incremental="wvc-2", checkpoint="wvc-3", backing=NAME + "-inc1.qcow2")
pool.refresh(0)
inc2 = pool.storageVolLookupByName(NAME + "-inc2.qcow2")
self.assertEqual(etree.fromstring(inc2.XMLDesc(0)).findtext("backingStore/path").rsplit("/", 1)[-1],
NAME + "-inc1.qcow2")
# only the changed blocks: the incremental file is far smaller than the full one
self.assertLess(inc2.info()[2], pool.storageVolLookupByName(NAME + "-full.qcow2").info()[2])
flat = pool.createXMLFrom(f"<volume><name>{NAME}-flat.raw</name><capacity>{64 * MIB}</capacity>"
"<target><format type='raw'/></target></volume>", inc2, 0)
data = wvmConnect(*self.args).download_volume(flat)
self.assertEqual(data[:MIB], b"\xaa" * MIB)
self.assertEqual(data[2 * MIB:3 * MIB], b"\xbb" * MIB)
self.assertEqual(data[4 * MIB:5 * MIB], b"\xcc" * MIB)
self.assertEqual(data[MIB:2 * MIB].count(0), MIB)
self.assertEqual(data[8 * MIB:16 * MIB], b"\xdd" * 8 * MIB)
proxy.prune_checkpoints(keep={"wvc-3"}, known={"wvc-1": 1, "wvc-2": 2, "wvc-3": 3}, devs=["vda"])
self.assertEqual([c.getName() for c in dom.listAllCheckpoints(0)], ["wvc-3"])
nodes = json.loads(libvirt_qemu.qemuMonitorCommand(
dom, json.dumps({"execute": "query-named-block-nodes", "arguments": {"flat": True}}), 0))["return"]
self.assertEqual(sorted({b["name"] for n in nodes for b in n.get("dirty-bitmaps", [])}), ["wvc-3"])
# after a migration the checkpoint's record is gone, its bitmap is not: the pruning finds it
dom.checkpointLookupByName("wvc-3").delete(libvirt.VIR_DOMAIN_CHECKPOINT_DELETE_METADATA_ONLY)
self.assertFalse(proxy.checkpoint_usable("wvc-3", ["vda"]))
proxy.prune_checkpoints(keep=set(), known={"wvc-3": 3}, devs=["vda"])
nodes = json.loads(libvirt_qemu.qemuMonitorCommand(
dom, json.dumps({"execute": "query-named-block-nodes", "arguments": {"flat": True}}), 0))["return"]
self.assertEqual([b for n in nodes for b in n.get("dirty-bitmaps", [])], [])