#!/usr/bin/python3
# group: rw auto quick
#
# Test removing persistent bitmap from backing
#
# Copyright (c) 2021 Virtuozzo International GmbH.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#

import time
import re

import iotests

iotests._verify_image_format(supported_fmts=['qcow2'])

vm = iotests.VM()
vm.add_drive_raw("driver=raw,id=drive0,file.driver=blkdebug,"
                 "file.image.driver=null-co,file.image.size=100M")
vm.launch()

vm.qmp('x-vz-set-block-latency-log-threshold', threshold_ms=200)

# Fast request, not logged:
result = vm.hmp_qemu_io('drive0', 'break read_aio A')
result = vm.hmp_qemu_io('drive0', 'aio_read 0 1M')
time.sleep(0.1)
result = vm.hmp_qemu_io('drive0', 'resume A')

# Slow requests (thanks to sleep(1)), logged:
result = vm.hmp_qemu_io('drive0', 'break write_aio A')
result = vm.hmp_qemu_io('drive0', 'aio_write 0 1M')
result = vm.hmp_qemu_io('drive0', 'break read_aio B')
result = vm.hmp_qemu_io('drive0', 'aio_read 1M 2M')
time.sleep(0.3)
result = vm.qmp('x-vz-query-block-io-requests', node_name='drive0')
for x in result['return']:
    # to get stable number for output
    if 250 < x['duration-ms'] < 400:
        x['duration-ms'] = '~300'
    print(x)

result = vm.hmp_qemu_io('drive0', 'resume A')
result = vm.hmp_qemu_io('drive0', 'resume B')

vm.shutdown()
print(re.findall(r'long [A-Z]*\[[0-9]*\]', vm.get_log(), re.MULTILINE))
