python-compute/node_agent/volume/volume.py

65 lines
1.7 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-08-31 20:37:41 +03:00
from lxml.builder import E
from lxml.etree import tostring
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())
))
return 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()