1
0
Fork 0
mirror of https://github.com/retspen/webvirtcloud synced 2026-12-03 17:36:05 +00:00

feat(vmbackups): a backup's file names begin with its VM's name

Someone looking at the target's directory could not tell whose backup a
file was without opening its manifest. A new backup's files are named
<vm>-<backup uuid>-<file> (the VM's name made safe for a file name, at most
64 characters). The prefix is kept on the row: backups made before keep
their wvc-<uuid> names (migration 0007), and an import takes it from the
manifest's file name. Manifests of either naming are found by their
UUID suffix.
This commit is contained in:
catborise 2026-11-18 14:57:14 +03:00
parent 8e0a84a3bd
commit 5b05e76ebc
8 changed files with 81 additions and 33 deletions

View file

@ -31,7 +31,7 @@ from operations.jobs import Cancelled, Kind, Outcome, Plan, register, register_p
from operations.models import Claim, Operation from operations.models import Claim, Operation
from operations.utils import safe_text, say from operations.utils import safe_text, say
from vrtManager import util from vrtManager import util
from vrtManager.backup import (backup_file_names, 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,
remove_files, restore_definition, restore_over_definition, target_pool, volume_exists, remove_files, restore_definition, restore_over_definition, target_pool, volume_exists,
wvmBackup) wvmBackup)
from vrtManager.connection import NVRAM_DIR, wvmConnect from vrtManager.connection import NVRAM_DIR, wvmConnect
@ -345,7 +345,7 @@ class CreateBackup(Kind):
"start"), compute=instance.compute.name) "start"), compute=instance.compute.name)
status = proxy.get_status() status = proxy.get_status()
live = status != VIR_DOMAIN_SHUTOFF live = status != VIR_DOMAIN_SHUTOFF
names = backup_file_names(op.intent["backup"], plan["disks"], bool(plan["nvram"])) names = backup_file_names(backup_prefix(instance.name, op.intent["backup"]), plan["disks"], bool(plan["nvram"]))
# a schedule deleted since the job was queued: the backup is kept, without it # 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 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) # a running VM's scheduled backup makes a checkpoint the next one builds on (bitmaps need qcow2 disks)
@ -1358,6 +1358,7 @@ class ImportBackups(Kind):
with transaction.atomic(): with transaction.atomic():
backup = Backup.objects.create( backup = Backup.objects.create(
uuid=manifest["backup"], target=target, state=Backup.READY, **fields, uuid=manifest["backup"], target=target, state=Backup.READY, **fields,
prefix=name.removesuffix("-manifest.json"),
instance=Instance.objects.filter(uuid=fields["vm_uuid"]).first(), instance=Instance.objects.filter(uuid=fields["vm_uuid"]).first(),
manifest=manifest, finished_at=timezone.now(), size=sum(f["size"] for f in files) + len(data), manifest=manifest, finished_at=timezone.now(), size=sum(f["size"] for f in files) + len(data),
) )

View file

@ -0,0 +1,18 @@
from django.db import migrations, models
def earlier_names(apps, schema_editor):
"""The backups made so far named their files from their UUID only."""
Backup = apps.get_model("vmbackups", "Backup")
for backup in Backup.objects.all():
Backup.objects.filter(pk=backup.pk).update(prefix=f"wvc-{backup.uuid}")
class Migration(migrations.Migration):
dependencies = [("vmbackups", "0006_run_note_messages")]
operations = [
migrations.AddField(model_name="backup", name="prefix", field=models.CharField(default="", max_length=128),
preserve_default=False),
migrations.RunPython(earlier_names, migrations.RunPython.noop),
]

View file

