python-compute/node_agent/utils/vmctl.py

74 lines
1.9 KiB
Python
Raw Normal View History

2023-07-22 23:59:49 +03:00
"""
Manage virtual machines.
Usage: na-vmctl [options] status <machine>
na-vmctl [options] is-running <machine>
na-vmctl [options] start <machine>
na-vmctl [options] shutdown <machine> [-f|--force] [-9|--sigkill]
Options:
-c, --config <file> Config file [default: /etc/node-agent/config.yaml]
2023-07-29 15:10:30 +03:00
-l, --loglvl <lvl> Logging level
2023-07-22 23:59:49 +03:00
-f, --force Force action. On shutdown calls graceful destroy()
-9, --sigkill Send SIGKILL to QEMU process. Not affects without --force
"""
import sys
import pathlib
import logging
2023-07-28 01:01:32 +03:00
import libvirt
2023-07-22 23:59:49 +03:00
from docopt import docopt
2023-07-29 14:29:37 +03:00
from ..main import LibvirtSession
from ..vm import VirtualMachine
from ..exceptions import VMError, VMNotFound
2023-07-22 23:59:49 +03:00
logger = logging.getLogger(__name__)
levels = logging.getLevelNamesMapping()
class Color:
RED = '\033[31m'
GREEN = '\033[32m'
YELLOW = '\033[33m'
NONE = '\033[0m'
def cli():
args = docopt(__doc__)
config = pathlib.Path(args['--config']) or None
2023-07-29 15:10:30 +03:00
loglvl = None
2023-07-28 01:01:32 +03:00
machine = args['<machine>']
2023-07-22 23:59:49 +03:00
2023-07-29 15:10:30 +03:00
if args['--loglvl']:
loglvl = args['--loglvl'].upper()
2023-07-22 23:59:49 +03:00
if loglvl in levels:
logging.basicConfig(level=levels[loglvl])
with LibvirtSession(config) as session:
try:
2023-07-28 01:01:32 +03:00
vm = VirtualMachine(session, machine)
2023-07-22 23:59:49 +03:00
if args['status']:
print(vm.status)
if args['is-running']:
if vm.is_running:
print('running')
else:
sys.exit(vm.status)
if args['start']:
vm.start()
print(f'{vm.name} started')
if args['shutdown']:
vm.shutdown(force=args['--force'], sigkill=args['sigkill'])
except VMNotFound as nferr:
2023-07-28 01:01:32 +03:00
sys.exit(f'{Color.RED}VM {machine} not found.{Color.NONE}')
2023-07-22 23:59:49 +03:00
except VMError as vmerr:
sys.exit(f'{Color.RED}{vmerr}{Color.NONE}')
if __name__ == '__main__':
cli()