python-compute/computelib/volume/volume.py

81 lines
2.1 KiB
Python
Raw Normal View History

2023-08-31 20:37:41 +03:00
from dataclasses import dataclass
from time import time
2023-08-27 23:42:56 +03:00
import libvirt
2023-09-23 21:24:56 +03:00
from lxml import etree
2023-08-31 20:37:41 +03:00
from lxml.builder import E
2023-08-27 23:42:56 +03:00
2023-08-31 20:37:41 +03:00
@dataclass
2023-08-27 23:42:56 +03:00
class VolumeInfo:
2023-08-31 20:37:41 +03:00
name: str
path: str
capacity: int
def to_xml(self) -> str:
unixtime = str(int(time()))
xml = E.volume(type='file')
xml.append(E.name(self.name))
xml.append(E.key(self.path))
xml.append(E.source())
xml.append(E.capacity(str(self.capacity * 1024 * 1024), unit='bytes'))
xml.append(E.allocation('0'))
xml.append(E.target(
E.path(self.path),
E.format(type='qcow2'),
E.timestamps(
E.atime(unixtime),
E.mtime(unixtime),
E.ctime(unixtime)),
E.compat('1.1'),
E.features(E.lazy_refcounts())
))
2023-09-23 21:24:56 +03:00
return etree.tostring(xml, encoding='unicode', pretty_print=True)
@dataclass
class DiskInfo:
target: str
path: str
readonly: bool = False
def to_xml(self) -> str:
xml = E.disk(type='file', device='disk')
xml.append(E.driver(name='qemu', type='qcow2', cache='writethrough'))
xml.append(E.source(file=self.path))
xml.append(E.target(dev=self.target, bus='virtio'))
if self.readonly:
xml.append(E.readonly())
return etree.tostring(xml, encoding='unicode', pretty_print=True)
2023-08-27 23:42:56 +03:00
class Volume:
2023-08-31 20:37:41 +03:00
def __init__(self, pool: libvirt.virStoragePool,
vol: libvirt.virStorageVol):
2023-08-27 23:42:56 +03:00
self.pool = pool
2023-08-31 20:37:41 +03:00
self.vol = vol
@property
def name(self) -> str:
return self.vol.name()
@property
def path(self) -> str:
return self.vol.path()
def dump_xml(self) -> str:
return self.vol.XMLDesc()
2023-08-27 23:42:56 +03:00
2023-08-31 20:37:41 +03:00
def clone(self, vol_info: VolumeInfo) -> None:
self.pool.createXMLFrom(
vol_info.to_xml(),
self.vol,
flags=libvirt.VIR_STORAGE_VOL_CREATE_PREALLOC_METADATA)
2023-08-27 23:42:56 +03:00
2023-08-31 20:37:41 +03:00
def resize(self, capacity: int):
"""Resize volume to `capacity`. Unit is mebibyte."""
self.vol.resize(capacity * 1024 * 1024)
2023-08-27 23:42:56 +03:00
2023-08-31 20:37:41 +03:00
def delete(self) -> None:
self.vol.delete()