mirror of
https://github.com/retspen/webvirtcloud
synced 2026-12-03 09:26:03 +00:00
feat(vmbackups): restore a backup as a new VM
A ready backup has a Restore button (Backups page and the VM's tab) and POST /api/v1/backups/<uuid>/restore/. The form takes the new VM's name (default <vm>-restored), a compute that has the target's pool, the pool for its disks, Connect the network (off by default: the restored guest keeps the VM's addresses and host name) and Start after restore. The job page follows the restore. The backup.restore job holds what a new VM's job holds, the backup (shared) and the target. Before anything is made it checks again: the host is not in maintenance; the name is free in the panel and on the host (a VM made with virsh too); the backup's files are in the target, the disks at their size and the small files with their SHA-256; the host offers the definition's emulator, machine type and firmware, its networks, bridges and network filters; the destination pool has room and none of the copies' names. The new VM's UUID, MACs, volume names and NVRAM path are recorded first. Then the disks are copied from the target, the NVRAM file uploaded, maintenance checked once more, and the VM defined last and given to the superuser who restored it. The definition is the kept one rewritten as a clone's (rewrite_for_new_vm, taken out of _clone_definition for both): new name, UUID and SMBIOS UUID, MACs and filter parameters, a VNC password, no cloud-init seed of the VM's; with a new generation ID, each disk's source the restored file without the old chain, the NVRAM path, and links down unless connected. Recovery records a VM defined by the recorded UUID; otherwise it removes the copies and the NVRAM file by their recorded names.
This commit is contained in:
parent
7227867d78
commit
823d34cc18
16 changed files with 1280 additions and 305 deletions
|
|
@ -8,7 +8,7 @@ from django.utils.translation import gettext_noop
|
|||
from lxml import etree
|
||||
|
||||
from vrtManager.connection import NVRAM_DIR, wvmConnect
|
||||
from vrtManager.instance import PERSISTENT_XML, wvmInstance
|
||||
from vrtManager.instance import PERSISTENT_XML, rewrite_for_new_vm, wvmInstance
|
||||
from vrtManager.util import OperationError
|
||||
|
||||
# pools that keep their volumes as files in one directory
|
||||
|
|
@ -190,6 +190,75 @@ def remove_files(pool, names):
|
|||
vol.delete(0)
|
||||
|
||||
|
||||
def volume_exists(pool, name):
|
||||
return wvmConnect._find_volume(pool, name) is not None
|
||||
|
||||
|
||||
def manifest_names(pool):
|
||||
pool.refresh(0)
|
||||
return sorted(name for name in pool.listVolumes() if name.startswith("wvc-") and name.endswith("-manifest.json"))
|
||||
|
||||
|
||||
def restore_definition(definition, *, name, uuid, macs, disks, nvram, connect):
|
||||
"""A backup's kept definition made a new VM's: rewrite_for_new_vm's
|
||||
changes (macs: one per NIC, in order), its media ejected, a new generation ID, each disk's
|
||||
source the restored file (disks: {dev: (path, format)}) with nothing of
|
||||
the old one's chain, the NVRAM file at nvram, and each NIC's link down
|
||||
unless connect: the restored guest keeps the VM's addresses and names."""
|
||||
tree = etree.fromstring(definition)
|
||||
clone_data = {"name": name, "clone-title": tree.findtext("title") or "",
|
||||
"clone-description": tree.findtext("description") or "",
|
||||
**{f"clone-net-mac-{number}": mac for number, mac in enumerate(macs)}}
|
||||
rewrite_for_new_vm(tree, clone_data, uuid)
|
||||
# media are not in the backup: the restore host may not have them, and the VM would not start
|
||||
for source in tree.xpath("devices/disk[@device='cdrom' or @device='floppy']/source"):
|
||||
source.getparent().remove(source)
|
||||
if (genid := tree.find("genid")) is not None:
|
||||
genid.text = None # libvirt makes a new one
|
||||
for disk in tree.xpath("devices/disk[@device='disk']"):
|
||||
path, disk_format = disks[disk.find("target").get("dev")]
|
||||
disk.set("type", "file")
|
||||
for old in disk.xpath("source|backingStore"):
|
||||
disk.remove(old)
|
||||
driver = disk.find("driver")
|
||||
if driver is None:
|
||||
driver = etree.SubElement(disk, "driver", name="qemu")
|
||||
driver.set("type", disk_format)
|
||||
source = etree.Element("source", file=path)
|
||||
disk.insert(list(disk).index(driver) + 1, source)
|
||||
if (element := tree.find("os/nvram")) is not None:
|
||||
if element.find("source") is not None:
|
||||
element.find("source").set("file", nvram)
|
||||
else:
|
||||
element.text = nvram
|
||||
if not connect:
|
||||
for interface in tree.findall("devices/interface"):
|
||||
link = interface.find("link")
|
||||
if link is None:
|
||||
link = etree.SubElement(interface, "link")
|
||||
link.set("state", "down")
|
||||
return etree.tostring(tree).decode()
|
||||
|
||||
|
||||
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
|
||||
its NICs name."""
|
||||
tree = etree.fromstring(definition)
|
||||
emulator = tree.findtext("devices/emulator")
|
||||
os_type = tree.find("os/type")
|
||||
arch, machine = os_type.get("arch"), os_type.get("machine")
|
||||
try:
|
||||
caps = etree.fromstring(conn.wvm.getDomainCapabilities(emulator, arch, machine, tree.get("type"), 0))
|
||||
except libvirt.libvirtError as err:
|
||||
raise OperationError(gettext_noop("This host cannot run the VM's emulator %(emulator)s with machine type %(machine)s: %(error)s"),
|
||||
emulator=emulator, machine=machine, error=err) from err
|
||||
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)
|
||||
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())):
|
||||
raise OperationError(gettext_noop("This host has no bridge %(name)s"), name=bridge)
|
||||
for nwfilter in sorted(set(tree.xpath("devices/interface/filterref/@filter")) - set(conn.get_nwfilters())):
|
||||
raise OperationError(gettext_noop("This host has no network filter %(name)s"), name=nwfilter)
|
||||
|
|
|
|||
|
|
@ -697,6 +697,68 @@ def agent_interfaces(dom):
|
|||
return interfaces
|
||||
|
||||
|
||||
|
||||
def rewrite_for_new_vm(tree, clone_data, uuid):
|
||||
"""A VM's persistent definition (tree) made another VM's, in place: its
|
||||
name, UUID, title and description, each NIC's MAC (clone-net-mac-<n>)
|
||||
and its filter parameters, a new VNC password, no host device, an
|
||||
empty TPM and no cloud-init seed of the VM's. The clone and the restore
|
||||
of a backup share it."""
|
||||
# the cloud-init seed holds the VM's own instance-id and hostname: the clone's drive stays empty
|
||||
seed = f"cidata-{tree.findtext('uuid')}.iso"
|
||||
for source in tree.xpath("devices/disk[@device='cdrom']/source"):
|
||||
if os.path.basename(source.get("file") or "") == seed:
|
||||
source.getparent().remove(source)
|
||||
tree.find("name").text = clone_data["name"]
|
||||
uuid_el = tree.find("uuid")
|
||||
if uuid_el is None:
|
||||
uuid_el = etree.SubElement(tree, "uuid")
|
||||
uuid_el.text = uuid
|
||||
# libvirt refuses an SMBIOS UUID other than the domain's
|
||||
for entry in tree.xpath("sysinfo/system/entry[@name='uuid']"):
|
||||
entry.text = uuid
|
||||
wvmInstance._set_options(
|
||||
tree,
|
||||
{
|
||||
"title": clone_data.get("clone-title", ""),
|
||||
"description": clone_data.get("clone-description", ""),
|
||||
},
|
||||
)
|
||||
|
||||
# the clone gets a new, empty TPM (the clone form says so): an emulated
|
||||
# one without the VM's state path; a host's or another process's would be shared
|
||||
for backend in tree.xpath("devices/tpm/backend"):
|
||||
if backend.get("type") != "emulator":
|
||||
raise util.OperationError(gettext_noop("A VM with a host's or an external TPM is not cloned; remove it first"))
|
||||
for source in backend.findall("source"):
|
||||
backend.remove(source)
|
||||
|
||||
# a host device is one VM's: the clone gets none (the clone form says so)
|
||||
for hostdev in tree.findall("devices/hostdev"):
|
||||
hostdev.getparent().remove(hostdev)
|
||||
for num, net in enumerate(tree.findall("devices/interface")):
|
||||
if net.get("type") == "hostdev": # numbered as the form numbers the VM's NICs
|
||||
net.getparent().remove(net)
|
||||
continue
|
||||
mac = clone_data.get(f"clone-net-mac-{num}")
|
||||
if not mac:
|
||||
raise ValueError(f"No MAC address for network interface {num}")
|
||||
net.find("mac").set("address", wvmInstance.fix_mac(mac))
|
||||
# a filter's parameters of the source's own addresses would block the clone's traffic:
|
||||
# its MAC is the clone's, its IP the one it learns (clean-traffic's default), unless
|
||||
# learning is off; libvirt learns no IPv6 address, so IPV6 stays for the admin to change
|
||||
for parameter in net.xpath("filterref/parameter[@name='MAC']"):
|
||||
parameter.set("value", wvmInstance.fix_mac(mac))
|
||||
if not net.xpath("filterref/parameter[@name='CTRL_IP_LEARNING'][@value='none']"):
|
||||
for parameter in net.xpath("filterref/parameter[@name='IP']"):
|
||||
parameter.getparent().remove(parameter)
|
||||
|
||||
# the clone's console gets a password of its own: one copied from the source would open both
|
||||
for graphics in tree.findall("devices/graphics[@type='vnc']"):
|
||||
graphics.set("passwd", util.randomPasswd(8)) # the length VNC allows
|
||||
graphics.attrib.pop("passwdValidTo", None) # an expired source's would leave it unusable
|
||||
|
||||
|
||||
class wvmInstance(wvmConnect):
|
||||
# set by cached_reads(): libvirt answers reused within the block
|
||||
_read_cache = None
|
||||
|
|
@ -2463,7 +2525,8 @@ class wvmInstance(wvmConnect):
|
|||
if pool is not None:
|
||||
pool.refresh(0)
|
||||
|
||||
def fix_mac(self, mac):
|
||||
@staticmethod
|
||||
def fix_mac(mac):
|
||||
if ":" in mac:
|
||||
return mac
|
||||
# if mac does not contain ":", try to split into tuples and join with ":"
|
||||
|
|
@ -2480,26 +2543,7 @@ class wvmInstance(wvmConnect):
|
|||
raise ValueError("An instance with the clone name already exists")
|
||||
|
||||
tree = etree.fromstring(self._XMLDesc(PERSISTENT_XML))
|
||||
# the cloud-init seed holds the VM's own instance-id and hostname: the clone's drive stays empty
|
||||
seed = f"cidata-{tree.findtext('uuid')}.iso"
|
||||
for source in tree.xpath("devices/disk[@device='cdrom']/source"):
|
||||
if os.path.basename(source.get("file") or "") == seed:
|
||||
source.getparent().remove(source)
|
||||
tree.find("name").text = clone_data["name"]
|
||||
uuid_el = tree.find("uuid")
|
||||
if uuid_el is None:
|
||||
uuid_el = etree.SubElement(tree, "uuid")
|
||||
uuid_el.text = uuid
|
||||
# libvirt refuses an SMBIOS UUID other than the domain's
|
||||
for entry in tree.xpath("sysinfo/system/entry[@name='uuid']"):
|
||||
entry.text = uuid
|
||||
self._set_options(
|
||||
tree,
|
||||
{
|
||||
"title": clone_data.get("clone-title", ""),
|
||||
"description": clone_data.get("clone-description", ""),
|
||||
},
|
||||
)
|
||||
rewrite_for_new_vm(tree, clone_data, uuid)
|
||||
|
||||
disks = []
|
||||
for disk in list(tree.findall("devices/disk")):
|
||||
|
|
@ -2518,39 +2562,6 @@ class wvmInstance(wvmConnect):
|
|||
raise ValueError("Cannot clone a disk without a supported source and destination")
|
||||
disks.append((source, dev))
|
||||
|
||||
# the clone gets a new, empty TPM (the clone form says so): an emulated
|
||||
# one without the VM's state path; a host's or another process's would be shared
|
||||
for backend in tree.xpath("devices/tpm/backend"):
|
||||
if backend.get("type") != "emulator":
|
||||
raise util.OperationError(gettext_noop("A VM with a host's or an external TPM is not cloned; remove it first"))
|
||||
for source in backend.findall("source"):
|
||||
backend.remove(source)
|
||||
|
||||
# a host device is one VM's: the clone gets none (the clone form says so)
|
||||
for hostdev in tree.findall("devices/hostdev"):
|
||||
hostdev.getparent().remove(hostdev)
|
||||
for num, net in enumerate(tree.findall("devices/interface")):
|
||||
if net.get("type") == "hostdev": # numbered as the form numbers the VM's NICs
|
||||
net.getparent().remove(net)
|
||||
continue
|
||||
mac = clone_data.get(f"clone-net-mac-{num}")
|
||||
if not mac:
|
||||
raise ValueError(f"No MAC address for network interface {num}")
|
||||
net.find("mac").set("address", self.fix_mac(mac))
|
||||
# a filter's parameters of the source's own addresses would block the clone's traffic:
|
||||
# its MAC is the clone's, its IP the one it learns (clean-traffic's default), unless
|
||||
# learning is off; libvirt learns no IPv6 address, so IPV6 stays for the admin to change
|
||||
for parameter in net.xpath("filterref/parameter[@name='MAC']"):
|
||||
parameter.set("value", self.fix_mac(mac))
|
||||
if not net.xpath("filterref/parameter[@name='CTRL_IP_LEARNING'][@value='none']"):
|
||||
for parameter in net.xpath("filterref/parameter[@name='IP']"):
|
||||
parameter.getparent().remove(parameter)
|
||||
|
||||
# the clone's console gets a password of its own: one copied from the source would open both
|
||||
for graphics in tree.findall("devices/graphics[@type='vnc']"):
|
||||
graphics.set("passwd", util.randomPasswd(8)) # the length VNC allows
|
||||
graphics.attrib.pop("passwdValidTo", None) # an expired source's would leave it unusable
|
||||
|
||||
nvram = tree.find("os/nvram")
|
||||
if nvram is not None and nvram.get("type", "file") != "file":
|
||||
raise util.OperationError(gettext_noop("Cannot clone a VM whose NVRAM is not a file"))
|
||||
|
|
@ -3143,7 +3154,8 @@ class wvmInstance(wvmConnect):
|
|||
if not found:
|
||||
raise util.OperationError(gettext_noop("The VM has no network interface %(mac)s"), mac=mac_address)
|
||||
|
||||
def _set_options(self, tree, options):
|
||||
@staticmethod
|
||||
def _set_options(tree, options):
|
||||
for o in ["title", "description"]:
|
||||
option = tree.find(o)
|
||||
option_value = options.get(o, "").strip()
|
||||
|
|
|
|||
|
|
@ -198,3 +198,124 @@ class FilesTestCase(unittest.TestCase):
|
|||
self.assertEqual(volume.findtext("target/permissions/mode"), "0600")
|
||||
conn.upload_volume(pool, "g", b"ab")
|
||||
self.assertIsNone(etree.fromstring(pool.createXML.call_args.args[0]).find("target/permissions"))
|
||||
|
||||
|
||||
SOURCE = """<domain type='kvm'>
|
||||
<name>vm1</name><uuid>11111111-1111-4111-8111-111111111111</uuid><genid>22222222-2222-4222-8222-222222222222</genid>
|
||||
<title>web</title>
|
||||
<sysinfo type='smbios'><system><entry name='uuid'>11111111-1111-4111-8111-111111111111</entry></system></sysinfo>
|
||||
<os><type arch='x86_64' machine='pc-q35-10.1'>hvm</type><loader readonly='yes' type='pflash'>/usr/share/edk2/ovmf/OVMF_CODE.fd</loader>
|
||||
<nvram>/var/lib/libvirt/qemu/nvram/vm1_VARS.fd</nvram></os>
|
||||
<devices>
|
||||
<emulator>/usr/libexec/qemu-kvm</emulator>
|
||||
<disk type='file' device='disk'><driver name='qemu' type='qcow2'/>
|
||||
<source file='/pool/a.qcow2'><seclabel model='dac' relabel='no'/></source>
|
||||
<backingStore type='file'><format type='qcow2'/><source file='/pool/base.qcow2'/></backingStore>
|
||||
<target dev='vda' bus='virtio'/></disk>
|
||||
<disk type='file' device='disk'><driver name='qemu' type='raw'/><source file='/pool/b.img'/><target dev='vdb' bus='virtio'/></disk>
|
||||
<disk type='file' device='cdrom'><source file='/iso/cidata-11111111-1111-4111-8111-111111111111.iso'/><target dev='sda'/></disk>
|
||||
<disk type='file' device='cdrom'><source file='/iso/install.iso'/><target dev='sdb'/></disk>
|
||||
<disk type='file' device='floppy'><source file='/iso/drivers.vfd'/><target dev='fda'/></disk>
|
||||
<interface type='network'><mac address='52:54:00:00:00:01'/><source network='default'/>
|
||||
<filterref filter='clean-traffic'><parameter name='MAC' value='52:54:00:00:00:01'/><parameter name='IP' value='192.0.2.5'/></filterref></interface>
|
||||
<interface type='bridge'><mac address='52:54:00:00:00:02'/><source bridge='br0'/><link state='up'/></interface>
|
||||
<graphics type='vnc' passwd='secret1'/>
|
||||
</devices>
|
||||
</domain>"""
|
||||
|
||||
|
||||
class RestoreDefinitionTestCase(unittest.TestCase):
|
||||
def restored(self, connect=False):
|
||||
from lxml import etree
|
||||
|
||||
from vrtManager.backup import restore_definition
|
||||
|
||||
xml = restore_definition(
|
||||
SOURCE, name="vm1-restored", uuid="33333333-3333-4333-8333-333333333333",
|
||||
macs=["52:54:00:aa:00:01", "52:54:00:aa:00:02"],
|
||||
disks={"vda": ("/dest/vm1-restored-vda.qcow2", "qcow2"), "vdb": ("/dest/vm1-restored-vdb.raw", "raw")},
|
||||
nvram="/var/lib/libvirt/qemu/nvram/vm1-restored_VARS.fd", connect=connect,
|
||||
)
|
||||
return etree.fromstring(xml)
|
||||
|
||||
def test_restore_definition(self):
|
||||
tree = self.restored()
|
||||
self.assertEqual(tree.findtext("name"), "vm1-restored")
|
||||
self.assertEqual(tree.findtext("uuid"), "33333333-3333-4333-8333-333333333333")
|
||||
self.assertEqual(tree.xpath("string(sysinfo/system/entry[@name='uuid'])"), "33333333-3333-4333-8333-333333333333")
|
||||
self.assertEqual(tree.findtext("genid") or "", "") # libvirt makes a new one
|
||||
self.assertIsNotNone(tree.find("genid"))
|
||||
self.assertEqual(tree.xpath("devices/interface/mac/@address"), ["52:54:00:aa:00:01", "52:54:00:aa:00:02"])
|
||||
self.assertEqual(tree.xpath("devices/interface/filterref/parameter[@name='MAC']/@value"), ["52:54:00:aa:00:01"])
|
||||
self.assertEqual(tree.xpath("devices/interface/filterref/parameter[@name='IP']"), [])
|
||||
self.assertEqual(tree.xpath("devices/disk[@device='disk']/source/@file"),
|
||||
["/dest/vm1-restored-vda.qcow2", "/dest/vm1-restored-vdb.raw"])
|
||||
self.assertEqual(tree.xpath("devices/disk[@device='disk']/driver/@type"), ["qcow2", "raw"])
|
||||
self.assertEqual(tree.xpath("devices/disk//backingStore|devices/disk//seclabel|devices/disk//dataStore"), [])
|
||||
self.assertEqual(tree.xpath("devices/disk[@device='cdrom']/source"), []) # the old VM's cloud-init seed
|
||||
self.assertEqual(len(tree.xpath("devices/disk[@device='cdrom']")), 2) # the drives stay
|
||||
self.assertEqual(tree.findtext("os/nvram"), "/var/lib/libvirt/qemu/nvram/vm1-restored_VARS.fd")
|
||||
self.assertEqual(tree.xpath("devices/interface/link/@state"), ["down", "down"])
|
||||
self.assertNotEqual(tree.xpath("string(devices/graphics/@passwd)"), "secret1")
|
||||
self.assertEqual(tree.findtext("title"), "web")
|
||||
|
||||
def test_media_are_ejected(self):
|
||||
# not in the backup: the restore host may not have them, and the VM would not start
|
||||
tree = self.restored()
|
||||
self.assertEqual(tree.xpath("devices/disk[@device='cdrom' or @device='floppy']/source"), [])
|
||||
self.assertEqual(len(tree.xpath("devices/disk[@device='cdrom' or @device='floppy']")), 3)
|
||||
|
||||
def test_links_kept_when_connected(self):
|
||||
self.assertEqual(self.restored(connect=True).xpath("devices/interface/link/@state"), ["up"])
|
||||
|
||||
|
||||
class RestoreHostTestCase(unittest.TestCase):
|
||||
def conn(self):
|
||||
conn = MagicMock()
|
||||
conn.get_networks.return_value = ["default"]
|
||||
conn.get_ifaces.return_value = ["br0", "eth0"]
|
||||
conn.get_nwfilters.return_value = ["clean-traffic"]
|
||||
conn.wvm.getDomainCapabilities.return_value = (
|
||||
"<domainCapabilities><os><loader><value>/usr/share/edk2/ovmf/OVMF_CODE.fd</value></loader></os></domainCapabilities>")
|
||||
return conn
|
||||
|
||||
def check(self, conn, *texts):
|
||||
from vrtManager.backup import check_restore_host
|
||||
|
||||
if not texts:
|
||||
check_restore_host(conn, SOURCE)
|
||||
return
|
||||
with self.assertRaises(util.OperationError) as caught:
|
||||
check_restore_host(conn, SOURCE)
|
||||
for text in texts:
|
||||
self.assertIn(text, str(caught.exception))
|
||||
|
||||
def test_a_host_that_offers_everything(self):
|
||||
conn = self.conn()
|
||||
self.check(conn)
|
||||
conn.wvm.getDomainCapabilities.assert_called_once_with("/usr/libexec/qemu-kvm", "x86_64", "pc-q35-10.1", "kvm", 0)
|
||||
|
||||
def test_a_missing_network_is_refused(self):
|
||||
conn = self.conn()
|
||||
conn.get_networks.return_value = []
|
||||
self.check(conn, "network default")
|
||||
|
||||
def test_a_missing_bridge_is_refused(self):
|
||||
conn = self.conn()
|
||||
conn.get_ifaces.return_value = ["eth0"]
|
||||
self.check(conn, "br0")
|
||||
|
||||
def test_a_missing_filter_is_refused(self):
|
||||
conn = self.conn()
|
||||
conn.get_nwfilters.return_value = []
|
||||
self.check(conn, "clean-traffic")
|
||||
|
||||
def test_an_emulator_or_machine_the_host_lacks_is_refused(self):
|
||||
conn = self.conn()
|
||||
conn.wvm.getDomainCapabilities.side_effect = error(libvirt.VIR_ERR_INVALID_ARG)
|
||||
self.check(conn, "/usr/libexec/qemu-kvm", "pc-q35-10.1")
|
||||
|
||||
def test_a_firmware_the_host_lacks_is_refused(self):
|
||||
conn = self.conn()
|
||||
conn.wvm.getDomainCapabilities.return_value = "<domainCapabilities><os><loader/></os></domainCapabilities>"
|
||||
self.check(conn, "OVMF_CODE.fd")
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue