1
0
Fork 0
mirror of https://github.com/retspen/webvirtcloud synced 2026-12-02 08:56:07 +00:00

fix(vmbackups): an incremental backup needs room for its changed blocks only

The target space check asked for every disk's virtual capacity even when
the backup copies only the blocks changed since its parent. The checkpoint
already reports those bytes per disk (VIR_DOMAIN_CHECKPOINT_XML_SIZE), so
checkpoint_usable becomes checkpoint_sizes and the check runs after the
parent is chosen, with the changed bytes for an incremental backup and the
capacity for a full one. The margin (free_percent, free_min_gib) is kept.
This commit is contained in:
catborise 2026-11-18 13:38:27 +03:00
parent 132676a772
commit 8cd7aee19a
5 changed files with 49 additions and 30 deletions

View file

@ -131,8 +131,8 @@ def _check_state(proxy, frozen):
def _checked(op):
"""In the worker, before anything is made: the VM, its target pool (the
one registered) and the space for its disks."""
"""In the worker, before anything is made: the VM and its target pool
(the one registered)."""
instance = _instance(op.params["instance"])
target = BackupTarget.objects.get(pk=op.params["target"])
_may_use(op.user, instance, target) # again: rights may have changed since the job was queued
@ -143,7 +143,6 @@ def _checked(op):
pool = target_pool(proxy, row.pool, row.pool_uuid)
plan = proxy.backup_plan()
_check_state(proxy, op.params["frozen"])
check_target_space(pool, plan["disks"], **_free_space())
# the target claim admits one backup at a time: this check counts every other one of the user's
_backup_quota(op.user, _estimate(plan))
return instance, target, row, proxy, pool, plan
@ -188,10 +187,11 @@ def _nvram(op, proxy):
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."""
"""The backup a scheduled backup of the VM builds on and the bytes each
disk changed since, or (None, 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
@ -199,17 +199,18 @@ def _chain_parent(policy, instance, target, plan, proxy, pool):
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
return None, None
if chain[-1].manifest.get("parent"): # its base's row is gone: the chain cannot be read whole
return None
return None, 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
return None, 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
return None, None
sizes = proxy.checkpoint_sizes(last.checkpoint, devs)
return (last, sizes) if sizes is not None else (None, None)
def _prune_checkpoints(op, proxy, plan):
@ -349,7 +350,10 @@ class CreateBackup(Kind):
# 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
parent, changed = _chain_parent(policy, instance, target, plan, proxy, pool) if checkpoint else (None, None)
# an incremental backup copies the blocks changed since its parent only
check_target_space(pool, [{"capacity": size} for size in changed.values()] if parent else plan["disks"],
**_free_space())
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,

View file

@ -23,6 +23,7 @@ from vmbackups.models import Backup, BackupFile, BackupTarget, BackupTargetPool
from vrtManager.util import OperationError
GIB = 1024**3
MIB = 1024**2
WORKER = "wvc-test:1:a"
NVRAM = "/var/lib/libvirt/qemu/nvram/vm1_VARS.fd"
@ -494,7 +495,7 @@ class CreateBackupTests(TransactionTestCase):
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
self.proxy.checkpoint_sizes.return_value = {"vda": MIB}
return parent
def scheduled(self):
@ -514,13 +515,26 @@ class CreateBackupTests(TransactionTestCase):
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.proxy.checkpoint_sizes.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_an_incremental_backup_needs_room_for_the_changed_data_only(self):
parent = self.chain()
self.pool.info.return_value = [2, 100 * GIB, 0, GIB + GIB // 2] # less than the disk's capacity and margin
op = self.scheduled()
self.run_job(op)
self.assertEqual(self.backup(op).parent, parent)
from operations.models import Claim
Claim.objects.all().delete()
self.proxy.checkpoint_sizes.return_value = None # a full backup then: it needs the disk's capacity
with self.assertRaisesMessage(OperationError, "the backup needs"):
self.run_job(self.scheduled())
def test_a_chain_as_long_as_full_every_starts_again(self):
self.chain(full_every=3, links=3)
op = self.scheduled()
@ -533,7 +547,7 @@ class CreateBackupTests(TransactionTestCase):
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)),
("lost bitmap", lambda: setattr(self.proxy.checkpoint_sizes, "return_value", None)),
("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})),

View file

@ -163,18 +163,19 @@ class wvmBackup(wvmInstance):
vol = None # in no pool: counted by its own size only
return total
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)."""
def checkpoint_sizes(self, name, devs):
"""The bytes each disk of devs changed since the checkpoint name,
{dev: size}, or None when it cannot be an incremental backup's base:
not on this host, or a disk without a bitmap of known size (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
return None
sizes = {d.get("name"): int(d.get("size")) for d in etree.fromstring(xml).xpath("disks/disk[@checkpoint='bitmap' and @size]")}
return {dev: sizes[dev] for dev in devs} if set(devs) <= set(sizes) else None
def prune_checkpoints(self, keep, known, devs):
"""Deletes the backups' checkpoints (wvc-) of a running VM but those

View file

@ -496,15 +496,15 @@ class CheckpointTestCase(unittest.TestCase):
self.deleted.append((name, flags))
checkpoints.pop(name)
def test_a_checkpoint_is_usable_only_with_a_size_for_every_disk(self):
def test_a_checkpoint_has_sizes_only_with_one_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)
self.assertEqual(p.checkpoint_sizes("wvc-a", ["vda", "vdb"]), {"vda": 0, "vdb": 4096})
self.assertIsNone(p.checkpoint_sizes("wvc-b", ["vda", "vdb"]))
self.assertIsNone(p.checkpoint_sizes("wvc-a", ["vda", "vdb", "vdc"]))
self.assertIsNone(p.checkpoint_sizes("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):

View file

@ -82,7 +82,7 @@ class LiveIncrementalTestCase(SimpleTestCase):
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.assertGreaterEqual(proxy.checkpoint_sizes("wvc-1", ["vda"])["vda"], MIB) # the block written since
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")
@ -111,7 +111,7 @@ class LiveIncrementalTestCase(SimpleTestCase):
# 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"]))
self.assertIsNone(proxy.checkpoint_sizes("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"]