mirror of
https://github.com/retspen/webvirtcloud
synced 2026-12-03 17:36:05 +00:00
feat(vmbackups): what a VM's backup holds and the target files
wvmBackup.backup_plan reads a VM's persistent definition and says what a backup copies: each file disk (qcow2 or raw) with its pool and virtual size, the NVRAM file, and what is left out (CD-ROMs, floppies). It refuses, naming the reason, what a backup could not restore as it is: encrypted, block, network, volume, directory and shareable disks, other disk formats, a disk in no storage pool, shared host directories, a kernel file boot, host devices, a saved state, TPM state (a later layer), an NVRAM file outside libvirt's directory, and a running VM whose disks change at its next start. The target side: the files' names from the backup's UUID only, the free space check (virtual size plus the snapshots' margin), small files written and read back with their SHA-256, read, removed and the manifests listed. download_volume is taken out of copy_nvram for both. Every user of the NVRAM pool runs in the worker, so its process lock holds. A push backup target of a raw disk (live backup or live clone) is made without qcow2's compat and features, which libvirt refuses for raw.
This commit is contained in:
parent
022737f143
commit
89835f2b06
10 changed files with 785 additions and 239 deletions
|
|
@ -1,9 +1,14 @@
|
|||
"""VM backups: the target pools and what a VM's backup holds (app vmbackups)."""
|
||||
|
||||
import hashlib
|
||||
import os
|
||||
|
||||
import libvirt
|
||||
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.util import OperationError
|
||||
|
||||
# pools that keep their volumes as files in one directory
|
||||
|
|
@ -41,3 +46,150 @@ def pool_space(pool):
|
|||
pool.refresh(0)
|
||||
_state, size, used, free = pool.info()
|
||||
return {"name": pool.name(), "size": size, "free": free, "used_percent": used * 100 / size if size else 0}
|
||||
|
||||
|
||||
class wvmBackup(wvmInstance):
|
||||
"""The VM side of a backup."""
|
||||
|
||||
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
|
||||
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)
|
||||
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"):
|
||||
raise OperationError(gettext_noop("%(vm)s boots a kernel file of the host; it cannot be backed up"), vm=name)
|
||||
if tree.xpath("devices/hostdev|devices/interface[@type='hostdev']"):
|
||||
raise OperationError(gettext_noop("%(vm)s has a host device; it cannot be backed up"), vm=name)
|
||||
|
||||
disks, left_out = [], []
|
||||
for disk in tree.xpath("devices/disk"):
|
||||
dev = disk.find("target").get("dev")
|
||||
if disk.get("device") in ("cdrom", "floppy"):
|
||||
why = gettext_noop("CD-ROM: not copied") if disk.get("device") == "cdrom" else gettext_noop("Floppy: not copied")
|
||||
left_out.append({"dev": dev, "why": why})
|
||||
continue
|
||||
if disk.xpath("encryption|source/encryption"):
|
||||
raise OperationError(gettext_noop("Disk %(dev)s is encrypted; it cannot be backed up"), dev=dev)
|
||||
path = disk.xpath("string(source/@file)")
|
||||
if disk.get("type") != "file" or not path:
|
||||
raise OperationError(gettext_noop("Disk %(dev)s is not a file; it cannot be backed up"), dev=dev)
|
||||
if disk.find("shareable") is not None:
|
||||
raise OperationError(gettext_noop("Disk %(dev)s is shareable; it cannot be backed up"), dev=dev)
|
||||
disk_format = disk.xpath("string(driver/@type)") or "raw"
|
||||
if disk_format not in ("qcow2", "raw"):
|
||||
raise OperationError(gettext_noop("Disk %(dev)s is %(format)s; only qcow2 and raw disks are backed up"),
|
||||
dev=dev, format=disk_format)
|
||||
try:
|
||||
vol = self.get_volume_by_path(path)
|
||||
except libvirt.libvirtError as err:
|
||||
if err.get_error_code() != libvirt.VIR_ERR_NO_STORAGE_VOL:
|
||||
raise
|
||||
raise OperationError(gettext_noop("Disk %(dev)s (%(path)s) is in no storage pool of the host; it cannot be backed up"),
|
||||
dev=dev, path=path) from err
|
||||
disks.append({"dev": dev, "path": path, "pool": vol.storagePoolLookupByVolume().name(),
|
||||
"format": disk_format, "capacity": vol.info()[1]})
|
||||
|
||||
if self.instance.state()[0] != libvirt.VIR_DOMAIN_SHUTOFF:
|
||||
# a running VM's disks are copied: the definition kept must name the same ones
|
||||
live = etree.fromstring(self._XMLDesc(0))
|
||||
copied = [(d["dev"], d["path"]) for d in disks]
|
||||
running = [(d.find("target").get("dev"), d.xpath("string(source/@file)"))
|
||||
for d in live.xpath("devices/disk[not(@device='cdrom' or @device='floppy')]")]
|
||||
if copied != running:
|
||||
changed = sorted({dev for dev, _path in set(copied) ^ set(running)})
|
||||
raise OperationError(gettext_noop("Disks %(devs)s change at the next start; back the VM up after it restarts"),
|
||||
devs=", ".join(changed))
|
||||
|
||||
nvram = tree.xpath("string(os/nvram/source/@file)") or (tree.findtext("os/nvram") or "").strip() or None
|
||||
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}
|
||||
|
||||
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
|
||||
format (libvirt's createXMLFrom). Returns the copy's path."""
|
||||
return self.get_wvmStorage(pool).clone_volume(
|
||||
self.get_volume_by_path(disk["path"]), name, vol_fmt=disk["format"],
|
||||
disk_owner_uid=owner_uid, disk_owner_gid=owner_gid,
|
||||
)
|
||||
|
||||
def make_live_targets(self, disks, pool, names, owner_uid, owner_gid):
|
||||
"""The empty volumes a running VM's push backup writes into, in the
|
||||
target pool; the targets begin_clone_backup takes."""
|
||||
targets = []
|
||||
for disk in disks:
|
||||
target = {"dev": disk["dev"], "pool": pool, "name": names[disk["dev"]],
|
||||
"capacity": disk["capacity"], "format": disk["format"]}
|
||||
target["path"] = self.create_clone_target(target, owner_uid, owner_gid)
|
||||
targets.append(target)
|
||||
return targets
|
||||
|
||||
def read_nvram(self, path):
|
||||
"""The bytes of the VM's NVRAM file; None when it was never made (the
|
||||
VM never started)."""
|
||||
with self._nvram_pool() as pool:
|
||||
vol = self._find_volume(pool, os.path.basename(path))
|
||||
return None if vol is None else self.download_volume(vol)
|
||||
|
||||
|
||||
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}"
|
||||
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,
|
||||
"domain": f"{prefix}-domain.xml",
|
||||
"manifest": f"{prefix}-manifest.json",
|
||||
}
|
||||
|
||||
|
||||
def check_target_space(pool, disks, free_percent, free_min_gib):
|
||||
"""The target keeps the disks' virtual capacity plus free_percent of
|
||||
it, at least free_min_gib GiB, free (the snapshots' and clones' rule)."""
|
||||
size = sum(d["capacity"] for d in disks)
|
||||
needed = size + max(size * free_percent / 100, free_min_gib * 1024**3)
|
||||
pool.refresh(0)
|
||||
free = pool.info()[3]
|
||||
if free < needed:
|
||||
raise OperationError(gettext_noop(
|
||||
"Storage pool %(pool)s has %(free).1f GiB free; the backup needs %(size).1f GiB (the copied disks, "
|
||||
"plus %(percent)g%% of them, at least %(minimum)g 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):
|
||||
"""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."""
|
||||
remove_files(pool, [name])
|
||||
vol = conn.upload_volume(pool, name, data, owner=owner)
|
||||
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)
|
||||
return hashlib.sha256(data).hexdigest()
|
||||
|
||||
|
||||
def get_file(conn, pool, name):
|
||||
return conn.download_volume(pool.storageVolLookupByName(name))
|
||||
|
||||
|
||||
def remove_files(pool, names):
|
||||
"""Deletes the volumes names of pool; missing ones are passed over."""
|
||||
for name in names:
|
||||
vol = wvmConnect._find_volume(pool, name)
|
||||
if vol is not None:
|
||||
vol.delete(0)
|
||||
|
||||
|
||||
def manifest_names(pool):
|
||||
pool.refresh(0)
|
||||
return sorted(name for name in pool.listVolumes() if name.startswith("wvc-") and name.endswith("-manifest.json"))
|
||||
|
|
|
|||
|
|
@ -197,6 +197,8 @@ UNREAD_DISKS = etree.XPath("devices/disk[@device='disk'][not(driver/@type='raw')
|
|||
# One use of NVRAM_DIR's pool at a time (_nvram_pool), on every host: a copy
|
||||
# holds two hosts' pools, and locks per host taken by migrations both ways
|
||||
# could deadlock. Reentrant, as that copy takes it twice.
|
||||
# A lock of the process is enough: every user (migration, clone, backup and
|
||||
# their recoveries) runs in the worker, the one process that runs jobs.
|
||||
NVRAM_LOCK = threading.RLock()
|
||||
|
||||
class wvmConnection(object):
|
||||
|
|
@ -1070,16 +1072,18 @@ class wvmConnect(object):
|
|||
with contextlib.suppress(libvirtError):
|
||||
pool.destroy()
|
||||
|
||||
def upload_volume(self, pool, name, data):
|
||||
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. A failed write leaves
|
||||
no volume."""
|
||||
stream, which every connection type carries; owner: (uid, gid) of
|
||||
its file, else libvirt's (root). A failed write leaves no volume."""
|
||||
permissions = (f"<permissions><owner>{owner[0]}</owner><group>{owner[1]}</group><mode>{mode}</mode></permissions>"
|
||||
if owner else "")
|
||||
stream = self.wvm.newStream(0)
|
||||
vol = None
|
||||
try:
|
||||
vol = pool.createXML(
|
||||
f"<volume><name>{util.xml_escape(name)}</name><capacity>{len(data)}</capacity>"
|
||||
"<target><format type='raw'/></target></volume>",
|
||||
f"<target><format type='raw'/>{permissions}</target></volume>",
|
||||
0,
|
||||
)
|
||||
vol.upload(stream, 0, len(data), 0)
|
||||
|
|
@ -1094,6 +1098,21 @@ class wvmConnect(object):
|
|||
raise
|
||||
return vol
|
||||
|
||||
def download_volume(self, vol):
|
||||
"""A volume's bytes, read through a libvirt stream. For small files
|
||||
(NVRAM, a backup's definition and manifest): held in memory."""
|
||||
chunks = []
|
||||
stream = self.wvm.newStream(0)
|
||||
try:
|
||||
vol.download(stream, 0, 0, 0)
|
||||
stream.recvAll(lambda _stream, data, out: out.append(data), chunks)
|
||||
stream.finish()
|
||||
except Exception:
|
||||
with contextlib.suppress(libvirtError):
|
||||
stream.abort()
|
||||
raise
|
||||
return b"".join(chunks)
|
||||
|
||||
@staticmethod
|
||||
def _find_volume(pool, name):
|
||||
try:
|
||||
|
|
|
|||
|
|
@ -502,17 +502,7 @@ class wvmInstances(wvmConnect):
|
|||
if self._find_volume(target, name) is None:
|
||||
raise util.OperationError(gettext_noop("The destination host cannot see the NVRAM file %(path)s"), path=path)
|
||||
return None
|
||||
chunks = []
|
||||
stream = conn.wvm.newStream(0)
|
||||
try:
|
||||
vol.download(stream, 0, 0, 0)
|
||||
stream.recvAll(lambda _stream, data, out: out.append(data), chunks)
|
||||
stream.finish()
|
||||
except Exception:
|
||||
with contextlib.suppress(libvirtError):
|
||||
stream.abort()
|
||||
raise
|
||||
self.upload_volume(target, name, b"".join(chunks))
|
||||
self.upload_volume(target, name, conn.download_volume(vol))
|
||||
return name
|
||||
|
||||
def delete_nvram(self, name):
|
||||
|
|
@ -2567,6 +2557,8 @@ class wvmInstance(wvmConnect):
|
|||
return tree, disks
|
||||
|
||||
def _clone_volume_xml(self, name, capacity, vol_format, owner_uid, owner_gid):
|
||||
# compat and features are qcow2's: libvirt refuses them for another format
|
||||
qcow2 = "<compat>1.1</compat><features><lazy_refcounts/></features>" if vol_format == "qcow2" else ""
|
||||
return f"""<volume>
|
||||
<name>{util.xml_escape(name)}</name>
|
||||
<capacity>{capacity}</capacity>
|
||||
|
|
@ -2579,8 +2571,7 @@ class wvmInstance(wvmConnect):
|
|||
<mode>0644</mode>
|
||||
<label>virt_image_t</label>
|
||||
</permissions>
|
||||
<compat>1.1</compat>
|
||||
<features><lazy_refcounts/></features>
|
||||
{qcow2}
|
||||
</target>
|
||||
</volume>"""
|
||||
|
||||
|
|
|
|||
|
|
@ -7,6 +7,7 @@ from unittest.mock import MagicMock
|
|||
import libvirt
|
||||
from lxml import etree
|
||||
|
||||
from vrtManager.connection import wvmConnect
|
||||
from vrtManager.instance import wvmInstances
|
||||
|
||||
|
||||
|
|
@ -196,6 +197,8 @@ class FakeSource:
|
|||
def get_nvram(self):
|
||||
return self.nvram
|
||||
|
||||
download_volume = wvmConnect.download_volume # through self.wvm's streams
|
||||
|
||||
reads = 0
|
||||
|
||||
def get_status(self):
|
||||
|
|
|
|||
200
vrtManager/tests/test_backup.py
Normal file
200
vrtManager/tests/test_backup.py
Normal file
|
|
@ -0,0 +1,200 @@
|
|||
"""What a VM's backup holds (wvmBackup.backup_plan), the target's file
|
||||
names and space, and the small files' upload read back."""
|
||||
|
||||
import unittest
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
import libvirt
|
||||
|
||||
from vrtManager import util
|
||||
from vrtManager.backup import backup_file_names, check_target_space, put_file, wvmBackup
|
||||
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>"
|
||||
CDROM = "<disk type='file' device='cdrom'><source file='/iso/x.iso'/><target dev='sda'/></disk>"
|
||||
|
||||
|
||||
def error(code):
|
||||
err = libvirt.libvirtError("x")
|
||||
err.err = (code,)
|
||||
return err
|
||||
|
||||
|
||||
def domain(devices=QCOW + RAW + CDROM, os_extra=""):
|
||||
return (
|
||||
f"<domain><name>vm1</name><uuid>u</uuid><os><type>hvm</type>{os_extra}</os>"
|
||||
f"<devices>{devices}</devices></domain>"
|
||||
)
|
||||
|
||||
|
||||
def proxy(xml=None, live=None, state=libvirt.VIR_DOMAIN_SHUTOFF, managed_save=False):
|
||||
p = wvmBackup.__new__(wvmBackup) # no connection: only these calls
|
||||
p.wvm = MagicMock()
|
||||
p.instance = MagicMock()
|
||||
p.instance.name.return_value = "vm1"
|
||||
p.instance.state.return_value = [state, 0]
|
||||
p.instance.hasManagedSaveImage.return_value = managed_save
|
||||
persistent = xml or domain()
|
||||
p._XMLDesc = lambda flags: persistent if flags == PERSISTENT_XML else (live or persistent)
|
||||
pool = MagicMock()
|
||||
pool.name.return_value = "default"
|
||||
|
||||
def volume(path):
|
||||
vol = MagicMock()
|
||||
vol.info.return_value = [0, (10 if path.endswith("qcow2") else 20) * GIB, GIB]
|
||||
vol.storagePoolLookupByVolume.return_value = pool
|
||||
return vol
|
||||
|
||||
p.get_volume_by_path = MagicMock(side_effect=volume)
|
||||
return p
|
||||
|
||||
|
||||
class BackupPlanTestCase(unittest.TestCase):
|
||||
def refused(self, p, *texts):
|
||||
with self.assertRaises(util.OperationError) as caught:
|
||||
p.backup_plan()
|
||||
for text in texts:
|
||||
self.assertIn(text, str(caught.exception))
|
||||
|
||||
def test_a_vm_with_qcow2_and_raw_disks_and_a_cdrom(self):
|
||||
plan = proxy().backup_plan()
|
||||
self.assertEqual(
|
||||
plan["disks"],
|
||||
[
|
||||
{"dev": "vda", "path": "/pool/a.qcow2", "pool": "default", "format": "qcow2", "capacity": 10 * GIB},
|
||||
{"dev": "vdb", "path": "/pool/b.img", "pool": "default", "format": "raw", "capacity": 20 * GIB},
|
||||
],
|
||||
)
|
||||
self.assertEqual(plan["left_out"], [{"dev": "sda", "why": "CD-ROM: not copied"}])
|
||||
self.assertIsNone(plan["nvram"])
|
||||
self.assertIn("<name>vm1</name>", plan["definition"])
|
||||
|
||||
def test_the_nvram_is_named(self):
|
||||
xml = domain(os_extra="<nvram>/var/lib/libvirt/qemu/nvram/vm1_VARS.fd</nvram>")
|
||||
self.assertEqual(proxy(xml).backup_plan()["nvram"], "/var/lib/libvirt/qemu/nvram/vm1_VARS.fd")
|
||||
xml = domain(os_extra="<nvram><source file='/var/lib/libvirt/qemu/nvram/vm1_VARS.fd'/></nvram>")
|
||||
self.assertEqual(proxy(xml).backup_plan()["nvram"], "/var/lib/libvirt/qemu/nvram/vm1_VARS.fd")
|
||||
|
||||
def test_an_nvram_outside_libvirts_directory_is_refused(self):
|
||||
self.refused(proxy(domain(os_extra="<nvram>/srv/vm1_VARS.fd</nvram>")), "/srv/vm1_VARS.fd")
|
||||
|
||||
def test_refusals_name_the_reason_and_the_device(self):
|
||||
cases = {
|
||||
"encrypted": (
|
||||
"<disk type='file' device='disk'><driver type='qcow2'/><source file='/pool/a.qcow2'>"
|
||||
"<encryption format='luks'/></source><target dev='vda'/></disk>",
|
||||
("vda", "encrypted"),
|
||||
),
|
||||
"block": ("<disk type='block' device='disk'><source dev='/dev/sdb'/><target dev='vda'/></disk>", ("vda", "not a file")),
|
||||
"network": ("<disk type='network' device='disk'><source protocol='rbd' name='p/i'/><target dev='vda'/></disk>", ("vda", "not a file")),
|
||||
"volume": ("<disk type='volume' device='disk'><source pool='p' volume='v'/><target dev='vda'/></disk>", ("vda", "not a file")),
|
||||
"dir": ("<disk type='dir' device='disk'><source dir='/srv'/><target dev='vda'/></disk>", ("vda", "not a file")),
|
||||
"shareable": (
|
||||
"<disk type='file' device='disk'><driver type='raw'/><source file='/pool/b.img'/><target dev='vda'/><shareable/></disk>",
|
||||
("vda", "shareable"),
|
||||
),
|
||||
"other format": (
|
||||
"<disk type='file' device='disk'><driver type='vmdk'/><source file='/pool/c.vmdk'/><target dev='vda'/></disk>",
|
||||
("vda", "vmdk"),
|
||||
),
|
||||
"filesystem": (QCOW + "<filesystem type='mount'><source dir='/srv'/><target dir='t'/></filesystem>", ("host directory",)),
|
||||
"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")),
|
||||
}
|
||||
for name, (devices, texts) in cases.items():
|
||||
with self.subTest(name):
|
||||
self.refused(proxy(domain(devices)), *texts)
|
||||
for tag in ("kernel", "initrd", "dtb"):
|
||||
with self.subTest(tag):
|
||||
self.refused(proxy(domain(os_extra=f"<{tag}>/boot/x</{tag}>")), "kernel")
|
||||
|
||||
def test_a_saved_state_is_refused(self):
|
||||
self.refused(proxy(managed_save=True), "saved state")
|
||||
|
||||
def test_a_disk_in_no_pool_is_refused_by_name(self):
|
||||
p = proxy()
|
||||
p.get_volume_by_path.side_effect = error(libvirt.VIR_ERR_NO_STORAGE_VOL)
|
||||
self.refused(p, "vda", "/pool/a.qcow2", "no storage pool")
|
||||
|
||||
def test_another_lookup_error_is_raised(self):
|
||||
p = proxy()
|
||||
p.get_volume_by_path.side_effect = error(libvirt.VIR_ERR_INTERNAL_ERROR)
|
||||
with self.assertRaises(libvirt.libvirtError):
|
||||
p.backup_plan()
|
||||
|
||||
def test_live_and_persistent_disks_must_match(self):
|
||||
changed = QCOW.replace("/pool/a.qcow2", "/pool/new.qcow2") + RAW
|
||||
p = proxy(domain(changed), live=domain(), state=libvirt.VIR_DOMAIN_RUNNING)
|
||||
self.refused(p, "vda", "next start")
|
||||
p = proxy(domain(QCOW), live=domain(QCOW + RAW), state=libvirt.VIR_DOMAIN_RUNNING)
|
||||
self.refused(p, "next start")
|
||||
p = proxy(domain(), live=domain(), state=libvirt.VIR_DOMAIN_RUNNING)
|
||||
self.assertEqual(len(p.backup_plan()["disks"]), 2)
|
||||
|
||||
|
||||
class FilesTestCase(unittest.TestCase):
|
||||
def test_file_names(self):
|
||||
uuid = "00000000-0000-4000-8000-000000000001"
|
||||
disks = [{"dev": "vda", "format": "qcow2"}, {"dev": "vdb", "format": "raw"}]
|
||||
self.assertEqual(
|
||||
backup_file_names(uuid, disks, nvram=True),
|
||||
{
|
||||
"disks": {"vda": f"wvc-{uuid}-vda.qcow2", "vdb": f"wvc-{uuid}-vdb.raw"},
|
||||
"nvram": f"wvc-{uuid}-nvram.fd",
|
||||
"domain": f"wvc-{uuid}-domain.xml",
|
||||
"manifest": f"wvc-{uuid}-manifest.json",
|
||||
},
|
||||
)
|
||||
self.assertIsNone(backup_file_names(uuid, disks, nvram=False)["nvram"])
|
||||
|
||||
def test_space_counts_virtual_capacity_and_the_margin(self):
|
||||
# 2 x 10 GiB plus max(10 % of it, 1 GiB) = 22 GiB
|
||||
pool = MagicMock()
|
||||
pool.name.return_value = "b1"
|
||||
disks = [{"capacity": 10 * GIB}, {"capacity": 10 * GIB}]
|
||||
pool.info.return_value = [2, 100 * GIB, 0, int(21.9 * GIB)]
|
||||
with self.assertRaisesRegex(util.OperationError, "Storage pool b1 has 21.9 GiB free; the backup needs 22.0 GiB"):
|
||||
check_target_space(pool, disks, 10, 1)
|
||||
pool.info.return_value = [2, 100 * GIB, 0, 22 * GIB]
|
||||
check_target_space(pool, disks, 10, 1)
|
||||
pool.refresh.assert_called_with(0)
|
||||
|
||||
def test_put_file_refuses_a_different_read_back(self):
|
||||
conn, pool = MagicMock(), MagicMock()
|
||||
pool.storageVolLookupByName.side_effect = error(libvirt.VIR_ERR_NO_STORAGE_VOL)
|
||||
conn.download_volume.return_value = b"other"
|
||||
with self.assertRaisesRegex(util.OperationError, "wvc-x-domain.xml"):
|
||||
put_file(conn, pool, "wvc-x-domain.xml", b"data", (107, 107))
|
||||
conn.upload_volume.return_value.delete.assert_called_once_with(0)
|
||||
|
||||
def test_put_file_returns_the_sha256_and_replaces_a_volume(self):
|
||||
conn, pool = MagicMock(), MagicMock()
|
||||
old = pool.storageVolLookupByName.return_value
|
||||
conn.download_volume.return_value = b"data"
|
||||
self.assertEqual(
|
||||
put_file(conn, pool, "wvc-x-domain.xml", b"data", (107, 108)),
|
||||
"3a6eb0790f39ac87c94f3856b2dd2c5d110e6811602261a9a923d3bb23adc8b7",
|
||||
)
|
||||
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))
|
||||
|
||||
def test_upload_volume_sets_the_owner(self):
|
||||
from lxml import etree
|
||||
|
||||
from vrtManager.connection import wvmConnect
|
||||
|
||||
conn = wvmConnect.__new__(wvmConnect)
|
||||
conn.wvm = MagicMock()
|
||||
pool = MagicMock()
|
||||
conn.upload_volume(pool, "f", b"ab", owner=(107, 108), mode="0600")
|
||||
volume = etree.fromstring(pool.createXML.call_args.args[0])
|
||||
self.assertEqual(volume.findtext("target/permissions/owner"), "107")
|
||||
self.assertEqual(volume.findtext("target/permissions/group"), "108")
|
||||
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"))
|
||||
|
|
@ -273,6 +273,16 @@ class CreateCloneTargetTestCase(unittest.TestCase):
|
|||
self.assertEqual(volume.findtext("target/permissions/owner"), "107")
|
||||
self.assertEqual(volume.findtext("target/permissions/group"), "108")
|
||||
self.assertEqual(flags, 0)
|
||||
self.assertEqual(volume.findtext("target/compat"), "1.1")
|
||||
|
||||
def test_a_raw_volume_has_no_qcow2_features(self):
|
||||
p = proxy()
|
||||
p.wvm.storagePoolLookupByName.return_value = p.pool
|
||||
p.create_clone_target({"pool": "default", "name": "copy-vdb.raw", "capacity": GIB, "format": "raw"}, 107, 107)
|
||||
volume = etree.fromstring(p.pool.createXML.call_args.args[0])
|
||||
self.assertEqual(volume.find("target/format").get("type"), "raw")
|
||||
self.assertIsNone(volume.find("target/compat"))
|
||||
self.assertIsNone(volume.find("target/features"))
|
||||
|
||||
|
||||
class DefineCloneTestCase(unittest.TestCase):
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue