diff --git a/README.md b/README.md index 9e14b612..97929333 100644 --- a/README.md +++ b/README.md @@ -588,9 +588,9 @@ and follow [Moving to a new machine](#moving-to-a-new-machine) with that `b` (le ### VM backups -Superusers back a VM up from its **Backups** tab into a backup target: a `dir` or `netfs` storage pool made on each host that sees it, added on **Backups → Backup targets** (another host's pool is accepted only when it is the same directory). A running VM keeps running: its disks are copied from one instant, with its file systems frozen for it when the guest agent answers; a shut-off VM's disks are copied as they are. A backup holds the disks, the VM's definition, its UEFI variables and a manifest. It is restored as a new VM, with its network disconnected unless asked, on a host that has the target's pool. After the panel's database is lost, add the target again and use **Read backups from target**. +Superusers back a VM up from its **Backups** tab into a backup target: a `dir` or `netfs` storage pool made on each host that sees it, added on **Backups → Backup targets** (another host's pool is accepted only when it is the same directory). A running VM keeps running: its disks are copied from one instant, with its file systems frozen for it when the guest agent answers; a shut-off VM's disks are copied as they are. A backup holds the disks, the VM's definition, its UEFI variables, its TPM state and a manifest; a VM with a TPM is backed up shut off. It is restored as a new VM, with its network disconnected unless asked, on a host that has the target's pool; the new VM gets the backed-up VM's TPM state. After the panel's database is lost, add the target again and use **Read backups from target**. -VMs with TPM state, host devices, shared host directories, or encrypted or non-file disks are not backed up; CD-ROMs are left out. +VMs with a TPM of their own settings (encryption, a state path), host devices, shared host directories, or encrypted or non-file disks are not backed up; CD-ROMs are left out. **Backups → Schedules** backs VMs up every day: chosen VMs or every VM of a compute, into a target, at a time in the panel's time zone (`TZ`), keeping the newest backups of each VM up to a number. The job worker starts each VM's backup within 6 hours of the time, one copy at a time per target, and waits for a host in maintenance; a VM not started in that window waits for the next day. Older backups of a schedule are deleted; backups taken by hand are not. Each target is checked once a day: a backup whose files are gone is marked missing. diff --git a/locale/tr/LC_MESSAGES/django.mo b/locale/tr/LC_MESSAGES/django.mo index 66ce0f8f..28a122ca 100644 Binary files a/locale/tr/LC_MESSAGES/django.mo and b/locale/tr/LC_MESSAGES/django.mo differ diff --git a/locale/tr/LC_MESSAGES/django.po b/locale/tr/LC_MESSAGES/django.po index 1d8298f8..84e10380 100644 --- a/locale/tr/LC_MESSAGES/django.po +++ b/locale/tr/LC_MESSAGES/django.po @@ -11,7 +11,7 @@ msgid "" msgstr "" "Project-Id-Version: PACKAGE VERSION\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2026-11-17 10:54+0000\n" +"POT-Creation-Date: 2026-11-17 10:55+0000\n" "PO-Revision-Date: 2020-11-04 12:00+0000\n" "Last-Translator: catborise , 2020\n" "Language-Team: Turkish (https://www.transifex.com/catborise/teams/110663/tr/)\n" @@ -3458,7 +3458,7 @@ msgid "Clone VM" msgstr "Sanal makineyi klonla" #: instances/jobs.py:656 instances/jobs.py:663 instances/jobs.py:1005 -#: vmbackups/jobs.py:243 vmbackups/jobs.py:652 +#: vmbackups/jobs.py:243 vmbackups/jobs.py:657 msgid "Copying disks" msgstr "Diskler kopyalanıyor" @@ -3542,12 +3542,12 @@ msgstr "" msgid "Each network card needs a network" msgstr "Her ağ kartının bir ağı olmalı" -#: instances/jobs.py:868 vrtManager/backup.py:276 vrtManager/instance.py:2871 +#: instances/jobs.py:868 vrtManager/backup.py:283 vrtManager/instance.py:2871 #, python-format msgid "This host has no network %(name)s" msgstr "Bu sunucuda %(name)s ağı yok" -#: instances/jobs.py:870 vrtManager/backup.py:280 vrtManager/instance.py:2873 +#: instances/jobs.py:870 vrtManager/backup.py:287 vrtManager/instance.py:2873 #, python-format msgid "This host has no network filter %(name)s" msgstr "Bu sunucuda %(name)s ağ filtresi yok" @@ -9928,35 +9928,40 @@ msgstr "Yedeğin %(name)s dosyası hedefte yok" msgid "The backup's file %(name)s differs from the one written" msgstr "Yedeğin %(name)s dosyası yazılandan farklı" -#: vmbackups/jobs.py:580 vmbackups/templates/vmbackups/restore.html:7 +#: vmbackups/jobs.py:581 vmbackups/templates/vmbackups/restore.html:7 msgid "Restore backup" msgstr "Yedeği geri yükle" -#: vmbackups/jobs.py:593 +#: vmbackups/jobs.py:594 msgid "Only a ready backup is restored" msgstr "Yalnızca hazır bir yedek geri yüklenir" -#: vmbackups/jobs.py:623 +#: vmbackups/jobs.py:624 #, python-format msgid "A VM named %(name)s exists on %(compute)s" msgstr "%(compute)s üzerinde %(name)s adlı bir sanal makine var" -#: vmbackups/jobs.py:631 +#: vmbackups/jobs.py:632 #, python-format msgid "This host has no active directory storage pool %(pool)s" msgstr "Bu sunucuda %(pool)s adlı etkin bir dizin depolama havuzu yok" #: vmbackups/jobs.py:648 #, python-format +msgid "The backup's TPM state file %(name)s is not a plain file name" +msgstr "Yedeğin TPM durum dosyası %(name)s düz bir dosya adı değil" + +#: vmbackups/jobs.py:653 +#, python-format msgid "The NVRAM file %(path)s exists already" msgstr "%(path)s NVRAM dosyası zaten var" -#: vmbackups/jobs.py:679 +#: vmbackups/jobs.py:689 #, python-format msgid "The VM was restored; it did not start: %(error)s" msgstr "Sanal makine geri yüklendi; başlamadı: %(error)s" -#: vmbackups/jobs.py:701 +#: vmbackups/jobs.py:711 #, python-format msgid "" "A disk was being copied when the job stopped; check this volume, then resolve" @@ -9965,7 +9970,7 @@ msgstr "" "İş durduğunda bir disk kopyalanıyordu; bu birimi kontrol edin, sonra bu işi " "çözün: %(volumes)s" -#: vmbackups/jobs.py:706 +#: vmbackups/jobs.py:716 #, python-format msgid "" "Storage pool %(pool)s is not active; the restore's copies in it are removed " @@ -9974,15 +9979,15 @@ msgstr "" "%(pool)s depolama havuzu etkin değil; geri yüklemenin içindeki kopyaları " "havuz etkin olunca kaldırılır" -#: vmbackups/jobs.py:715 +#: vmbackups/jobs.py:730 msgid "The VM was not defined; its copies were removed" msgstr "Sanal makine tanımlanmadı; kopyaları kaldırıldı" -#: vmbackups/jobs.py:734 vmbackups/templates/vmbackups/target.html:18 +#: vmbackups/jobs.py:749 vmbackups/templates/vmbackups/target.html:18 msgid "Read backups from target" msgstr "Yedekleri hedeften oku" -#: vmbackups/jobs.py:782 +#: vmbackups/jobs.py:797 #, python-format msgid "" "Not read, as a file of the backup is missing, changed or unreadable: " @@ -9991,11 +9996,11 @@ msgstr "" "Yedeğin bir dosyası eksik, değişmiş ya da okunamaz olduğu için okunmadı: " "%(names)s" -#: vmbackups/jobs.py:798 +#: vmbackups/jobs.py:813 msgid "Check backup target" msgstr "Yedek hedefini denetle" -#: vmbackups/jobs.py:825 +#: vmbackups/jobs.py:840 #, python-format msgid "Files of these backups are missing from the target: %(backups)s" msgstr "Şu yedeklerin dosyaları hedefte yok: %(backups)s" @@ -10471,7 +10476,12 @@ msgstr "" msgid "This host has no firmware %(loader)s" msgstr "Bu sunucuda %(loader)s firmware'i yok" -#: vrtManager/backup.py:278 +#: vrtManager/backup.py:280 +#, python-format +msgid "This host offers no TPM 2.0 %(model)s: install swtpm on it" +msgstr "Bu ana makine TPM 2.0 %(model)s sunmuyor: üzerine swtpm kurun" + +#: vrtManager/backup.py:285 #, python-format msgid "This host has no bridge %(name)s" msgstr "Bu sunucuda %(name)s köprüsü yok" diff --git a/locale/zh/LC_MESSAGES/django.mo b/locale/zh/LC_MESSAGES/django.mo index 954096b6..839b50aa 100644 Binary files a/locale/zh/LC_MESSAGES/django.mo and b/locale/zh/LC_MESSAGES/django.mo differ diff --git a/locale/zh/LC_MESSAGES/django.po b/locale/zh/LC_MESSAGES/django.po index d81a2871..5694fc45 100644 --- a/locale/zh/LC_MESSAGES/django.po +++ b/locale/zh/LC_MESSAGES/django.po @@ -7,7 +7,7 @@ msgid "" msgstr "" "Project-Id-Version: \n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2026-11-17 10:54+0000\n" +"POT-Creation-Date: 2026-11-17 10:55+0000\n" "PO-Revision-Date: \n" "Last-Translator: \n" "Language-Team: \n" @@ -3288,7 +3288,7 @@ msgid "Clone VM" msgstr "克隆虚拟机" #: instances/jobs.py:656 instances/jobs.py:663 instances/jobs.py:1005 -#: vmbackups/jobs.py:243 vmbackups/jobs.py:652 +#: vmbackups/jobs.py:243 vmbackups/jobs.py:657 msgid "Copying disks" msgstr "正在复制磁盘" @@ -3358,12 +3358,12 @@ msgstr "镜像已存在。请检查卷或更改虚拟机名称" msgid "Each network card needs a network" msgstr "每个网卡都需要一个网络" -#: instances/jobs.py:868 vrtManager/backup.py:276 vrtManager/instance.py:2871 +#: instances/jobs.py:868 vrtManager/backup.py:283 vrtManager/instance.py:2871 #, python-format msgid "This host has no network %(name)s" msgstr "此主机没有网络 %(name)s" -#: instances/jobs.py:870 vrtManager/backup.py:280 vrtManager/instance.py:2873 +#: instances/jobs.py:870 vrtManager/backup.py:287 vrtManager/instance.py:2873 #, python-format msgid "This host has no network filter %(name)s" msgstr "此主机没有网络过滤器 %(name)s" @@ -9356,68 +9356,73 @@ msgstr "目标中缺少备份文件 %(name)s" msgid "The backup's file %(name)s differs from the one written" msgstr "备份文件 %(name)s 与写入的不同" -#: vmbackups/jobs.py:580 vmbackups/templates/vmbackups/restore.html:7 +#: vmbackups/jobs.py:581 vmbackups/templates/vmbackups/restore.html:7 msgid "Restore backup" msgstr "恢复备份" -#: vmbackups/jobs.py:593 +#: vmbackups/jobs.py:594 msgid "Only a ready backup is restored" msgstr "只能恢复就绪的备份" -#: vmbackups/jobs.py:623 +#: vmbackups/jobs.py:624 #, python-format msgid "A VM named %(name)s exists on %(compute)s" msgstr "%(compute)s 上已存在名为 %(name)s 的虚拟机" -#: vmbackups/jobs.py:631 +#: vmbackups/jobs.py:632 #, python-format msgid "This host has no active directory storage pool %(pool)s" msgstr "此主机没有名为 %(pool)s 的活动目录存储池" #: vmbackups/jobs.py:648 #, python-format +msgid "The backup's TPM state file %(name)s is not a plain file name" +msgstr "备份的 TPM 状态文件 %(name)s 不是普通文件名" + +#: vmbackups/jobs.py:653 +#, python-format msgid "The NVRAM file %(path)s exists already" msgstr "NVRAM 文件 %(path)s 已存在" -#: vmbackups/jobs.py:679 +#: vmbackups/jobs.py:689 #, python-format msgid "The VM was restored; it did not start: %(error)s" msgstr "虚拟机已恢复;但未能启动:%(error)s" -#: vmbackups/jobs.py:701 +#: vmbackups/jobs.py:711 #, python-format msgid "" "A disk was being copied when the job stopped; check this volume, then resolve" " this job: %(volumes)s" msgstr "作业停止时正在复制磁盘;请检查此卷,然后解决此作业:%(volumes)s" -#: vmbackups/jobs.py:706 +#: vmbackups/jobs.py:716 #, python-format msgid "" "Storage pool %(pool)s is not active; the restore's copies in it are removed " "when it is" msgstr "存储池 %(pool)s 未激活;其中恢复的副本将在其激活后删除" -#: vmbackups/jobs.py:715 +#: vmbackups/jobs.py:730 msgid "The VM was not defined; its copies were removed" msgstr "虚拟机未定义;其副本已删除" -#: vmbackups/jobs.py:734 vmbackups/templates/vmbackups/target.html:18 +#: vmbackups/jobs.py:749 vmbackups/templates/vmbackups/target.html:18 msgid "Read backups from target" msgstr "从目标读取备份" -#: vmbackups/jobs.py:782 +#: vmbackups/jobs.py:797 #, python-format msgid "" "Not read, as a file of the backup is missing, changed or unreadable: " "%(names)s" msgstr "由于备份的某个文件缺失、已更改或无法读取,未读取:%(names)s" -#: vmbackups/jobs.py:798 +#: vmbackups/jobs.py:813 msgid "Check backup target" msgstr "检查备份目标" -#: vmbackups/jobs.py:825 +#: vmbackups/jobs.py:840 #, python-format msgid "Files of these backups are missing from the target: %(backups)s" msgstr "以下备份的文件在目标中缺失:%(backups)s" @@ -9852,7 +9857,12 @@ msgstr "此主机无法以机器类型 %(machine)s 运行虚拟机的模拟器 % msgid "This host has no firmware %(loader)s" msgstr "此主机没有固件 %(loader)s" -#: vrtManager/backup.py:278 +#: vrtManager/backup.py:280 +#, python-format +msgid "This host offers no TPM 2.0 %(model)s: install swtpm on it" +msgstr "此主机不提供 TPM 2.0 %(model)s:请在其上安装 swtpm" + +#: vrtManager/backup.py:285 #, python-format msgid "This host has no bridge %(name)s" msgstr "此主机没有网桥 %(name)s" diff --git a/vmbackups/jobs.py b/vmbackups/jobs.py index 39b9b271..191e2c74 100644 --- a/vmbackups/jobs.py +++ b/vmbackups/jobs.py @@ -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"))) diff --git a/vmbackups/tests/test_restore.py b/vmbackups/tests/test_restore.py index f8ae1b71..c69fcb4f 100644 --- a/vmbackups/tests/test_restore.py +++ b/vmbackups/tests/test_restore.py @@ -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"}) diff --git a/vrtManager/backup.py b/vrtManager/backup.py index fa10ecb3..b78d8ea2 100644 --- a/vrtManager/backup.py +++ b/vrtManager/backup.py @@ -258,7 +258,7 @@ def restore_definition(definition, *, name, uuid, macs, disks, nvram, connect): def check_restore_host(conn, definition): """Refuses a host that cannot run the backup's definition: its emulator, - machine type and firmware, the networks, bridges and network filters + machine type, firmware and TPM, the networks, bridges and network filters its NICs name.""" tree = etree.fromstring(definition) emulator = tree.findtext("devices/emulator") @@ -272,6 +272,13 @@ def check_restore_host(conn, definition): loader = (tree.findtext("os/loader") or "").strip() if loader and loader not in caps.xpath("os/loader/value/text()"): raise OperationError(gettext_noop("This host has no firmware %(loader)s"), loader=loader) + if (tpm := tree.find("devices/tpm")) is not None: + offered = "devices/tpm[@supported='yes']/enum[@name='{}']/value/text()" + if ("emulator" not in caps.xpath(offered.format("backendModel")) + or "2.0" not in caps.xpath(offered.format("backendVersion")) + or tpm.get("model") not in caps.xpath(offered.format("model"))): + raise OperationError(gettext_noop("This host offers no TPM 2.0 %(model)s: install swtpm on it"), + model=tpm.get("model")) for network in sorted(set(tree.xpath("devices/interface[@type='network']/source/@network")) - set(conn.get_networks())): raise OperationError(gettext_noop("This host has no network %(name)s"), name=network) for bridge in sorted(set(tree.xpath("devices/interface[@type='bridge']/source/@bridge")) - set(conn.get_ifaces())): diff --git a/vrtManager/tests/test_backup.py b/vrtManager/tests/test_backup.py index b6e21e52..393218f4 100644 --- a/vrtManager/tests/test_backup.py +++ b/vrtManager/tests/test_backup.py @@ -350,14 +350,14 @@ class RestoreHostTestCase(unittest.TestCase): "/usr/share/edk2/ovmf/OVMF_CODE.fd") return conn - def check(self, conn, *texts): + def check(self, conn, *texts, definition=SOURCE): from vrtManager.backup import check_restore_host if not texts: - check_restore_host(conn, SOURCE) + check_restore_host(conn, definition) return with self.assertRaises(util.OperationError) as caught: - check_restore_host(conn, SOURCE) + check_restore_host(conn, definition) for text in texts: self.assertIn(text, str(caught.exception)) @@ -390,3 +390,25 @@ class RestoreHostTestCase(unittest.TestCase): conn = self.conn() conn.wvm.getDomainCapabilities.return_value = "" self.check(conn, "OVMF_CODE.fd") + + def test_a_tpm_needs_the_host_to_offer_its_model_with_swtpm(self): + conn = self.conn() + self.check(conn) # no TPM in the definition + with_tpm = SOURCE.replace("", "" + TPM) + self.check(conn, "TPM 2.0 tpm-crb", "swtpm", definition=with_tpm) + + def offers(models, backends="emulator", versions="2.0"): + conn.wvm.getDomainCapabilities.return_value = ( + "/usr/share/edk2/ovmf/OVMF_CODE.fd" + f"{models}" + f"{backends}{versions}" + "") + + offers("tpm-tis") + self.check(conn, "tpm-crb", definition=with_tpm) + offers("tpm-crb", backends="passthrough") + self.check(conn, "swtpm", definition=with_tpm) + offers("tpm-crb", versions="1.2") + self.check(conn, "swtpm", definition=with_tpm) + offers("tpm-tistpm-crb") + self.check(conn, definition=with_tpm) diff --git a/vrtManager/tests/test_live_tpm_backup.py b/vrtManager/tests/test_live_tpm_backup.py new file mode 100644 index 00000000..28b645ba --- /dev/null +++ b/vrtManager/tests/test_live_tpm_backup.py @@ -0,0 +1,92 @@ +"""Live check that a shut-off VM's TPM state is read through libvirt, and +that state written under another VM's UUID is the one that VM starts with: +libvirt makes it swtpm's and does not manufacture a new TPM over it. + +Runs only with TEST_LIBVIRT_HOST set (see vrtManager/tests/livetest.py), on +a host with swtpm. +""" + +import os +import unittest +import uuid + +import libvirt +from django.test import SimpleTestCase +from lxml import etree + +from vrtManager.backup import wvmBackup +from vrtManager.connection import connection_manager, wvmConnect +from vrtManager.tests import livetest + +TPM = "" + + +class LiveTpmBackupTestCase(SimpleTestCase): + @classmethod + def setUpClass(cls): + if not livetest.enabled(): + raise unittest.SkipTest("Set TEST_LIBVIRT_HOST to run the live libvirt tests") + cls.args = ( + os.environ["TEST_LIBVIRT_HOST"], + os.environ.get("TEST_LIBVIRT_LOGIN", ""), + os.environ.get("TEST_LIBVIRT_PASSWORD", ""), + int(os.environ.get("TEST_LIBVIRT_TYPE", 4)), + ) + cls.conn = connection_manager.get_connection(*cls.args) + if wvmConnect(*cls.args).get_tpm_model("x86_64", "q35") is None: + raise unittest.SkipTest("The host has no swtpm") + livetest.cleanup(cls.conn) + cls.inventory = livetest.inventory(cls.conn) + cls.pools = {p.name() for p in cls.conn.listAllStoragePools()} + super().setUpClass() + + @classmethod + def tearDownClass(cls): + livetest.cleanup(cls.conn) + super().tearDownClass() + if livetest.inventory(cls.conn) != cls.inventory: + raise AssertionError("Live tests changed objects outside the test namespace") + if {p.name() for p in cls.conn.listAllStoragePools()} != cls.pools: + raise AssertionError("A storage pool was left behind") + + def tearDown(self): + # the TPM state goes with the VM + for dom in self.conn.listAllDomains(): + if dom.name().startswith(livetest.PREFIX + "tpm"): + if dom.isActive(): + dom.destroy() + dom.undefineFlags(livetest.UNDEFINE_FLAGS | libvirt.VIR_DOMAIN_UNDEFINE_TPM) + + def run_once(self, name): + dom = livetest.define_vm(self.conn, name, [], extra_devices=TPM) + dom.createWithFlags(libvirt.VIR_DOMAIN_START_PAUSED) + dom.destroy() + return dom + + def test_the_state_is_kept_by_the_vm_it_is_restored_to(self): + source = self.run_once(livetest.PREFIX + "tpm-a") + proxy = wvmBackup(*self.args, source.name(), uuid=source.UUIDString()) + self.assertTrue(proxy.backup_plan()["tpm"]) + state = proxy.read_tpm() + self.assertIn("tpm2-00.permall", state) + self.assertNotIn(".lock", state) + + restored = livetest.define_vm(self.conn, livetest.PREFIX + "tpm-b", [], extra_devices=TPM) + host = wvmConnect(*self.args) + with host._tpm_pool(restored.UUIDString(), build=True) as pool: + for name, data in state.items(): + host.upload_volume(pool, name, data, owner=(0, 0), mode="0600") + restored.createWithFlags(libvirt.VIR_DOMAIN_START_PAUSED) + restored.destroy() + + copy = wvmBackup(*self.args, restored.name(), uuid=restored.UUIDString()) + self.assertEqual(copy.read_tpm(), state) + with host._tpm_pool(restored.UUIDString()) as pool: + permissions = etree.fromstring(pool.storageVolLookupByName("tpm2-00.permall").XMLDesc(0)) + self.assertNotEqual(permissions.findtext("target/permissions/owner"), "0") # swtpm's now + + def test_a_vm_that_never_started_has_no_state(self): + dom = livetest.define_vm(self.conn, livetest.PREFIX + "tpm-c", [], extra_devices=TPM) + self.assertEqual(wvmBackup(*self.args, dom.name(), uuid=dom.UUIDString()).read_tpm(), {}) + with wvmConnect(*self.args)._tpm_pool(str(uuid.uuid4())) as pool: + self.assertIsNone(pool)