ViReR.NeT  

  Home  -  Infos/Docs  -  Tools/Outils Code  -  Links/Liens  -  News  -  Download  -  Others/Autres Site map

 

Export usb device automaticaly under Centos 6.2 - 6.3 with Libvirt/Qemu-KVM

 




If gnome ins runing/installed on the hypervysor you must 
Disable nautilus(gnome) automount :

/home/library/.gconf/apps/nautilus/preferences/%gconf.xml  :
<?xml version="1.0"?>
<gconf>
        <entry name="media_automount" mtime="1342014314" type="bool" value="false"/>
        <entry name="media_automount_open" mtime="1342014313" type="bool" value="false"/>
</gconf>




Add on the guest host xml USB 2.0 part (/etc/libvirt/qemu/<guest hostname>.xml) :
or with virt manager > controller usb > model = USB 2.0 :
...
    <controller type='usb' index='0' model='ich9-ehci1'>
      <address type='pci' domain='0x0000' bus='0x00' slot='0x05' function='0x7'/>
    </controller>
    <controller type='usb' index='0' model='ich9-uhci1'>
      <master startport='0'/>
      <address type='pci' domain='0x0000' bus='0x00' slot='0x05' function='0x0' multifunction='on'/>
    </controller>
    <controller type='usb' index='0' model='ich9-uhci2'>
      <master startport='2'/>
      <address type='pci' domain='0x0000' bus='0x00' slot='0x05' function='0x1'/>
    </controller>
    <controller type='usb' index='0' model='ich9-uhci3'>
      <master startport='4'/>
      <address type='pci' domain='0x0000' bus='0x00' slot='0x05' function='0x2'/>
    </controller>
...


On the hypervysor modify UDEV rules and create the folling file /etc/udev/rules.d/usb-export.rules with :
KERNEL=="sd[b-z][0-9]",SUBSYSTEM=="block",ACTION=="add",RUN+="/opt/usb-export.sh %k %n"
KERNEL=="sd[b-z]",ACTION=="remove",RUN+="/opt/usb-remove.sh %k %n"




Then create the export script /opt/usb-export.sh :
#!/bin/sh
############################################
# Guardis 2012
############################################

DOMAINID="<guest hostname/id>"
VENDOR=`/sbin/udevadm info --query=all --name=$1 | grep ID_VENDOR_ID | cut -d '=' -f 2`
PRODUCT=`/sbin/udevadm info --query=all --name=$1 | grep ID_MODEL_ID | cut -d '=' -f 2`

echo "<hostdev mode='subsystem' type='usb'>
<source>
<vendor id='0x%%vendor%%'/>
<product id='0x%%product%%'/>
</source>
</hostdev>" > /tmp/usb.xml

sed -i "s/%%vendor%%/${VENDOR}/g;s/%%product%%/${PRODUCT}/g" /tmp/usb.xml

virsh attach-device $DOMAINID /tmp/usb.xml

# Wait for initialization for fixing the add/remove directly bug
nohup $( sleep 10 ; mv /tmp/usb.xml /tmp/usb-$1.xml ) &

exit 0
# EOF

And create the remove script /opt/usb-remove.sh
#!/bin/sh
############################################
# Guardis 2012
############################################
DOMAINID="<guest hostname/id>"
if [ -e /tmp/usb-$1[0-9].xml ]; then
    virsh detach-device $DOMAINID /tmp/usb-$1[0-9].xml
    rm -f /tmp/usb-$1[0-9].xml
fi
# EOF


Make all script executable :
chmod a+x /opt/usb-export.sh /opt/usb-remove.sh