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

feat(vmbackups): restore a backup's TPM state

The restore writes the backup's TPM state files into libvirt's swtpm
directory of the new VM's UUID before the VM is defined; libvirt makes
them swtpm's when the VM starts and keeps the state, so the guest keeps
its TPM identity. A file name from a manifest that is not a plain name is
refused before anything is made, a host without swtpm is refused, and
recovery of a restore that did not define its VM removes the files.
This commit is contained in:
catborise 2026-11-17 13:51:32 +03:00
parent 52b6096efe
commit da52a23ed8
10 changed files with 253 additions and 42 deletions

View file

@ -574,7 +574,8 @@ def _check_files(conn, pool, files):
class RestoreBackup(Kind):
"""A ready backup made a new VM on a compute that has the target's pool:
its disks copied from the target into one of the compute's pools, its
NVRAM file into libvirt's directory, then the VM defined, last."""
NVRAM file and TPM state into libvirt's directories, then the VM
defined, last."""
name = "backup.restore"
label = _("Restore backup")
@ -641,6 +642,10 @@ class RestoreBackup(Kind):
# the VM's own file in libvirt's directory; libvirt makes it from the template when none was kept
nvram = os.path.join(NVRAM_DIR, p["name"] + "_VARS" + os.path.splitext(old_nvram)[1]) if old_nvram else None
macs = [get_random_mac_address() for _nic in tree.findall("devices/interface")]
tpm_files = list(backup.files.filter(role=BackupFile.TPM).order_by("dev"))
for f in tpm_files: # a manifest read from a target names them: a file of the VM's directory only
if not f.dev or "/" in f.dev or f.dev.startswith("."):
raise util.OperationError(_("The backup's TPM state file %(name)s is not a plain file name"), name=f.dev)
if nvram:
# a file of that name may be a removed VM's kept one, or another VM's: never taken, never removed
with conn._nvram_pool() as nvram_pool:
@ -648,7 +653,7 @@ class RestoreBackup(Kind):
raise util.OperationError(_("The NVRAM file %(path)s exists already"), path=nvram)
# what the VM is made of, before anything is made: recovery finds and removes it by these
ctx.record_intent(nvram=nvram, macs=macs)
ctx.record_intent(nvram=nvram, macs=macs, tpm=bool(tpm_files))
ctx.set_phase(_("Copying disks"))
storage = wvmStorage(compute.hostname, compute.login, compute.password, compute.type, p["pool"])
paths = {}
@ -663,6 +668,11 @@ class RestoreBackup(Kind):
with conn._nvram_pool() as nvram_pool:
# QEMU's, as the clone's copy: qemu may run without libvirt changing a file's owner
conn.upload_volume(nvram_pool, os.path.basename(nvram), data, owner=_owner(), mode="0600")
if tpm_files:
with conn._tpm_pool(op.intent["uuid"], build=True) as tpm_pool:
for f in tpm_files:
# root's: libvirt makes the state directory swtpm's when the VM starts
conn.upload_volume(tpm_pool, f.dev, get_file(conn, tpool, f.volume), owner=(0, 0), mode="0600")
compute.refuse_new_vms() # again: the host may have gone in maintenance while the disks were copied
xml = restore_definition(definition, name=p["name"], uuid=op.intent["uuid"], macs=macs,
@ -711,6 +721,11 @@ class RestoreBackup(Kind):
if nvram := op.intent.get("nvram"):
with conn._nvram_pool() as nvram_pool:
remove_files(nvram_pool, [os.path.basename(nvram)])
if op.intent.get("tpm"):
# the new UUID's directory: only this job wrote in it (its empty directories stay)
with conn._tpm_pool(op.intent["uuid"]) as tpm_pool:
if tpm_pool is not None:
remove_files(tpm_pool, tpm_pool.listVolumes())
ended = Operation.CANCELLED if op.cancel_requested else Operation.FAILED
return Outcome(ended, error=say(_("The VM was not defined; its copies were removed")))

View file

@ -209,6 +209,61 @@ class RestoreTests(TransactionTestCase):
self.assertIn("vm1-restored-vda.qcow2", outcome.error[0]["values"]["volumes"])
self.assertEqual(self.removed, [])
def with_tpm(self, name="tpm2-00.permall"):
volume = f"{self.backup.prefix}-tpm-{name}"
self.files[volume] = b"state"
BackupFile.objects.create(backup=self.backup, role=BackupFile.TPM, dev=name, volume=volume, size=5,
sha256=hashlib.sha256(b"state").hexdigest())
self.tpm_pool = MagicMock()
self.tpm_pool.listVolumes.return_value = [name]
self.conn._tpm_pool.side_effect = lambda uuid, build=False: contextlib.nullcontext(self.tpm_pool)
def test_the_tpm_state_goes_to_the_new_vms_directory_before_it_is_defined(self):
self.with_tpm()
self.conn.upload_volume.side_effect = lambda *a, **kw: self.conn.wvm.defineXML.assert_not_called()
op = self.submit()
self.run_job(op)
self.assertTrue(op.intent["tpm"])
self.conn._tpm_pool.assert_called_once_with(op.intent["uuid"], build=True)
# root's: libvirt makes the state directory swtpm's when the VM starts
self.conn.upload_volume.assert_called_with(self.tpm_pool, "tpm2-00.permall", b"state", owner=(0, 0), mode="0600")
self.conn.wvm.defineXML.assert_called_once()
def refused_tpm_name(self, name):
self.with_tpm(name)
with self.assertRaisesMessage(OperationError, name):
self.run_job(self.submit())
self.storage.clone_volume.assert_not_called()
self.conn._tpm_pool.assert_not_called()
def test_a_tpm_file_name_that_is_a_path_is_refused_before_anything_is_made(self):
self.refused_tpm_name("../../qemu/nvram/x")
def test_a_hidden_tpm_file_name_is_refused(self):
self.refused_tpm_name(".lock")
def test_recovery_removes_the_tpm_files_of_a_vm_not_defined(self):
self.with_tpm()
self.conn.wvm.defineXML.side_effect = RuntimeError("worker gone")
op = self.submit()
with self.assertRaises(RuntimeError):
self.run_job(op)
op.refresh_from_db()
self.conn._tpm_pool.reset_mock()
self.assertEqual(RestoreBackup().reconcile(op).state, Operation.FAILED)
self.conn._tpm_pool.assert_called_once_with(op.intent["uuid"])
self.assertIn("tpm2-00.permall", self.removed)
def test_recovery_before_the_tpm_directory_was_made(self):
self.with_tpm()
self.conn._tpm_pool.side_effect = lambda uuid, build=False: contextlib.nullcontext(None)
self.conn.upload_volume.side_effect = RuntimeError("worker gone") # the NVRAM file's
op = self.submit()
with self.assertRaises(RuntimeError):
self.run_job(op)
op.refresh_from_db()
self.assertEqual(RestoreBackup().reconcile(op).state, Operation.FAILED)
def test_the_nvram_file_is_qemus(self):
self.run_job(self.submit())
self.assertEqual(self.conn.upload_volume.call_args.kwargs, {"owner": _owner(), "mode": "0600"})