#!/bin/bash
set -x

# Purpose: Attach several disks and detach them ... to see if we can
# trigger a bug in QEMU: https://bugs.launchpad.net/qemu/+bug/1894804
# (Second DEVICE_DELETED event missing during virtio-blk disk device
# detach)

# Create some CPU load; this consistently utiizes 40% of vCPU time -- as
# observed via `sar -u 5` and %user utilization -- which is "Percentage
# of CPU utilization that occurred while executing at the user level
# (application). Note that this field includes time spent running
# virtual processors."
function gen_cpu_load() {
    stress --cpu 3
}


# Create 20 raw disk images
function create_disk() {
    for i in `seq 1 20`; do 
        qemu-img create -f raw $i.raw 10M; 
    done
}

# Construct a guest XML by attaching 50 disks to a single Virtio SCSI
# controller by manually incrementing the 'unit' number
function attach_dev() {
    for i in {b..u}; do
        j=$(expr $j + 1)
        cat << EOF > disk-$i.xml
<disk type='file' device='disk'>
  <driver name='qemu' type='raw' cache='none'/>
  <source file='/var/lib/libvirt/images/$j.raw'/>
  <target dev='vd$i' />
</disk>
EOF

        # Attach the device to take effect on the live guest
        sudo virsh attach-device test_f32_vm1 disk-$i.xml  --live

    done
}


function detach_dev() {
    for i in {b..u}; do
        sudo virsh detach-device cvm1 disk-$i.xml --live
    done
}

# Invoke the calls
gen_cpu_load
create_disk
attach_dev
virsh domblklist cvm1
detach_dev

