Skip to content

Instantly share code, notes, and snippets.

@praul
Created August 25, 2022 06:46
Show Gist options
  • Save praul/0c86db44ecdce7da0fa39f8683116fb4 to your computer and use it in GitHub Desktop.
Save praul/0c86db44ecdce7da0fa39f8683116fb4 to your computer and use it in GitHub Desktop.
vmswitch for virsh- shutdown one vm, start another. on shutdown, start the first one again
#!/bin/bash
# chmod +x and run this script directly, NOT with "bash vmswitcher"
# ./vmswitcher -d to run in background
#Enter your vm-ids here
IDLEVM="powersave-server"
ACTIVEVM="bin10"
LOGFILE="/var/log/vmswitcher.$IDLEVM-$ACTIVEVM.log"
LOCKFILE="/tmp/vmswitcher.$IDLEVM-$ACTIVEVM.lock"
#Prevent multiple executions
if test -f "$LOCKFILE"; then
echo "Lockfile found. If you're sure, no other version of this script is running, remove it with:"
echo "rm $LOCKFILE"
echo "Exiting"
exit 1
fi
touch $LOCKFILE
#Daemonize
case "$1" in
-d|--daemon)
echo "Shutting down $IDLEVM"
echo "Starting $IDLEVM"
echo "Detaching"
echo "cat $LOGFILE to view output"
touch $LOGFILE
rm $LOCKFILE
$0 < $LOGFILE &> $LOGFILE & disown
exit 0
;;
*)
;;
esac
echo "$(date) Shutting down $IDLEVM"
virsh shutdown $IDLEVM 2>/dev/null
echo "$(date) Waiting for shutdown of $IDLEVM"
until virsh domstate $IDLEVM | grep -q 'shut off'
do
virsh shutdown $IDLEVM 2>/dev/null
sleep 5
done
echo "$(date) ...Shutdown. Starting $ACTIVEVM"
virsh start $ACTIVEVM
echo "$(date) ...Started. Wait 1min to $ACTIVEVM to boot"
sleep 60
echo "$(date) ...$ACTIVEVM running. Polling for shutdown."
until virsh domstate $ACTIVEVM | grep -q 'shut off'
do
sleep 10
done
echo "$(date) ...$ACTIVEVM is shut down. Starting $IDLEVM"
virsh start $IDLEVM
echo "$(date) ...Polling for startup of $IDLEVM"
until virsh domstate $IDLEVM | grep -q 'running'
do
sleep 1
done
echo "$(date) ...$IDLEVM running. Exit."
rm $LOCKFILE
exit 0
@praul
Copy link
Author

praul commented Aug 25, 2022

I use this to start my win10-vm and get the "powersave" vm running again, as soon as win10 is shutdown.
Background: Vfio GPU Passthrough with pci id kernel bind to vfio. If no vm is running, power consumption is higher.
The powersave-vm is a simple ubuntu server with nvidia drivers.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment