mirror of
https://github.com/retspen/webvirtcloud
synced 2026-12-02 17:06:09 +00:00
feat(vmbackups): back up a shut-off VM's TPM state
A VM with the panel's emulated TPM 2.0 is backed up when it is shut off: each state file of libvirt's swtpm directory for the VM, read through a transient pool on it, becomes a small file of the backup (role tpm), written and read back like the NVRAM file. A running or paused VM with a TPM is refused, and so is a TPM with its own settings (encryption, a state path, another backend). The manifest says whether the TPM state was copied or never written.
This commit is contained in:
parent
a145c07601
commit
52b6096efe
11 changed files with 371 additions and 166 deletions
|
|
@ -54,14 +54,19 @@ class wvmBackup(wvmInstance):
|
|||
def backup_plan(self):
|
||||
"""What a backup of the VM copies, from its persistent definition:
|
||||
{"definition", "disks": [{dev, path, pool, format, capacity}],
|
||||
"nvram": path or None, "left_out": [{dev, why}]}. Refuses, naming
|
||||
"nvram": path or None, "tpm": whether it has a TPM (shut off: its
|
||||
state is read by the job), "left_out": [{dev, why}]}. Refuses, naming
|
||||
why, a VM whose backup could not be restored as it is."""
|
||||
tree = etree.fromstring(self._XMLDesc(PERSISTENT_XML))
|
||||
name = self.instance.name()
|
||||
if self.instance.hasManagedSaveImage(0):
|
||||
raise OperationError(gettext_noop("%(vm)s has a saved state; start it or remove the saved state first"), vm=name)
|
||||
if tree.find("devices/tpm") is not None:
|
||||
raise OperationError(gettext_noop("%(vm)s has TPM state; TPM backups come later"), vm=name)
|
||||
tpm = self.get_tpm()
|
||||
if tpm == "custom":
|
||||
raise OperationError(gettext_noop("%(vm)s has a TPM of its own settings (encryption, a state path or "
|
||||
"another backend); it cannot be backed up"), vm=name)
|
||||
if tpm and self.instance.state()[0] != libvirt.VIR_DOMAIN_SHUTOFF:
|
||||
raise OperationError(gettext_noop("%(vm)s has TPM state; shut it down to back it up"), vm=name)
|
||||
if tree.find("devices/filesystem") is not None:
|
||||
raise OperationError(gettext_noop("%(vm)s shares a host directory (filesystem); it cannot be backed up"), vm=name)
|
||||
if tree.xpath("os/kernel|os/initrd|os/dtb"):
|
||||
|
|
@ -112,7 +117,8 @@ class wvmBackup(wvmInstance):
|
|||
if nvram and os.path.dirname(nvram) != NVRAM_DIR:
|
||||
raise OperationError(gettext_noop("The NVRAM file %(path)s is not in libvirt's NVRAM directory %(dir)s and cannot be copied"),
|
||||
path=nvram, dir=NVRAM_DIR)
|
||||
return {"definition": etree.tostring(tree).decode(), "disks": disks, "nvram": nvram, "left_out": left_out}
|
||||
return {"definition": etree.tostring(tree).decode(), "disks": disks, "nvram": nvram, "tpm": bool(tpm),
|
||||
"left_out": left_out}
|
||||
|
||||
def copy_disk_offline(self, disk, pool, name, owner_uid, owner_gid):
|
||||
"""A shut-off VM's disk copied into the target pool, flat, in its
|
||||
|
|
@ -140,6 +146,15 @@ class wvmBackup(wvmInstance):
|
|||
vol = self._find_volume(pool, os.path.basename(path))
|
||||
return None if vol is None else self.download_volume(vol)
|
||||
|
||||
def read_tpm(self):
|
||||
"""The shut-off VM's TPM state files: {name: bytes}, {} when it never
|
||||
started. swtpm's .lock is not state."""
|
||||
with self._tpm_pool(self.instance.UUIDString()) as pool:
|
||||
if pool is None:
|
||||
return {}
|
||||
return {name: self.download_volume(pool.storageVolLookupByName(name))
|
||||
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."""
|
||||
|
|
@ -147,6 +162,7 @@ def backup_file_names(uuid, disks, nvram):
|
|||
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,
|
||||
"tpm": f"{prefix}-tpm-", # and the state file's name
|
||||
"domain": f"{prefix}-domain.xml",
|
||||
"manifest": f"{prefix}-manifest.json",
|
||||
}
|
||||
|
|
@ -166,12 +182,12 @@ def check_target_space(pool, disks, free_percent, free_min_gib):
|
|||
pool=pool.name(), free=free / 1024**3, size=needed / 1024**3, percent=free_percent, minimum=free_min_gib)
|
||||
|
||||
|
||||
def put_file(conn, pool, name, data, owner):
|
||||
def put_file(conn, pool, name, data, owner, mode="0644"):
|
||||
"""Writes a small file of a backup into the target pool as owner (uid,
|
||||
gid), replacing one of that name, and reads it back. Returns its
|
||||
SHA-256."""
|
||||
gid) with mode, replacing one of that name, and reads it back. Returns
|
||||
its SHA-256."""
|
||||
remove_files(pool, [name])
|
||||
vol = conn.upload_volume(pool, name, data, owner=owner)
|
||||
vol = conn.upload_volume(pool, name, data, owner=owner, mode=mode)
|
||||
if conn.download_volume(vol) != data:
|
||||
vol.delete(0)
|
||||
raise OperationError(gettext_noop("The file %(name)s read back from the backup target differs from the one written"), name=name)
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
from django.utils.translation import gettext_noop
|
||||
import contextlib
|
||||
import errno
|
||||
import io
|
||||
import logging
|
||||
import os
|
||||
|
|
@ -188,6 +189,8 @@ request_finished.connect(_request_finished, dispatch_uid="vrtManager.connection.
|
|||
|
||||
# libvirt's per-host directory of the VMs' UEFI variables (NVRAM)
|
||||
NVRAM_DIR = "/var/lib/libvirt/qemu/nvram"
|
||||
# libvirt's per-host directory of the emulated TPMs' state: <vm uuid>/tpm2/
|
||||
SWTPM_DIR = "/var/lib/libvirt/swtpm"
|
||||
# the files and devices of a definition's disks that may grow from others; a
|
||||
# raw one does not
|
||||
UNREAD_DISKS = etree.XPath("devices/disk[@device='disk'][not(driver/@type='raw')]/source/@file|"
|
||||
|
|
@ -1072,6 +1075,35 @@ class wvmConnect(object):
|
|||
with contextlib.suppress(libvirtError):
|
||||
pool.destroy()
|
||||
|
||||
@contextlib.contextmanager
|
||||
def _tpm_pool(self, vm_uuid, build=False):
|
||||
"""An active, refreshed pool on the TPM 2.0 state directory of the VM
|
||||
vm_uuid, destroyed after; None when the directory does not exist (the
|
||||
VM never started) and build is false; build makes it. Used only by
|
||||
the worker's jobs that hold the VM: the pool a stopped worker left on
|
||||
the directory is taken, as libvirt refuses a second one."""
|
||||
path = f"{SWTPM_DIR}/{vm_uuid}/tpm2"
|
||||
pool = self.pool_at(path)
|
||||
if pool is not None:
|
||||
pool.refresh(0)
|
||||
else:
|
||||
try:
|
||||
pool = self.wvm.storagePoolCreateXML(
|
||||
f"<pool type='dir'><name>webvirtcloud-tpm-{uuid.uuid4().hex[:8]}</name>"
|
||||
f"<target><path>{path}</path></target></pool>",
|
||||
libvirt.VIR_STORAGE_POOL_CREATE_WITH_BUILD if build else 0,
|
||||
)
|
||||
except libvirtError as err:
|
||||
if build or err.get_error_code() != libvirt.VIR_ERR_SYSTEM_ERROR or err.get_int1() != errno.ENOENT:
|
||||
raise
|
||||
yield None
|
||||
return
|
||||
try:
|
||||
yield pool
|
||||
finally:
|
||||
with contextlib.suppress(libvirtError):
|
||||
pool.destroy()
|
||||
|
||||
def upload_volume(self, pool, name, data, owner=None, mode="0644"):
|
||||
"""A new raw volume in pool holding data, written through a libvirt
|
||||
stream, which every connection type carries; owner: (uid, gid) of
|
||||
|
|
|
|||
|
|
@ -2,6 +2,7 @@
|
|||
names and space, and the small files' upload read back."""
|
||||
|
||||
import unittest
|
||||
from contextlib import nullcontext
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
import libvirt
|
||||
|
|
@ -13,6 +14,7 @@ from vrtManager.instance import PERSISTENT_XML
|
|||
GIB = 1024**3
|
||||
QCOW = "<disk type='file' device='disk'><driver name='qemu' type='qcow2'/><source file='/pool/a.qcow2'/><target dev='vda'/></disk>"
|
||||
RAW = "<disk type='file' device='disk'><driver name='qemu' type='raw'/><source file='/pool/b.img'/><target dev='vdb'/></disk>"
|
||||
TPM = "<tpm model='tpm-crb'><backend type='emulator' version='2.0'/></tpm>"
|
||||
CDROM = "<disk type='file' device='cdrom'><source file='/iso/x.iso'/><target dev='sda'/></disk>"
|
||||
|
||||
|
||||
|
|
@ -34,6 +36,7 @@ def proxy(xml=None, live=None, state=libvirt.VIR_DOMAIN_SHUTOFF, managed_save=Fa
|
|||
p.wvm = MagicMock()
|
||||
p.instance = MagicMock()
|
||||
p.instance.name.return_value = "vm1"
|
||||
p.instance.UUIDString.return_value = "u"
|
||||
p.instance.state.return_value = [state, 0]
|
||||
p.instance.hasManagedSaveImage.return_value = managed_save
|
||||
persistent = xml or domain()
|
||||
|
|
@ -103,7 +106,12 @@ class BackupPlanTestCase(unittest.TestCase):
|
|||
"host device": (QCOW + "<hostdev mode='subsystem' type='pci'/>", ("host device",)),
|
||||
"host device NIC": (QCOW + "<interface type='hostdev'><mac address='52:54:00:00:00:09'/></interface>",
|
||||
("host device",)),
|
||||
"tpm": (QCOW + "<tpm model='tpm-crb'><backend type='emulator'/></tpm>", ("vm1", "TPM")),
|
||||
"encrypted tpm": (QCOW + "<tpm model='tpm-crb'><backend type='emulator' version='2.0'>"
|
||||
"<encryption secret='33333333-3333-4333-8333-333333333333'/></backend></tpm>", ("vm1", "TPM")),
|
||||
"tpm state path": (QCOW + "<tpm model='tpm-crb'><backend type='emulator' version='2.0'>"
|
||||
"<source type='dir' path='/srv/tpm'/></backend></tpm>", ("vm1", "TPM")),
|
||||
"host tpm": (QCOW + "<tpm model='tpm-tis'><backend type='passthrough'><device path='/dev/tpm0'/></backend></tpm>",
|
||||
("vm1", "TPM")),
|
||||
}
|
||||
for name, (devices, texts) in cases.items():
|
||||
with self.subTest(name):
|
||||
|
|
@ -112,6 +120,33 @@ class BackupPlanTestCase(unittest.TestCase):
|
|||
with self.subTest(tag):
|
||||
self.refused(proxy(domain(os_extra=f"<{tag}>/boot/x</{tag}>")), "kernel")
|
||||
|
||||
def test_a_shut_off_vms_tpm_is_backed_up_and_its_state_read_by_the_job(self):
|
||||
p = proxy(domain(QCOW + TPM))
|
||||
p._tpm_pool = MagicMock()
|
||||
self.assertTrue(p.backup_plan()["tpm"])
|
||||
p._tpm_pool.assert_not_called() # the plan runs in pages too: only the worker reads the state
|
||||
self.assertFalse(proxy(domain(QCOW)).backup_plan()["tpm"])
|
||||
|
||||
def test_the_tpm_state_files_are_read_without_swtpms_lock(self):
|
||||
p = proxy(domain(QCOW + TPM))
|
||||
state = MagicMock()
|
||||
state.listVolumes.return_value = [".lock", "tpm2-00.permall"]
|
||||
p._tpm_pool = MagicMock(return_value=nullcontext(state))
|
||||
p.download_volume = MagicMock(return_value=b"state")
|
||||
self.assertEqual(p.read_tpm(), {"tpm2-00.permall": b"state"})
|
||||
p._tpm_pool.assert_called_once_with("u")
|
||||
state.storageVolLookupByName.assert_called_once_with("tpm2-00.permall")
|
||||
|
||||
def test_a_tpm_that_never_started_has_no_files(self):
|
||||
p = proxy(domain(QCOW + TPM))
|
||||
p._tpm_pool = MagicMock(return_value=nullcontext(None))
|
||||
self.assertEqual(p.read_tpm(), {})
|
||||
|
||||
def test_a_running_or_paused_vm_with_a_tpm_is_refused(self):
|
||||
for state in (libvirt.VIR_DOMAIN_RUNNING, libvirt.VIR_DOMAIN_PAUSED):
|
||||
with self.subTest(state):
|
||||
self.refused(proxy(domain(QCOW + TPM), state=state), "vm1", "TPM", "shut it down")
|
||||
|
||||
def test_a_saved_state_is_refused(self):
|
||||
self.refused(proxy(managed_save=True), "saved state")
|
||||
|
||||
|
|
@ -145,6 +180,7 @@ class FilesTestCase(unittest.TestCase):
|
|||
{
|
||||
"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",
|
||||
},
|
||||
|
|
@ -181,7 +217,42 @@ class FilesTestCase(unittest.TestCase):
|
|||
)
|
||||
old.delete.assert_called_once_with(0)
|
||||
# written as QEMU's user: an NFS export that squashes root refuses root's files
|
||||
conn.upload_volume.assert_called_once_with(pool, "wvc-x-domain.xml", b"data", owner=(107, 108))
|
||||
conn.upload_volume.assert_called_once_with(pool, "wvc-x-domain.xml", b"data", owner=(107, 108), mode="0644")
|
||||
|
||||
def test_a_tpm_directory_that_does_not_exist_gives_no_pool(self):
|
||||
import errno
|
||||
|
||||
from vrtManager.connection import wvmConnect
|
||||
|
||||
conn = wvmConnect.__new__(wvmConnect)
|
||||
conn.wvm = MagicMock()
|
||||
missing = libvirt.libvirtError("cannot open directory")
|
||||
missing.err = (libvirt.VIR_ERR_SYSTEM_ERROR, 0, "", 2, None, None, None, errno.ENOENT, -1)
|
||||
conn.wvm.storagePoolCreateXML.side_effect = missing
|
||||
conn.wvm.listAllStoragePools.return_value = []
|
||||
with conn._tpm_pool("u") as pool:
|
||||
self.assertIsNone(pool)
|
||||
self.assertIn("/var/lib/libvirt/swtpm/u/tpm2", conn.wvm.storagePoolCreateXML.call_args.args[0])
|
||||
conn.wvm.listAllStoragePools.return_value = []
|
||||
with self.assertRaises(libvirt.libvirtError), conn._tpm_pool("u", build=True):
|
||||
pass
|
||||
missing.err = (libvirt.VIR_ERR_SYSTEM_ERROR, 0, "", 2, None, None, None, errno.EACCES, -1)
|
||||
with self.assertRaises(libvirt.libvirtError), conn._tpm_pool("u"):
|
||||
pass
|
||||
|
||||
def test_a_tpm_pool_a_stopped_worker_left_is_taken_and_destroyed(self):
|
||||
from vrtManager.connection import wvmConnect
|
||||
|
||||
conn = wvmConnect.__new__(wvmConnect)
|
||||
conn.wvm = MagicMock()
|
||||
left = MagicMock()
|
||||
left.XMLDesc.return_value = "<pool><target><path>/var/lib/libvirt/swtpm/u/tpm2</path></target></pool>"
|
||||
conn.wvm.listAllStoragePools.return_value = [left]
|
||||
with conn._tpm_pool("u") as pool:
|
||||
self.assertIs(pool, left)
|
||||
conn.wvm.storagePoolCreateXML.assert_not_called()
|
||||
left.refresh.assert_called_once_with(0)
|
||||
left.destroy.assert_called_once_with()
|
||||
|
||||
def test_upload_volume_sets_the_owner(self):
|
||||
from lxml import etree
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue