#!/usr/bin/python3

import subprocess
import json
import syslog
import traceback

syslog.openlog('inconsistent-bitmaps-remover')


def handle_vm(vm):
    syslog.syslog('Handling vm: ' + vm)

    result = subprocess.run(['virsh', 'qemu-monitor-command', vm,
                            '{"execute": "query-version"}'],
                            check=True, stdout=subprocess.PIPE)
    result = json.loads(result.stdout)['return']

    syslog.syslog('  version: ' + result['package'])

    if result['package'] != 'qemu-kvm-vz-2.12.0-33.vz7.14':
        return

    result = subprocess.run(['virsh', 'qemu-monitor-command', vm,
                            '{"execute": "query-block"}'],
                            check=True, stdout=subprocess.PIPE)
    result = json.loads(result.stdout)['return']

    for disk in result:
        if 'device' not in disk:
            continue
        syslog.syslog('  Handling disk: ' + disk['device'])
        if 'dirty-bitmaps' in disk:
            for b in disk['dirty-bitmaps']:
                if 'inconsistent' in b and b['inconsistent']:
                    syslog.syslog('    Found inconsistent bitmap: "{}", '
                                  'removing:'.format(b['name']))
                    args = ['virsh', 'qemu-monitor-command', vm,
                            '{"execute": "block-dirty-bitmap-remove", '
                            '"arguments": {"node": "' + disk['device'] +
                            '", "name": "' + b['name'] + '"}}']
                    syslog.syslog('    Run command: ' +
                                  ' '.join(args[:3]) + " '" + args[3] + "'")
                    subprocess.run(args)


result = subprocess.run(['virsh', 'list'], check=True, stdout=subprocess.PIPE,
                        encoding='utf-8')
lines = result.stdout.split('\n')
vms = [line.split()[1] for line in lines[2:-2]]

syslog.syslog('found vms: ' + str(vms))

for vm in vms:
    try:
        handle_vm(vm)
    except Exception:
        syslog.syslog(syslog.LOG_ERR, traceback.format_exc())
