qemu-hook 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. #!/bin/sh -e
  2. #
  3. # Libvirt qemu hook to magically connect VM bridge interfaces to desired untagged Vlan
  4. #
  5. # IF
  6. # * the VM interface if configured to be connected to a bridge,
  7. # * the bridge is configured to be vlan aware (vlan_filtering = 1)
  8. # * the VM interface name ends with _vXXXX with XXXX being a one to four
  9. # digit number
  10. # the interface will be configured as an untagged port connected to vlan XXXX.
  11. #
  12. # See <man bridge> for more details about vlan aware bridges.
  13. #
  14. # Maximilian Wilhelm <max@sdn.clinic>
  15. # -- Wed, 31 Aug 2016 20:48:02 +0200
  16. my_name="qemu-magic"
  17. # We only care for the "started" event.
  18. if [ "$2" != 'started' ]; then
  19. exit 0
  20. fi
  21. if ! which xmlstarlet >/dev/null 2>/dev/null; then
  22. logger -t "${my_name}" "ERROR: xmlstarlet not found. Dying of shame."
  23. echo "${my_name}: ERROR: xmlstarlet not found. Dying of shame." >&2
  24. exit 1
  25. fi
  26. xmlstarlet sel -t -m '//interface[@type="bridge"]' -v 'concat(target/@dev, " ", source/@bridge)' --nl | while read iface bridge; do
  27. if [ ! -d "/sys/class/net/${bridge}/bridge" ]; then
  28. logger -t "${my_name}" "Bridge \"${bridge}\" for iface \"${iface}\" doesn't exist or isn't a bridge."
  29. exit 2
  30. fi
  31. # If this kernel does not support vlan-aware bridges there's nothing to be done here.
  32. if [ ! -f "/sys/class/net/${bridge}/bridge/vlan_filtering" ]; then
  33. continue
  34. fi
  35. # If this bridge isn't configured to be vlan-aware, there's nothing to be done here either.
  36. vlan_filtering=$(cat "/sys/class/net/${bridge}/bridge/vlan_filtering")
  37. if [ "${vlan_filtering}" = 0 ]; then
  38. continue
  39. fi
  40. # If the interface is named *_vXXXX, with X being a 1-4 digit number
  41. # we assume that this is iface should be connected to Vlan XXXX with
  42. # an untagged port.
  43. vlan_id=$(echo ${iface} | grep -o '_v[0-9]\{1,4\}$' | cut -c3-)
  44. if [ "${vlan_id}" ]; then
  45. # Remove association with vlan 1 and add association with
  46. # vlan $vlan_id with packages being sent out untagged and
  47. # untagged ingress packets get tagged accordingly.
  48. bridge vlan del vid 1 dev "${iface}"
  49. bridge vlan add vid "${vlan_id}" dev "${iface}" pvid untagged
  50. logger -t "${my_name}" "Configured untagged pvid ${vlan_id} for ${iface} in bridge ${bridge}."
  51. # If the interface doesn't suggest an untagged Vlan association go
  52. # for an /etc/network/interface entry which we try to get up and
  53. # running with ifup. Proceed with fingers crossed.
  54. else
  55. if ifup $iface; then
  56. logger -t qemu-magic "ifup'ed ${iface}."
  57. else
  58. logger -t qemu-magic "ifup ${iface} FAILED."
  59. fi
  60. fi
  61. done