python-compute/node_agent/session.py

52 lines
1.5 KiB
Python
Raw Normal View History

2023-07-22 23:59:49 +03:00
from contextlib import AbstractContextManager
2023-08-24 22:36:12 +03:00
from pathlib import Path
2023-07-22 23:59:49 +03:00
2023-06-17 20:07:50 +03:00
import libvirt
2023-07-22 23:59:49 +03:00
from .config import ConfigLoader
2023-07-29 15:35:36 +03:00
class LibvirtSessionError(Exception):
2023-08-24 22:36:12 +03:00
"""Something went wrong while connecting to libvirtd."""
2023-07-22 23:59:49 +03:00
class LibvirtSession(AbstractContextManager):
2023-08-24 22:36:12 +03:00
2023-07-22 23:59:49 +03:00
def __init__(self, config: Path | None = None):
self.config = ConfigLoader(config)
self.session = self._connect(self.config['libvirt']['uri'])
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-07-22 23:59:49 +03:00
def _connect(self, connection_uri: str):
try:
return libvirt.open(connection_uri)
except libvirt.libvirtError as err:
raise LibvirtSessionError(
2023-08-24 22:36:12 +03:00
f'Failed to open connection to the hypervisor: {err}') from err
2023-06-17 20:07:50 +03:00
2023-07-22 23:59:49 +03:00
def close(self) -> None:
self.session.close()
2023-08-27 23:42:56 +03:00
def list_domains(self):
return self.session.listAllDomains()
def get_domain(self, name: str) -> libvirt.virDomain:
try:
return self.session.lookupByName(name)
except libvirt.libvirtError as err:
if err.get_error_code() == libvirt.VIR_ERR_NO_DOMAIN:
raise VMNotFound(name)
else:
raise LibvirtSessionError(err)
def get_storage_pool(self, name: str) -> libvirt.virStoragePool:
try:
return self.session.storagePoolLookupByName(name)
except libvirt.libvirtError as err:
raise LibvirtSessionError(err)