@ -6,6 +6,7 @@ from django.db import models
from computes.models import Compute from computes.models import Compute
from instances.models import Instance from instances.models import Instance
from operations.models import Operation from operations.models import Operation
from vrtManager.backup import backup_prefix
class BackupTarget(models.Model): class BackupTarget(models.Model):
@ -112,6 +113,7 @@ class Backup(models.Model):
checkpoint = models.CharField(max_length=64, blank=True) # the VM's checkpoint made with it checkpoint = models.CharField(max_length=64, blank=True) # the VM's checkpoint made with it
# whose job made it: a VM owner's own backups count in their backup quota # 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="+") 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 "-"
class Meta: class Meta:
ordering = ["-created_at"] ordering = ["-created_at"]
@ -126,10 +128,10 @@ class Backup(models.Model):
"""Whether a backup builds on this one: a failed one holds nothing.""" """Whether a backup builds on this one: a failed one holds nothing."""
return self.children.filter(state__in=self.LIVING).exists() return self.children.filter(state__in=self.LIVING).exists()
@property def save(self, *args, **kwargs):
def prefix(self): if not self.prefix:
"""Every file of the backup in the target is named from its UUID only.""" self.prefix = backup_prefix(self.vm_name, self.uuid)
return f"wvc-{self.uuid}" super().save(*args, **kwargs)
class BackupFile(models.Model): class BackupFile(models.Model):

View file

@ -125,7 +125,7 @@ class CreateBackupTests(TransactionTestCase):
def test_a_shut_off_vm_is_copied_offline(self): def test_a_shut_off_vm_is_copied_offline(self):
op = self.submit() op = self.submit()
self.assertEqual(self.run_job(op), {"backup": op.intent["backup"]}) self.assertEqual(self.run_job(op), {"backup": op.intent["backup"]})
prefix = f"wvc-{op.intent['backup']}" prefix = f"vm1-{op.intent['backup']}"
self.proxy.copy_disk_offline.assert_called_once_with(plan()["disks"][0], "b1", f"{prefix}-vda.qcow2", *_owner()) self.proxy.copy_disk_offline.assert_called_once_with(plan()["disks"][0], "b1", f"{prefix}-vda.qcow2", *_owner())
self.proxy.begin_clone_backup.assert_not_called() self.proxy.begin_clone_backup.assert_not_called()
self.assertEqual(self.written, [f"{prefix}-domain.xml", f"{prefix}-manifest.json"]) # the manifest last self.assertEqual(self.written, [f"{prefix}-domain.xml", f"{prefix}-manifest.json"]) # the manifest last
@ -142,7 +142,7 @@ class CreateBackupTests(TransactionTestCase):
self.proxy.backup_plan.return_value = plan(tpm=True) self.proxy.backup_plan.return_value = plan(tpm=True)
op = self.submit() op = self.submit()
self.run_job(op) self.run_job(op)
prefix = f"wvc-{op.intent['backup']}" prefix = f"vm1-{op.intent['backup']}"
self.assertEqual(self.written, [f"{prefix}-tpm-tpm2-00.permall", f"{prefix}-domain.xml", f"{prefix}-manifest.json"]) self.assertEqual(self.written, [f"{prefix}-tpm-tpm2-00.permall", f"{prefix}-domain.xml", f"{prefix}-manifest.json"])
self.assertEqual(self.modes[f"{prefix}-tpm-tpm2-00.permall"], "0600") # a secret self.assertEqual(self.modes[f"{prefix}-tpm-tpm2-00.permall"], "0600") # a secret
self.assertEqual(self.modes[f"{prefix}-domain.xml"], "0600") # its graphics passwords self.assertEqual(self.modes[f"{prefix}-domain.xml"], "0600") # its graphics passwords
@ -161,13 +161,13 @@ class CreateBackupTests(TransactionTestCase):
def test_a_failed_backup_removes_the_tpm_files_it_wrote(self): def test_a_failed_backup_removes_the_tpm_files_it_wrote(self):
self.proxy.backup_plan.return_value = plan(tpm=True) self.proxy.backup_plan.return_value = plan(tpm=True)
op = self.submit() op = self.submit()
prefix = f"wvc-{op.intent['backup']}" prefix = f"vm1-{op.intent['backup']}"
self.pool.listVolumes.return_value = [f"{prefix}-tpm-tpm2-00.permall", "wvc-00000000-0000-4000-8000-000000000009-tpm-x"] self.pool.listVolumes.return_value = [f"{prefix}-tpm-tpm2-00.permall", "vm2-00000000-0000-4000-8000-000000000009-tpm-x"]
self.fail_on = "-domain.xml" # once the TPM file is written self.fail_on = "-domain.xml" # once the TPM file is written
op = self.interrupted(op) op = self.interrupted(op)
self.assertEqual(CreateBackup().reconcile(op).state, Operation.FAILED) self.assertEqual(CreateBackup().reconcile(op).state, Operation.FAILED)
self.assertIn(f"{prefix}-tpm-tpm2-00.permall", self.removed) self.assertIn(f"{prefix}-tpm-tpm2-00.permall", self.removed)
self.assertNotIn("wvc-00000000-0000-4000-8000-000000000009-tpm-x", self.removed) self.assertNotIn("vm2-00000000-0000-4000-8000-000000000009-tpm-x", self.removed)
def test_a_running_vm_is_frozen_backed_up_and_thawed(self): def test_a_running_vm_is_frozen_backed_up_and_thawed(self):
self.proxy.get_status.return_value = libvirt.VIR_DOMAIN_RUNNING self.proxy.get_status.return_value = libvirt.VIR_DOMAIN_RUNNING
@ -266,7 +266,7 @@ class CreateBackupTests(TransactionTestCase):
self.proxy.read_nvram.side_effect = [b"vars", b"new", b"vars"] # before; after, changed then back self.proxy.read_nvram.side_effect = [b"vars", b"new", b"vars"] # before; after, changed then back
op = self.submit() op = self.submit()
self.run_job(op) self.run_job(op)
self.assertIn(f"wvc-{op.intent['backup']}-nvram.fd", self.written) self.assertIn(f"vm1-{op.intent['backup']}-nvram.fd", self.written)
self.assertEqual(self.backup(op).manifest["nvram"], "copied") self.assertEqual(self.backup(op).manifest["nvram"], "copied")
def test_nvram_changed_across_the_copy_is_retried_then_refused(self): def test_nvram_changed_across_the_copy_is_retried_then_refused(self):
@ -278,7 +278,7 @@ class CreateBackupTests(TransactionTestCase):
self.assertEqual(self.proxy.read_nvram.call_count, 4) # before, then three after self.assertEqual(self.proxy.read_nvram.call_count, 4) # before, then three after
outcome = CreateBackup().reconcile(op) outcome = CreateBackup().reconcile(op)
self.assertEqual(outcome.state, Operation.FAILED) self.assertEqual(outcome.state, Operation.FAILED)
self.assertIn(f"wvc-{op.intent['backup']}-vda.qcow2", self.removed) self.assertIn(f"vm1-{op.intent['backup']}-vda.qcow2", self.removed)
self.assertEqual(self.backup(op).state, Backup.FAILED) self.assertEqual(self.backup(op).state, Backup.FAILED)
def test_the_guest_shutting_down_does_not_fail_the_backup(self): def test_the_guest_shutting_down_does_not_fail_the_backup(self):
@ -319,14 +319,14 @@ class CreateBackupTests(TransactionTestCase):
outcome = CreateBackup().reconcile(op) outcome = CreateBackup().reconcile(op)
self.assertEqual(outcome.state, Operation.FAILED) self.assertEqual(outcome.state, Operation.FAILED)
self.assertIn("No space left on device", outcome.error[0]["text"]) self.assertIn("No space left on device", outcome.error[0]["text"])
self.assertIn(f"wvc-{op.intent['backup']}-vda.qcow2", self.removed) self.assertIn(f"vm1-{op.intent['backup']}-vda.qcow2", self.removed)
self.assertEqual(self.backup(op).state, Backup.FAILED) self.assertEqual(self.backup(op).state, Backup.FAILED)
def test_a_failed_push_backup_removes_the_volumes(self): def test_a_failed_push_backup_removes_the_volumes(self):
self.proxy.get_status.return_value = libvirt.VIR_DOMAIN_RUNNING self.proxy.get_status.return_value = libvirt.VIR_DOMAIN_RUNNING
self.proxy.backup_result.return_value = (False, "No space left on device") self.proxy.backup_result.return_value = (False, "No space left on device")
op = self.interrupted(self.submit()) op = self.interrupted(self.submit())
self.assertIn(f"wvc-{op.intent['backup']}-vda.qcow2", self.removed) self.assertIn(f"vm1-{op.intent['backup']}-vda.qcow2", self.removed)
self.assertEqual(CreateBackup().reconcile(op).state, Operation.FAILED) self.assertEqual(CreateBackup().reconcile(op).state, Operation.FAILED)
def live_interrupted(self): def live_interrupted(self):
@ -352,7 +352,7 @@ class CreateBackupTests(TransactionTestCase):
self.proxy.backup_result.return_value = None self.proxy.backup_result.return_value = None
outcome = CreateBackup().reconcile(op) outcome = CreateBackup().reconcile(op)
self.assertEqual(outcome.state, Operation.UNCERTAIN) self.assertEqual(outcome.state, Operation.UNCERTAIN)
self.assertIn(f"wvc-{op.intent['backup']}-vda.qcow2", outcome.error[0]["values"]["volumes"]) self.assertIn(f"vm1-{op.intent['backup']}-vda.qcow2", outcome.error[0]["values"]["volumes"])
self.assertEqual(self.removed, []) # the files stay for the administrator self.assertEqual(self.removed, []) # the files stay for the administrator
self.assertEqual(self.backup(op).state, Backup.FAILED) self.assertEqual(self.backup(op).state, Backup.FAILED)
@ -416,7 +416,7 @@ class CreateBackupTests(TransactionTestCase):
self.proxy.backup_targets.return_value = None self.proxy.backup_targets.return_value = None
self.proxy.backup_result.return_value = (False, "operation aborted") self.proxy.backup_result.return_value = (False, "operation aborted")
self.assertEqual(CreateBackup().reconcile(op).state, Operation.CANCELLED) self.assertEqual(CreateBackup().reconcile(op).state, Operation.CANCELLED)
self.assertIn(f"wvc-{op.intent['backup']}-vda.qcow2", self.removed) self.assertIn(f"vm1-{op.intent['backup']}-vda.qcow2", self.removed)
def test_an_offline_copy_cancelled_stops_before_its_next_disk(self): def test_an_offline_copy_cancelled_stops_before_its_next_disk(self):
op = self.submit() op = self.submit()
@ -432,7 +432,7 @@ class CreateBackupTests(TransactionTestCase):
with self.assertRaises(Cancelled): with self.assertRaises(Cancelled):
self.run_job(op) self.run_job(op)
self.assertEqual(self.written, []) self.assertEqual(self.written, [])
self.assertIn(f"wvc-{op.intent['backup']}-vda.qcow2", self.removed) self.assertIn(f"vm1-{op.intent['backup']}-vda.qcow2", self.removed)
self.assertEqual(self.backup(op).state, Backup.FAILED) self.assertEqual(self.backup(op).state, Backup.FAILED)
def test_a_vm_started_during_its_offline_copy_is_not_published(self): def test_a_vm_started_during_its_offline_copy_is_not_published(self):
@ -444,7 +444,7 @@ class CreateBackupTests(TransactionTestCase):
outcome = CreateBackup().reconcile(op) # recovery does not publish it either outcome = CreateBackup().reconcile(op) # recovery does not publish it either
self.assertEqual(outcome.state, Operation.FAILED) self.assertEqual(outcome.state, Operation.FAILED)
self.assertIn("started", str(outcome.error)) self.assertIn("started", str(outcome.error))
self.assertIn(f"wvc-{op.intent['backup']}-vda.qcow2", self.removed) self.assertIn(f"vm1-{op.intent['backup']}-vda.qcow2", self.removed)
self.assertEqual(self.backup(op).state, Backup.FAILED) self.assertEqual(self.backup(op).state, Backup.FAILED)
def test_progress_counts_the_copied_disks(self): def test_progress_counts_the_copied_disks(self):

