2023-04-02 21:38:34 +02:00
|
|
|
#!/usr/bin/env bash
|
|
|
|
set -eu
|
|
|
|
|
|
|
|
# Configure QEMU for graceful shutdown
|
|
|
|
|
|
|
|
QEMU_MONPORT=7100
|
|
|
|
QEMU_POWERDOWN_TIMEOUT=30
|
2023-04-10 21:05:34 +02:00
|
|
|
_QEMU_PID=/run/qemu.pid
|
|
|
|
_QEMU_SHUTDOWN_COUNTER=/run/qemu.counter
|
2023-04-02 21:38:34 +02:00
|
|
|
|
2023-04-10 21:05:34 +02:00
|
|
|
# Allows for troubleshooting signals sent to the process
|
|
|
|
_trap(){
|
|
|
|
func="$1" ; shift
|
|
|
|
for sig ; do
|
2023-04-10 21:13:28 +02:00
|
|
|
trap '$func $sig' "$sig"
|
2023-04-10 21:05:34 +02:00
|
|
|
done
|
|
|
|
}
|
|
|
|
|
|
|
|
_graceful_shutdown(){
|
2023-04-02 21:38:34 +02:00
|
|
|
|
|
|
|
local QEMU_MONPORT="${QEMU_MONPORT:-7100}"
|
|
|
|
local QEMU_POWERDOWN_TIMEOUT="${QEMU_POWERDOWN_TIMEOUT:-120}"
|
|
|
|
|
|
|
|
set +e
|
2023-04-10 21:05:34 +02:00
|
|
|
echo "Trapped $1 signal"
|
|
|
|
echo 0 > "${_QEMU_SHUTDOWN_COUNTER}"
|
|
|
|
|
|
|
|
FILE="${IMG}/agent.ver"
|
|
|
|
if [ ! -f "$FILE" ]; then
|
|
|
|
AGENT_VERSION="1"
|
|
|
|
echo "$AGENT_VERSION" > "$IMG"/agent.ver
|
|
|
|
else
|
|
|
|
AGENT_VERSION=$(cat "${FILE}")
|
|
|
|
fi
|
|
|
|
|
|
|
|
# Don't send the powerdown signal because Synology ignores it
|
|
|
|
# echo 'system_powerdown' | nc -q 1 -w 1 localhost "${QEMU_MONPORT}">/dev/null
|
2023-04-02 21:38:34 +02:00
|
|
|
|
2023-04-10 21:05:34 +02:00
|
|
|
if (($AGENT_VERSION < 2)); then
|
|
|
|
echo "Please update the agent to allow gracefull shutdowns..."
|
|
|
|
pkill -f qemu-system-x86_64
|
|
|
|
else
|
|
|
|
# Send a NMI interrupt which will be detected by the agent
|
|
|
|
echo 'nmi' | nc -q 1 -w 1 localhost "${QEMU_MONPORT}">/dev/null
|
|
|
|
fi
|
|
|
|
|
|
|
|
while [ "$(cat ${_QEMU_SHUTDOWN_COUNTER})" -lt "${QEMU_POWERDOWN_TIMEOUT}" ]; do
|
|
|
|
|
|
|
|
# Increase the counter
|
|
|
|
echo $(($(cat ${_QEMU_SHUTDOWN_COUNTER})+1)) > ${_QEMU_SHUTDOWN_COUNTER}
|
2023-04-02 21:38:34 +02:00
|
|
|
|
2023-04-10 21:05:34 +02:00
|
|
|
# Try to connect to qemu
|
|
|
|
if echo 'info version'| nc -q 1 -w 1 localhost "${QEMU_MONPORT:-7100}">/dev/null; then
|
2023-04-02 21:38:34 +02:00
|
|
|
|
2023-04-10 21:05:34 +02:00
|
|
|
sleep 1
|
|
|
|
#echo "Shutting down, waiting... ($(cat ${_QEMU_SHUTDOWN_COUNTER})/${QEMU_POWERDOWN_TIMEOUT})"
|
|
|
|
|
|
|
|
fi
|
2023-04-02 21:38:34 +02:00
|
|
|
done
|
|
|
|
|
2023-04-10 21:05:34 +02:00
|
|
|
echo 'quit' | nc -q 1 -w 1 localhost "${QEMU_MONPORT}">/dev/null || true
|
2023-04-02 21:38:34 +02:00
|
|
|
|
2023-04-10 21:05:34 +02:00
|
|
|
return
|
2023-04-02 21:38:34 +02:00
|
|
|
}
|
|
|
|
|
2023-04-10 21:05:34 +02:00
|
|
|
_trap _graceful_shutdown SIGTERM SIGHUP SIGINT SIGABRT SIGQUIT
|
2023-04-02 21:38:34 +02:00
|
|
|
|
2023-04-02 22:53:06 +02:00
|
|
|
KVM_MON_OPTS="-monitor telnet:localhost:${QEMU_MONPORT:-7100},server,nowait,nodelay"
|