1
0
Fork 0
mirror of https://github.com/retspen/webvirtcloud synced 2026-12-02 08:56:07 +00:00
webvirtcloud/vrtManager/storage.py
catborise aeef837afa feat(storages): the pool page tells which VMs use each volume
A volume left behind (a disk kept when its VM was deleted, an old image) was
not told apart from one a VM needs until its deletion was refused. The pool
page now has a "Used by" column: the VMs of this host whose disks, UEFI
variables, saved state or snapshots are the volume or are built on it, "In
use" for one only another volume is built on, else "Not used on this host";
buttons list each kind, and a VM's name finds its volumes. Its deletion still
asks the other hosts, as one sharing the storage may use it. When the host's
VMs cannot be read the page lists the volumes without the column.

The scan that refuses deleting a used volume now also counts a VM's UEFI
variables file and a snapshot's block device, and reads each VM once.
2026-11-20 08:29:33 +03:00

439 lines
18 KiB
Python

from django.utils.translation import gettext_noop
import contextlib
import libvirt
from lxml import etree
from vrtManager import util
from vrtManager.connection import wvmConnect
# pools whose volumes are files: they take any image format
FILE_POOL_TYPES = ("dir", "fs", "netfs")
def rbd_source_children(pool):
"""The <auth> and <host> elements of an RBD disk's <source>, as XML text:
the disk reaches Ceph as its pool does, with its user, its secret (by
uuid or usage) and its monitors."""
source = etree.fromstring(pool.XMLDesc(0)).find("source")
children = [etree.Element("host", host.attrib) for host in source.findall("host")]
auth = source.find("auth")
if auth is not None:
disk_auth = etree.Element("auth", username=auth.get("username"))
secret = auth.find("secret")
etree.SubElement(disk_auth, "secret", type=auth.get("type"),
**{key: value for key, value in secret.attrib.items() if key in ("uuid", "usage")})
children.insert(0, disk_auth)
return "".join(etree.tostring(child, encoding="unicode") for child in children)
def volume_details(vol):
"""A volume's name, capacity (size), allocation, format and path, from its XML:
one libvirt call, which refreshes the volume as info() does. Logical and
iSCSI volumes have no format (None)."""
def read(doc):
return {
"name": util.get_xpath(doc, "/volume/name"),
"size": int(util.get_xpath(doc, "/volume/capacity")),
"allocation": int(util.get_xpath(doc, "/volume/allocation")),
"type": util.get_xpath(doc, "/volume/target/format/@type"),
"path": util.get_xpath(doc, "/volume/target/path"),
}
return util.get_xml_path(vol.XMLDesc(0), func=read)
class wvmStorages(wvmConnect):
def get_storages_info(self):
"""Each pool's state, autostart, type, path (an RBD pool's Ceph pool),
volume count, size, free space and the percent used. An active pool
is refreshed first: libvirt measures its space only when it is
refreshed, so two hosts sharing a pool's storage told different free
space, each as of its own last refresh."""
get_storages = self.get_storages()
storages = []
for pool in get_storages:
stg = self.get_storage(pool)
stg_status = stg.isActive()
if stg_status:
with contextlib.suppress(libvirt.libvirtError): # refused while a volume is cloned in it
stg.refresh(0)
doc = etree.fromstring(stg.XMLDesc(0))
stg_vol = len(stg.listVolumes()) if stg_status else None
_state, stg_size, _allocation, stg_free = stg.info()
storages.append(
{
"name": pool,
"status": stg_status,
"autostart": stg.autostart(),
"type": doc.get("type"),
"path": util.get_xpath(doc, "/pool/target/path") or util.get_xpath(doc, "/pool/source/name"),
"volumes": stg_vol,
"size": stg_size,
"free": stg_free,
"used_percent": (stg_size - stg_free) * 100 / stg_size if stg_size else 0,
}
)
return storages
def define_storage(self, xml, flags):
"""Define the pool, start it with flags and set it to autostart. A
pool that does not start is undefined again, so its name stays free
for another try."""
stg = self.wvm.storagePoolDefineXML(xml, 0)
try:
stg.create(flags)
except libvirt.libvirtError:
stg.undefine()
raise
stg.setAutostart(1)
return stg
def get_pool_by_target(self, target):
pool_names = self.get_storages()
for pool_name in pool_names:
stg = wvmStorage(self.host, self.login, self.passwd, self.conn, pool_name)
if stg.get_target_path() == target:
return self.get_storage(pool_name)
if stg.get_type() == "rbd" and stg.get_source_name() == target:
return self.get_storage(pool_name)
return None
def create_storage(self, stg_type, name, source, target):
xml = f"""<pool type='{stg_type}'>
<name>{name}</name>"""
if stg_type == "logical":
xml += f"""<source>
<device path='{source}'/>
<name>{name}</name>
<format type='lvm2'/>
</source>"""
if stg_type == "logical":
target = f"/dev/{name}"
xml += f"""
<target>
<path>{target}</path>
</target>
</pool>"""
# builds the dir pool's directory or the logical pool's volume group
try:
return self.define_storage(xml, libvirt.VIR_STORAGE_POOL_CREATE_WITH_BUILD)
except libvirt.libvirtError as err:
# libvirt refuses a device that holds data; erasing it is left to the host's admin:
# with an overwrite, libvirt clears the partition table even of a disk in use
if stg_type != "logical" or err.get_error_code() != libvirt.VIR_ERR_STORAGE_POOL_BUILT:
raise
raise util.OperationError(gettext_noop(
"Device %(device)s already holds data: a partition table, a file system or a volume group. "
"If it is the right device, erase it on the host with \"wipefs -a %(device)s\" and try again."),
device=source) from err
def create_storage_ceph(
self, stg_type, name, ceph_pool, ceph_host, ceph_user, secret
):
ceph_pool, ceph_host, ceph_user, secret = map(util.xml_escape, (ceph_pool, ceph_host, ceph_user, secret))
xml = f"""
<pool type='{stg_type}'>
<name>{name}</name>
<source>
<name>{ceph_pool}</name>
<host name='{ceph_host}' port='6789'/>
<auth username='{ceph_user}' type='ceph'>
<secret uuid='{secret}'/>
</auth>
</source>
</pool>
"""
self.define_storage(xml, 0)
def create_storage_netfs(
self, stg_type, name, netfs_host, source, source_format, target
):
netfs_host, source_format = util.xml_escape(netfs_host), util.xml_escape(source_format)
xml = f"""
<pool type='{stg_type}'>
<name>{name}</name>
<source>
<host name='{netfs_host}'/>
<dir path='{source}'/>
<format type='{source_format}'/>
</source>
<target>
<path>{target}</path>
</target>
</pool>
"""
# builds the mount point
return self.define_storage(xml, libvirt.VIR_STORAGE_POOL_CREATE_WITH_BUILD)
class wvmStorage(wvmConnect):
def __init__(self, host, login, passwd, conn, pool):
wvmConnect.__init__(self, host, login, passwd, conn)
self.pool = self.get_storage(pool)
def get_name(self):
return self.pool.name()
def get_status(self):
status = [
"Not running",
"Initializing pool, not available",
"Running normally",
"Running degraded",
"Inaccessible", # running, but its storage cannot be reached: a share whose server is gone
]
try:
return status[self.pool.info()[0]]
except IndexError: # a state newer than these
return "Unknown"
def get_size(self):
_state, capacity, _allocation, available = self.pool.info()
return [capacity, available]
def _XMLDesc(self, flags):
return self.pool.XMLDesc(flags)
def _createXML(self, xml, flags):
self.pool.createXML(xml, flags)
def _define(self, xml):
return self.wvm.storagePoolDefineXML(xml, 0)
def is_active(self):
return self.pool.isActive()
def get_uuid(self):
return self.pool.UUIDString()
def start(self):
return self.pool.create(0)
def stop(self):
"""Refused while it holds a disk of a running VM, named by the pool
or by a volume's path: that VM would lose the disk."""
name = self.pool.name()
paths = {vol.path() for vol in self.pool.listAllVolumes()}
vms = self.domains_using(
lambda domain: domain.xpath("devices/disk/source[@pool=$name]", name=name)
or paths.intersection(self._source_paths(domain)),
running_only=True,
)
if vms:
raise util.OperationError(gettext_noop("Pool %(name)s holds disks of the running VMs %(vms)s; shut them down first"), name=name, vms=', '.join(vms))
return self.pool.destroy()
def delete(self):
"""Refused while a VM's definition names it for a disk: that VM would
no longer start. So is a disk given by its path in a pool that mounts
or activates its storage (a share, a file system, an LVM group): the
path is gone with the pool. A directory pool's files stay; the device
directories of iSCSI and disk pools are every pool's, not this one's."""
name, kind = self.pool.name(), self.get_type()
target = (self.get_target_path() or "").rstrip("/")
under = (target + "/",) if kind in ("fs", "netfs", "logical") and target else ()
if kind == "logical" and (group := self.get_source_name()):
under += ("/dev/mapper/" + group.replace("-", "--") + "-",) # device mapper's name of its volumes
def needs(domain):
return domain.xpath("devices/disk/source[@pool=$name]", name=name) or any(
path.startswith(under) for path in domain.xpath("devices/disk//source/@file | devices/disk//source/@dev"))
if vms := self.domains_using(needs):
raise util.OperationError(gettext_noop("VMs %(vms)s have disks in pool %(name)s and would no longer start; detach those disks first"), vms=', '.join(vms), name=name)
self.pool.undefine()
def get_autostart(self):
return self.pool.autostart()
def set_autostart(self, value):
self.pool.setAutostart(value)
def get_type(self):
return util.get_xml_path(self._XMLDesc(0), "/pool/@type")
def get_target_path(self):
return util.get_xml_path(self._XMLDesc(0), "/pool/target/path")
def get_source_name(self):
return util.get_xml_path(self._XMLDesc(0), "/pool/source/name")
def get_volumes(self):
return self.pool.listVolumes()
def get_volume(self, name):
return self.pool.storageVolLookupByName(name)
def _vol_XMLDesc(self, name):
vol = self.get_volume(name)
return vol.XMLDesc(0)
def check_unused_elsewhere(self, name, elsewhere):
"""Refuses a volume a VM of another host sharing this storage uses:
elsewhere(paths) gives those the other hosts use
(instances.utils.paths_used_on_other_computes). Asked before this
host's lock, which a host that does not answer would hold meanwhile."""
path = self.pool.storageVolLookupByName(name).path()
if path in elsewhere([path]):
raise util.InUse(gettext_noop("Volume %(name)s is in use on another compute that shares this storage"), name=name)
def volume_users(self):
"""{path: VM names, sorted} of the paths this host uses (path_users): none for
a backing file only another volume is built on."""
return {path: sorted(names) for path, names in self.path_users().items()}
def del_volume(self, name):
"""libvirt deletes any volume; one a VM of this host still needs is refused."""
vol = self.pool.storageVolLookupByName(name)
if vol.path() in self.paths_in_use():
raise util.InUse(gettext_noop("Volume %(name)s is in use: a VM's disk, a backing file or a snapshot's file"), name=name)
vol.delete(0)
def get_volume_format_type(self, name):
vol_xml = self._vol_XMLDesc(name)
return util.get_xml_path(vol_xml, "/volume/target/format/@type")
def get_volume_type(self, name):
vol_xml = self._vol_XMLDesc(name)
return util.get_xml_path(vol_xml, "/volume/@type")
def refresh(self):
return self.pool.refresh(0)
def get_volume_details(self, volname):
"""The volume's details (volume_details), the pool refreshed first."""
with contextlib.suppress(libvirt.libvirtError): # refused while a volume is cloned in the pool
self.refresh()
return volume_details(self.get_volume(volname))
def update_volumes(self):
"""Every volume's details (volume_details) by name, the pool refreshed
first: two calls and one per volume, where a lookup, info() and the
XML of each took six. A volume deleted meanwhile is left out."""
with contextlib.suppress(libvirt.libvirtError): # refused while a volume is cloned in the pool
self.refresh()
volumes = []
for vol in self.pool.listAllVolumes(0):
try:
volumes.append(volume_details(vol))
except libvirt.libvirtError as err:
if err.get_error_code() != libvirt.VIR_ERR_NO_STORAGE_VOL:
raise
return sorted(volumes, key=lambda volume: volume["name"])
def create_volume(
self,
name,
size,
vol_fmt="qcow2",
metadata=False,
disk_owner_uid=0,
disk_owner_gid=0,
):
size = int(size) * 1073741824
if self.get_type() in FILE_POOL_TYPES:
name += f".{vol_fmt}" if vol_fmt in ("qcow", "qcow2") else ".img"
alloc = 0
else: # a block device, an LVM volume or an RBD image is raw and allocated whole
vol_fmt = "raw"
alloc = size
metadata = False
if vol_fmt == "unknown":
vol_fmt = "raw"
xml = f"""
<volume>
<name>{util.xml_escape(name)}</name>
<capacity>{size}</capacity>
<allocation>{alloc}</allocation>
<target>
<format type='{vol_fmt}'/>
<permissions>
<owner>{disk_owner_uid}</owner>
<group>{disk_owner_gid}</group>
<mode>0644</mode>
<label>virt_image_t</label>
</permissions>"""
if vol_fmt == "qcow2":
xml += """
<compat>1.1</compat>
<features>
<lazy_refcounts/>
</features>"""
xml += """</target>
</volume>"""
self._createXML(xml, metadata)
return name
def clone_name(self, target_file, vol_fmt, file_suffix="img"):
"""The name clone_volume gives a copy: a dir pool adds the format's suffix."""
if self.get_type() not in FILE_POOL_TYPES:
return target_file
if vol_fmt in ("qcow", "qcow2"):
return f"{target_file}.{vol_fmt}"
return f"{target_file}.{file_suffix}" if file_suffix else target_file
def refuse_running_copy(self, name):
"""A volume a running guest writes is not copied: the copy would mix
instants."""
path, pool = self.get_volume(name).path(), self.pool.name()
# a disk names it by its path (an RBD image by pool/image) or by its pool and name
uses = "devices/disk/source[@file=$p or @dev=$p or @name=$p or (@pool=$pool and @volume=$v)]"
if vms := self.domains_using(lambda domain: domain.xpath(uses, p=path, pool=pool, v=name), running_only=True):
raise util.OperationError(gettext_noop("The running VMs %(vms)s use volume %(name)s; shut them down to copy it"),
vms=", ".join(vms), name=name)
def read_volume(self, name):
"""The size of volume name and its bytes, read in chunks: a running
guest's volume is refused, as for a copy."""
self.refuse_running_copy(name)
vol = self.get_volume(name)
size = vol.infoFlags(libvirt.VIR_STORAGE_VOL_GET_PHYSICAL)[2] # a file's length, not its capacity
stream = self.wvm.newStream(0)
vol.download(stream, 0, 0, 0)
def chunks():
try:
while data := stream.recv(1 << 20):
yield data
stream.finish()
except BaseException: # also a download the browser left (GeneratorExit)
with contextlib.suppress(libvirt.libvirtError):
stream.abort()
raise
return size, chunks()
def clone_volume(self, vol, target_file, vol_fmt=None, metadata=False, mode="0644", disk_owner_uid=0, disk_owner_gid=0):
"""A copy named target_file in this pool of vol, a volume of this pool
or another; its path. clone_name gives a dir pool's name its suffix."""
if not vol_fmt:
vol_fmt = util.get_xml_path(vol.XMLDesc(0), "/volume/target/format/@type")
size = 0 # a file copy takes the source's size and grows as written
if self.get_type() not in FILE_POOL_TYPES:
# a block device, an LVM volume or an RBD image is raw and allocated whole:
# a sparse LVM volume is a snapshot that fails once the copy fills it
vol_fmt = "raw"
size = vol.info()[1]
metadata = metadata and vol_fmt == "qcow2" # libvirt preallocates qcow2 metadata only
xml = f"""
<volume>
<name>{util.xml_escape(target_file)}</name>
<capacity>{size}</capacity>
<allocation>{size}</allocation>
<target>
<format type='{vol_fmt}'/>
<permissions>
<owner>{disk_owner_uid}</owner>
<group>{disk_owner_gid}</group>
<mode>{mode}</mode>
<label>virt_image_t</label>
</permissions>"""
if vol_fmt == "qcow2":
xml += """
<compat>1.1</compat>
<features>
<lazy_refcounts/>
</features>"""
xml += """ </target>
</volume>"""
return self.pool.createXMLFrom(xml, vol, metadata).path()