View file

@ -98,6 +98,7 @@ class ImportTests(TransactionTestCase):
self.assertEqual((backup.state, backup.target, backup.instance, backup.vm_name, backup.consistency), self.assertEqual((backup.state, backup.target, backup.instance, backup.vm_name, backup.consistency),
(Backup.READY, self.target, self.vm, "vm1", "frozen")) (Backup.READY, self.target, self.vm, "vm1", "frozen"))
self.assertEqual(backup.created_at.isoformat(), "2026-11-01T10:00:00+00:00") self.assertEqual(backup.created_at.isoformat(), "2026-11-01T10:00:00+00:00")
self.assertEqual(backup.prefix, f"wvc-{self.a}") # its files' names, as the target has them
self.assertEqual(sorted(backup.files.values_list("role", flat=True)), ["disk", "domain"]) self.assertEqual(sorted(backup.files.values_list("role", flat=True)), ["disk", "domain"])
self.assertEqual(self.read()["added"], 0) self.assertEqual(self.read()["added"], 0)
self.assertEqual(Backup.objects.count(), 2) self.assertEqual(Backup.objects.count(), 2)

View file

@ -51,8 +51,9 @@ class BackupModelTests(TestCase):
self.assertIsNone(self.target.pool_on(self.compute)) self.assertIsNone(self.target.pool_on(self.compute))
def test_prefix(self): def test_prefix(self):
backup = Backup(uuid=UUID("00000000-0000-4000-8000-000000000001")) target = BackupTarget.objects.create(name="nfs-p")
self.assertEqual(backup.prefix, "wvc-00000000-0000-4000-8000-000000000001") backup = Backup.objects.create(uuid=UUID("00000000-0000-4000-8000-000000000001"), target=target, vm_name="web 01")
self.assertEqual(backup.prefix, "web_01-00000000-0000-4000-8000-000000000001")
def test_claim_keys(self): def test_claim_keys(self):
self.assertEqual(backup_target_key(3), "backup_target:3") self.assertEqual(backup_target_key(3), "backup_target:3")

