So I had an interesting problem today: I want to have a script that will decide what to do based
on whether a file has something or not. Specifically, I am running libvirt with KVM/QEMU and wanted to know if a given vm client was configured with PC passthrough. Now, there are a ton of ways to do that, but I wanted to do it using Bourne or bash and grep. You know, something like
root@vmhost:~# virsh dumpxml vmclient | grep "type='pci' managed='yes'"root@vmhost:~#
since if it has that pattern, it is passing PCI through. What I need then is to have grep look for that pattern and give me back some kind of return code that tells me if it is there or not.
At first I thought grep -q (quiet), as in
virsh dumpxml vmclient | grep -q "type='pci' managed='yes'" | echo $?
would work (you would need then to fish the return code using $?, which is why I put the echo $?). After all we only care whether it finds it or not. But the thing is that it would return 0 no matter it found the pattern or not. Major bummer.
Now, grep has this -c option that would count how many times it finds the pattern. Which probably leads to if it does not find it, the count should be 0, right? Let's test it out:
root@vmhost1:~# virsh dumpxml vmclient|grep -c "type='pci' managed='no'" 0 root@vmhost1:~# virsh dumpxml vmclient |grep -c "type='pci' managed='yes'" 1 root@vmhost1:~#
I think you can see where I am going with this. So, here is a scaled-down version of what I ended up writing:
#!/bin/sh vmclient=$1 have_pci=$(virsh dumpxml ${vmclient} | grep -c "type='pci' managed='yes'" ) if [ "$have_pci" -eq 0 ] then echo "${vmclient} is PCI passthrough-free. Rejoy!" # Do something interesting else echo "${vmclient} has PCI passthrough. Be nice to it." # Do something interesting fi
As you can see it puts our little research to work by detecting if the vm whose name you provide as command line argument ($1) is configured to do PCI passthrough or not. Since this is just a sample skeleton code, it just tells us whether it does or not (the if statement); we could then use that info to do something else. In fact, I am using that test in a larger script I wrote; I did not want to include it here because I wanted to focus on one thing.
I hope this might be useful to someone out there. I probably should talk about the pci passthrough madness, but let's leave that for another episode, shall we?
No comments:
Post a Comment