Fedora + libvirt 下在宿主关机时安全关闭虚拟机

发布日期:分类:Linux & homelab Fedora + libvirt 下在宿主关机时安全关闭虚拟机无评论

很简单的一个问题,但过程比较难绷,所以特此记录

为了能方便的既跑虚拟机,又跑Docker容器,我经常使用Fedora Server来作为宿主系统,配合红帽官方的Cockpit面板进行管理,其对虚拟机(基于libvirt/qemu/kvm)和容器(官方只支持Podman)的支持尚可。

但其在关机时虚拟机会直接被强制停止,并不安全。我们希望在直接对宿主机进行关机或重启时,其能够像PVE、EXSi等虚拟化系统一样发起并等待虚拟机的安全关机。

首先这个功能libvirt是提供了的,由libvirt-guests.service实现,但不知为何在Fedora并没有被默认启用。

进一步的,我们发现其配置文件/etc/sysconfig/libvirt-guests从某个版本起被移除了(你还能搜到关于这件事的相关讨论,暴躁用户 vs 倔强maintainer),更不方便我们配置了,因此首先恢复其内容:

# URIs to check for running guests
# example: URIS='default xen:/// vbox+tcp://host/system lxc:///'
#URIS=default

# action taken on host boot
# - start   all guests which were running on shutdown are started on boot
#           regardless on their autostart settings                                 
# - ignore  libvirt-guests init script won't start any guest on boot, however,     
#           guests marked as autostart will still be automatically started by      
#           libvirtd                                                               
#ON_BOOT=start                                                                     

# Number of seconds to wait between each guest start. Set to 0 to allow            
# parallel startup.
#START_DELAY=0

# action taken on host shutdown
# - suspend   all running guests are suspended using virsh managedsave
# - shutdown  all running guests are asked to shutdown. Please be careful with
#             this settings since there is no way to distinguish between a
#             guest which is stuck or ignores shutdown requests and a guest
#             which just needs a long time to shutdown. When setting
#             ON_SHUTDOWN=shutdown, you must also set SHUTDOWN_TIMEOUT to a
#             value suitable for your guests.
ON_SHUTDOWN=shutdown

# If set to non-zero, shutdown will suspend guests concurrently. Number of
# guests on shutdown at any time will not exceed number set in this variable.
#PARALLEL_SHUTDOWN=0

# Number of seconds we're willing to wait for a guest to shut down. If parallel
# shutdown is enabled, this timeout applies as a timeout for shutting down all
# guests on a single URI defined in the variable URIS. If this is 0, then there
# is no time out (use with caution, as guests might not respond to a shutdown
# request). The default value is 300 seconds (5 minutes).
#SHUTDOWN_TIMEOUT=300

# If non-zero, try to bypass the file system cache when saving and
# restoring guests, even though this may give slower operation for
# some file systems.
#BYPASS_CACHE=0

注意我这里设置的是ON_SHUTDOWN=shutdown,因为对于有PCIe设备直通的虚拟机suspend可能无法使用。

然后启用libvirt-guests.service服务:

sudo systemctl enable --now libvirt-guests

然后在虚拟机关机时(或libvirt-guests服务关闭时)正在运行的虚拟机应当能正常关机,并且这些虚拟机会在宿主机下次启动时自动启动(恢复状态)。

这里不得不吐槽一下红帽经常搞一些breaking change,之前升级就被Network UPS Tools (NUT)的服务配置坑过一次

作者:WuSiYu

学生,计算机/HPC/MLsys/LLM infra方向

发表评论

您的邮箱地址不会被公开。 必填项已用 * 标注