python-compute/computelib/session.py

53 lines
1.8 KiB
Python
Raw Normal View History

2023-07-22 23:59:49 +03:00
from contextlib import AbstractContextManager
2023-06-17 20:07:50 +03:00
import libvirt
2023-09-23 21:24:56 +03:00
from .exceptions import LibvirtSessionError, VMNotFound
2023-09-02 00:52:28 +03:00
from .vm import GuestAgent, VirtualMachine
2023-08-31 20:37:41 +03:00
from .volume import StoragePool
2023-07-22 23:59:49 +03:00
class LibvirtSession(AbstractContextManager):
2023-08-24 22:36:12 +03:00
2023-08-31 20:37:41 +03:00
def __init__(self, uri: str = 'qemu:///system'):
2023-09-23 21:24:56 +03:00
try:
self.connection = libvirt.open(uri)
except libvirt.libvirtError as err:
raise LibvirtSessionError(err) from err
2023-07-22 23:59:49 +03:00
def __enter__(self):
return self
def __exit__(self, exception_type, exception_value, exception_traceback):
self.close()
2023-06-17 20:07:50 +03:00
2023-09-23 21:24:56 +03:00
def get_machine(self, name: str) -> VirtualMachine:
2023-08-27 23:42:56 +03:00
try:
2023-09-23 21:24:56 +03:00
return VirtualMachine(self.connection.lookupByName(name))
2023-08-27 23:42:56 +03:00
except libvirt.libvirtError as err:
if err.get_error_code() == libvirt.VIR_ERR_NO_DOMAIN:
2023-08-31 20:37:41 +03:00
raise VMNotFound(name) from err
raise LibvirtSessionError(err) from err
2023-08-27 23:42:56 +03:00
2023-09-23 21:24:56 +03:00
def list_machines(self) -> list[VirtualMachine]:
return [VirtualMachine(dom) for dom in
self.connection.listAllDomains()]
2023-08-31 20:37:41 +03:00
2023-09-23 21:24:56 +03:00
def get_guest_agent(self, name: str,
timeout: int | None = None) -> GuestAgent:
2023-08-31 20:37:41 +03:00
try:
2023-09-23 21:24:56 +03:00
return GuestAgent(self.connection.lookupByName(name), timeout)
2023-08-31 20:37:41 +03:00
except libvirt.libvirtError as err:
2023-09-23 21:24:56 +03:00
if err.get_error_code() == libvirt.VIR_ERR_NO_DOMAIN:
raise VMNotFound(name) from err
2023-08-31 20:37:41 +03:00
raise LibvirtSessionError(err) from err
def get_storage_pool(self, name: str) -> StoragePool:
2023-09-23 21:24:56 +03:00
return StoragePool(self.connection.storagePoolLookupByName(name))
2023-08-31 20:37:41 +03:00
2023-09-23 21:24:56 +03:00
def list_storage_pools(self) -> list[StoragePool]:
2023-08-31 20:37:41 +03:00
return [StoragePool(p) for p in self.connection.listStoragePools()]
def close(self) -> None:
self.connection.close()