79 lines
1.9 KiB
Python
79 lines
1.9 KiB
Python
import os
|
|
from pathlib import Path
|
|
from time import sleep
|
|
from typing import List, Optional
|
|
|
|
import libvirt
|
|
from libvirt import virDomain, virStoragePool
|
|
|
|
from virt import spawn_vm
|
|
from wireguard_mesh import create_mesh
|
|
|
|
|
|
def cleanup(vms: List[virDomain], storage_pool: Optional[virStoragePool] = None):
|
|
for vm in vms:
|
|
try:
|
|
vm.destroy()
|
|
except libvirt.libvirtError as ex:
|
|
print(f'error shutting down {vm.name()}: {ex.get_error_message()}')
|
|
# vm.undefine()
|
|
|
|
if storage_pool is not None:
|
|
|
|
for volume in storage_pool.listAllVolumes():
|
|
print(f'deleting volume: {volume.path()}')
|
|
volume.delete()
|
|
storage_pool.destroy()
|
|
# storage_pool.undefine()
|
|
|
|
|
|
def main():
|
|
nodes = create_mesh()
|
|
print(nodes)
|
|
|
|
tmp_dir = '/tmp/node_configs'
|
|
|
|
p = Path(tmp_dir)
|
|
if p.exists():
|
|
for file in p.iterdir():
|
|
file.unlink()
|
|
p.rmdir()
|
|
|
|
os.makedirs(tmp_dir)
|
|
|
|
for node in nodes.values():
|
|
with open(p / f'{node.name}.conf', 'w+') as fh:
|
|
fh.write(node.config)
|
|
|
|
libvirt_conn_uri = 'qemu:///system'
|
|
conn = libvirt.open(libvirt_conn_uri)
|
|
|
|
# TODO map to all
|
|
storage_pool_path = Path('/tmp/test')
|
|
vms: List[virDomain] = [
|
|
spawn_vm(conn, node.name, storage_pool_path, node.config)
|
|
for node in nodes.values()
|
|
]
|
|
|
|
print('vms created, resuming cpus...')
|
|
|
|
for vm in vms:
|
|
vm.resume()
|
|
|
|
try:
|
|
while True:
|
|
sleep(1)
|
|
except KeyboardInterrupt:
|
|
print('caught SIGTERM, finishing...')
|
|
|
|
storage_pool: Optional[virStoragePool] = None
|
|
storage_pool_name = 'wireguard_test'
|
|
if storage_pool_name in (p.name() for p in conn.listAllStoragePools()):
|
|
storage_pool = conn.storagePoolLookupByName(storage_pool_name)
|
|
|
|
cleanup(vms, storage_pool)
|
|
|
|
|
|
if __name__ == '__main__':
|
|
main()
|