View file

@ -2,6 +2,7 @@
import hashlib import hashlib
import os import os
import re
import libvirt import libvirt
from django.utils.translation import gettext_noop from django.utils.translation import gettext_noop
@ -213,9 +214,15 @@ class wvmBackup(wvmInstance):
for name in sorted(pool.listVolumes()) if not name.startswith(".")} for name in sorted(pool.listVolumes()) if not name.startswith(".")}
def backup_file_names(uuid, disks, nvram): def backup_prefix(vm_name, uuid):
"""The names of a backup's files in the target pool, from its UUID only.""" """The start of a backup's file names in the target pool: its VM's name,
prefix = f"wvc-{uuid}" so the directory shows whose it is, and the backup's UUID."""
name = re.sub(r"[^A-Za-z0-9._-]", "_", vm_name)[:64].lstrip(".-") or "vm"
return f"{name}-{uuid}"
def backup_file_names(prefix, disks, nvram):
"""The names of a backup's files in the target pool."""
return { return {
"disks": {d["dev"]: f"{prefix}-{d['dev']}.{'qcow2' if d['format'] == 'qcow2' else 'raw'}" for d in disks}, "disks": {d["dev"]: f"{prefix}-{d['dev']}.{'qcow2' if d['format'] == 'qcow2' else 'raw'}" for d in disks},
"nvram": f"{prefix}-nvram.fd" if nvram else None, "nvram": f"{prefix}-nvram.fd" if nvram else None,
@ -267,9 +274,12 @@ def volume_exists(pool, name):
return wvmConnect._find_volume(pool, name) is not None return wvmConnect._find_volume(pool, name) is not None
MANIFEST_NAME = re.compile(r"-[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}-manifest\.json$")
def manifest_names(pool): def manifest_names(pool):
pool.refresh(0) pool.refresh(0)
return sorted(name for name in pool.listVolumes() if name.startswith("wvc-") and name.endswith("-manifest.json")) return sorted(name for name in pool.listVolumes() if MANIFEST_NAME.search(name))
def set_disk_sources(tree, disks): def set_disk_sources(tree, disks):

View file

@ -9,7 +9,7 @@ import libvirt
from lxml import etree from lxml import etree
from vrtManager import util from vrtManager import util
from vrtManager.backup import backup_file_names, check_target_space, put_file, wvmBackup from vrtManager.backup import backup_file_names, backup_prefix, check_target_space, manifest_names, put_file, wvmBackup
from vrtManager.instance import PERSISTENT_XML from vrtManager.instance import PERSISTENT_XML
GIB = 1024**3 GIB = 1024**3
@ -208,18 +208,33 @@ class BackupPlanTestCase(unittest.TestCase):
class FilesTestCase(unittest.TestCase): class FilesTestCase(unittest.TestCase):
def test_file_names(self): def test_file_names(self):
uuid = "00000000-0000-4000-8000-000000000001" uuid = "00000000-0000-4000-8000-000000000001"
prefix = backup_prefix("web-01", uuid)
self.assertEqual(prefix, f"web-01-{uuid}") # whose backup it is, seen in the target's directory
disks = [{"dev": "vda", "format": "qcow2"}, {"dev": "vdb", "format": "raw"}] disks = [{"dev": "vda", "format": "qcow2"}, {"dev": "vdb", "format": "raw"}]
self.assertEqual( self.assertEqual(
backup_file_names(uuid, disks, nvram=True), backup_file_names(prefix, disks, nvram=True),
{ {
"disks": {"vda": f"wvc-{uuid}-vda.qcow2", "vdb": f"wvc-{uuid}-vdb.raw"}, "disks": {"vda": f"{prefix}-vda.qcow2", "vdb": f"{prefix}-vdb.raw"},
"nvram": f"wvc-{uuid}-nvram.fd", "nvram": f"{prefix}-nvram.fd",
"tpm": f"wvc-{uuid}-tpm-", "tpm": f"{prefix}-tpm-",
"domain": f"wvc-{uuid}-domain.xml", "domain": f"{prefix}-domain.xml",
"manifest": f"wvc-{uuid}-manifest.json", "manifest": f"{prefix}-manifest.json",
}, },
) )
self.assertIsNone(backup_file_names(uuid, disks, nvram=False)["nvram"]) self.assertIsNone(backup_file_names(prefix, disks, nvram=False)["nvram"])
def test_a_vm_name_is_made_safe_for_a_file_name(self):
uuid = "00000000-0000-4000-8000-000000000001"
self.assertEqual(backup_prefix("my vm/ç", uuid), f"my_vm__-{uuid}")
self.assertEqual(backup_prefix("..", uuid), f"vm-{uuid}")
self.assertEqual(len(backup_prefix("x" * 200, uuid)), 64 + 1 + 36)
def test_manifests_of_either_naming_are_found(self):
pool = MagicMock()
uuid = "00000000-0000-4000-8000-000000000001"
pool.listVolumes.return_value = [f"wvc-{uuid}-manifest.json", f"web-01-{uuid}-manifest.json",
f"web-01-{uuid}-vda.qcow2", "notes-manifest.json"]
self.assertEqual(manifest_names(pool), [f"web-01-{uuid}-manifest.json", f"wvc-{uuid}-manifest.json"])
def test_space_counts_virtual_capacity_and_the_margin(self): def test_space_counts_virtual_capacity_and_the_margin(self):
# 2 x 10 GiB plus max(10 % of it, 1 GiB) = 22 GiB # 2 x 10 GiB plus max(10 % of it, 1 GiB) = 22 GiB