Hi,
I came up with the following solution.
It requires QEMU Guest Agent to be configured and running within the machine.
libvirt has the possibility to run hooks scripts for particular hypervisor and machine state.
You can read more about it in
Hooks for specific system management.
This possibility immediately drew my attention.
I wrote the following hook for QEMU hypervisor:
Code:
$ cat /etc/libvirt/hooks/qemu
#!/bin/bash
PATH=/usr/sbin:/sbin:/usr/bin:/bin
################################################################################
function guest_update_time() {
################################################################################
for ((cnt = 0; cnt < 10; ++cnt)); do
virsh qemu-agent-command "${1}" '{"execute" : "guest-ping"}' && break
sleep 0.3
done
timeout --kill-after=1 1 virsh domtime "${1}" --now || true
}
# Executes after the QEMU process has successfully started up.
# <https://www.libvirt.org/hooks.html#qemu>
if [[ (${1} != "-") && (${2} = "started") && (${3} = "begin") && (${4} = "-") ]]; then
guest_update_time "${1}" </dev/null >/dev/null 2>/dev/null &
fi
It works in the following way:
It tests to see if the machine state is "started"
(${2} = "started").
If so, then it executes
guest_update_time() function in the background.
(It is important to execute the function in the background, otherwise the script blocks and the machine startup does not proceed).
For a maximum of 3 seconds,
guest_update_time() tries to check if Guest Agent is running.
As soon as it determines the Guest Agent is running, the machine time is updated with
virsh domtime
Things to keep in mind:
1. The hook is executed on behalf of the user executing the QEMU process.
I'm not 100% sure about that, but this is what I observed when running virtual
machine in qemu:///session connection.
2. The hook is run for
all started machines, and for all users.
Better solution would be to start it only for the restored machines, but I didn't want to mess with preserving the state of the machine.
If needed, it could be implemented.
--
Best regards,
Andrzej Telszewski