mirror of
https://github.com/retspen/webvirtcloud
synced 2026-12-02 08:56:07 +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:
parent
8e0a84a3bd
commit
5b05e76ebc
8 changed files with 81 additions and 33 deletions
|
|
@ -31,7 +31,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, 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,
|
||||
wvmBackup)
|
||||
from vrtManager.connection import NVRAM_DIR, wvmConnect
|
||||
|
|
@ -345,7 +345,7 @@ class CreateBackup(Kind):
|
|||
"start"), compute=instance.compute.name)
|
||||
status = proxy.get_status()
|
||||
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
|
||||
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)
|
||||
|
|
@ -1358,6 +1358,7 @@ class ImportBackups(Kind):
|
|||
with transaction.atomic():
|
||||
backup = Backup.objects.create(
|
||||
uuid=manifest["backup"], target=target, state=Backup.READY, **fields,
|
||||
prefix=name.removesuffix("-manifest.json"),
|
||||
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),
|
||||
)
|
||||
|
|
|
|||
18
vmbackups/migrations/0007_backup_prefix.py
Normal file
18
vmbackups/migrations/0007_backup_prefix.py
Normal 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),
|
||||
]
|
||||
|
|
@ -6,6 +6,7 @@ from django.db import models
|
|||
from computes.models import Compute
|
||||
from instances.models import Instance
|
||||
from operations.models import Operation
|
||||
from vrtManager.backup import backup_prefix
|
||||
|
||||
|
||||
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
|
||||
# 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 "-"
|
||||
|
||||
class Meta:
|
||||
ordering = ["-created_at"]
|
||||
|
|
@ -126,10 +128,10 @@ class Backup(models.Model):
|
|||
"""Whether a backup builds on this one: a failed one holds nothing."""
|
||||
return self.children.filter(state__in=self.LIVING).exists()
|
||||
|
||||
@property
|
||||
def prefix(self):
|
||||
"""Every file of the backup in the target is named from its UUID only."""
|
||||
return f"wvc-{self.uuid}"
|
||||
def save(self, *args, **kwargs):
|
||||
if not self.prefix:
|
||||
self.prefix = backup_prefix(self.vm_name, self.uuid)
|
||||
super().save(*args, **kwargs)
|
||||
|
||||
|
||||
class BackupFile(models.Model):
|
||||
|
|
|
|||
|
|
@ -125,7 +125,7 @@ class CreateBackupTests(TransactionTestCase):
|
|||
def test_a_shut_off_vm_is_copied_offline(self):
|
||||
op = self.submit()
|
||||
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.begin_clone_backup.assert_not_called()
|
||||
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)
|
||||
op = self.submit()
|
||||
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.modes[f"{prefix}-tpm-tpm2-00.permall"], "0600") # a secret
|
||||
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):
|
||||
self.proxy.backup_plan.return_value = plan(tpm=True)
|
||||
op = self.submit()
|
||||
prefix = f"wvc-{op.intent['backup']}"
|
||||
self.pool.listVolumes.return_value = [f"{prefix}-tpm-tpm2-00.permall", "wvc-00000000-0000-4000-8000-000000000009-tpm-x"]
|
||||
prefix = f"vm1-{op.intent['backup']}"
|
||||
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
|
||||
op = self.interrupted(op)
|
||||
self.assertEqual(CreateBackup().reconcile(op).state, Operation.FAILED)
|
||||
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):
|
||||
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
|
||||
op = self.submit()
|
||||
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")
|
||||
|
||||
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
|
||||
outcome = CreateBackup().reconcile(op)
|
||||
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)
|
||||
|
||||
def test_the_guest_shutting_down_does_not_fail_the_backup(self):
|
||||
|
|
@ -319,14 +319,14 @@ class CreateBackupTests(TransactionTestCase):
|
|||
outcome = CreateBackup().reconcile(op)
|
||||
self.assertEqual(outcome.state, Operation.FAILED)
|
||||
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)
|
||||
|
||||
def test_a_failed_push_backup_removes_the_volumes(self):
|
||||
self.proxy.get_status.return_value = libvirt.VIR_DOMAIN_RUNNING
|
||||
self.proxy.backup_result.return_value = (False, "No space left on device")
|
||||
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)
|
||||
|
||||
def live_interrupted(self):
|
||||
|
|
@ -352,7 +352,7 @@ class CreateBackupTests(TransactionTestCase):
|
|||
self.proxy.backup_result.return_value = None
|
||||
outcome = CreateBackup().reconcile(op)
|
||||
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.backup(op).state, Backup.FAILED)
|
||||
|
||||
|
|
@ -416,7 +416,7 @@ class CreateBackupTests(TransactionTestCase):
|
|||
self.proxy.backup_targets.return_value = None
|
||||
self.proxy.backup_result.return_value = (False, "operation aborted")
|
||||
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):
|
||||
op = self.submit()
|
||||
|
|
@ -432,7 +432,7 @@ class CreateBackupTests(TransactionTestCase):
|
|||
with self.assertRaises(Cancelled):
|
||||
self.run_job(op)
|
||||
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)
|
||||
|
||||
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
|
||||
self.assertEqual(outcome.state, Operation.FAILED)
|
||||
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)
|
||||
|
||||
def test_progress_counts_the_copied_disks(self):
|
||||
|
|
|
|||
|
|
@ -98,6 +98,7 @@ class ImportTests(TransactionTestCase):
|
|||
self.assertEqual((backup.state, backup.target, backup.instance, backup.vm_name, backup.consistency),
|
||||
(Backup.READY, self.target, self.vm, "vm1", "frozen"))
|
||||
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(self.read()["added"], 0)
|
||||
self.assertEqual(Backup.objects.count(), 2)
|
||||
|
|
|
|||
|
|
@ -51,8 +51,9 @@ class BackupModelTests(TestCase):
|
|||
self.assertIsNone(self.target.pool_on(self.compute))
|
||||
|
||||
def test_prefix(self):
|
||||
backup = Backup(uuid=UUID("00000000-0000-4000-8000-000000000001"))
|
||||
self.assertEqual(backup.prefix, "wvc-00000000-0000-4000-8000-000000000001")
|
||||
target = BackupTarget.objects.create(name="nfs-p")
|
||||
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):
|
||||
self.assertEqual(backup_target_key(3), "backup_target:3")
|
||||
|
|
|
|||
|
|
@ -2,6 +2,7 @@
|
|||
|
||||
import hashlib
|
||||
import os
|
||||
import re
|
||||
|
||||
import libvirt
|
||||
from django.utils.translation import gettext_noop
|
||||
|
|
@ -213,9 +214,15 @@ class wvmBackup(wvmInstance):
|
|||
for name in sorted(pool.listVolumes()) if not name.startswith(".")}
|
||||
|
||||
|
||||
def backup_file_names(uuid, disks, nvram):
|
||||
"""The names of a backup's files in the target pool, from its UUID only."""
|
||||
prefix = f"wvc-{uuid}"
|
||||
def backup_prefix(vm_name, uuid):
|
||||
"""The start of a backup's file names in the target pool: its VM's name,
|
||||
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 {
|
||||
"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,
|
||||
|
|
@ -267,9 +274,12 @@ def volume_exists(pool, name):
|
|||
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):
|
||||
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):
|
||||
|
|
|
|||
|
|
@ -9,7 +9,7 @@ import libvirt
|
|||
from lxml import etree
|
||||
|
||||
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
|
||||
|
||||
GIB = 1024**3
|
||||
|
|
@ -208,18 +208,33 @@ class BackupPlanTestCase(unittest.TestCase):
|
|||
class FilesTestCase(unittest.TestCase):
|
||||
def test_file_names(self):
|
||||
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"}]
|
||||
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"},
|
||||
"nvram": f"wvc-{uuid}-nvram.fd",
|
||||
"tpm": f"wvc-{uuid}-tpm-",
|
||||
"domain": f"wvc-{uuid}-domain.xml",
|
||||
"manifest": f"wvc-{uuid}-manifest.json",
|
||||
"disks": {"vda": f"{prefix}-vda.qcow2", "vdb": f"{prefix}-vdb.raw"},
|
||||
"nvram": f"{prefix}-nvram.fd",
|
||||
"tpm": f"{prefix}-tpm-",
|
||||
"domain": f"{prefix}-domain.xml",
|
||||
"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):
|
||||
# 2 x 10 GiB plus max(10 % of it, 1 GiB) = 22 GiB
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue