-
Notifications
You must be signed in to change notification settings - Fork 45
/
usb-libvirt-hotplug.sh
executable file
·108 lines (94 loc) · 2.51 KB
/
usb-libvirt-hotplug.sh
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
#!/bin/bash
#
# usb-libvirt-hotplug.sh
#
# This script can be used to hotplug USB devices to libvirt virtual
# machines from udev rules.
#
# This can be used to attach devices when they are plugged into a
# specific port on the host machine.
#
# See: https://github.com/olavmrk/usb-libvirt-hotplug
#
# Abort script execution on errors
set -e
PROG="$(basename "$0")"
if [ ! -t 1 ]; then
# stdout is not a tty. Send all output to syslog.
coproc logger --tag "${PROG}"
exec >&${COPROC[1]} 2>&1
fi
DOMAIN="$1"
if [ -z "${DOMAIN}" ]; then
echo "Missing libvirt domain parameter for ${PROG}." >&2
exit 1
fi
#
# Do some sanity checking of the udev environment variables.
#
if [ -z "${SUBSYSTEM}" ]; then
echo "Missing udev SUBSYSTEM environment variable." >&2
exit 1
fi
if [ "${SUBSYSTEM}" != "usb" ]; then
echo "Invalid udev SUBSYSTEM: ${SUBSYSTEM}" >&2
echo "You should probably add a SUBSYSTEM=\"USB\" match to your udev rule." >&2
exit 1
fi
if [ -z "${DEVTYPE}" ]; then
echo "Missing udev DEVTYPE environment variable." >&2
exit 1
fi
if [ "${DEVTYPE}" == "usb_interface" ]; then
# This is normal -- sometimes the udev rule will match
# usb_interface events as well.
exit 0
fi
if [ "${DEVTYPE}" != "usb_device" ]; then
echo "Invalid udev DEVTYPE: ${DEVTYPE}" >&2
exit 1
fi
if [ -z "${ACTION}" ]; then
echo "Missing udev ACTION environment variable." >&2
exit 1
fi
if [ "${ACTION}" == 'add' ]; then
COMMAND='attach-device'
elif [ "${ACTION}" == 'remove' ]; then
COMMAND='detach-device'
else
echo "Invalid udev ACTION: ${ACTION}" >&2
exit 1
fi
if [ -z "${BUSNUM}" ]; then
echo "Missing udev BUSNUM environment variable." >&2
exit 1
fi
if [ -z "${DEVNUM}" ]; then
echo "Missing udev DEVNUM environment variable." >&2
exit 1
fi
#
# This is a bit ugly. udev passes us the USB bus number and
# device number with leading zeroes. E.g.:
# BUSNUM=001 DEVNUM=022
# This causes libvirt to assume that the numbers are octal.
# To work around this, we need to strip the leading zeroes.
# The easiest way is to ask bash to convert the numbers from
# base 10:
#
BUSNUM=$((10#$BUSNUM))
DEVNUM=$((10#$DEVNUM))
#
# Now we have all the information we need to update the VM.
# Run the appropriate virsh-command, and ask it to read the
# update XML from stdin.
#
echo "Running virsh ${COMMAND} ${DOMAIN} for USB bus=${BUSNUM} device=${DEVNUM}:" >&2
virsh "${COMMAND}" "${DOMAIN}" /dev/stdin <<END
<hostdev mode='subsystem' type='usb'>
<source>
<address bus='${BUSNUM}' device='${DEVNUM}' />
</source>
</hostdev>
END