1
0
Fork 0
mirror of https://github.com/retspen/webvirtcloud synced 2026-12-02 08:56:07 +00:00

feat(instances): a guest that crashes or hangs is restarted or stopped

The VM Settings "When the guest crashes" choice (on_crash, restart for new
VMs) never acted: a guest reports a crash through a panic device, and the
panel gave VMs none. A guest whose kernel panicked stayed "running" until
someone noticed.

- new VMs get the panic device the host offers (get_panic_model: x86 ISA
  pvpanic, which Linux has built in and Windows gets with virtio-win; the
  PCI one elsewhere; ISA on x86 when libvirt does not tell), and an x86
  machine without a watchdog of its own (not q35, which has the iTCO; not
  microvm, which has no PCI bus) an i6300esb
- choosing Restart or Stop adds the panic device to a VM without one, an
  i6300esb when it has no watchdog (libvirt before 9.1 shows no iTCO on
  q35), and gives its watchdogs the matching action (reset, poweroff): a
  guest that arms its watchdog and hangs is met as one that crashed. A VM
  without these devices shows no choice made and says it cannot report a
  crash or a hang yet. From the next start, as before

Checked live on a Vagrant host with a guest whose init exits (kernel panic):
without the device it stayed "running (booted)"; after Stop it ended
"shut off (crashed)", after Restart it booted again.
This commit is contained in:
catborise 2026-11-22 21:45:50 +03:00
parent bdc5569cc8
commit ede9e0bca7
14 changed files with 179 additions and 25 deletions

View file

@ -1074,6 +1074,7 @@ class CreateInstance(Kind):
add_cdrom=data["add_cdrom"],
add_input=data["add_input"],
tpm_model=conn.get_tpm_model(data["arch"], data["machine"]) if data["tpm"] else None,
panic_model=conn.get_panic_model(data["arch"], data["machine"]),
)
except Exception as err:
# a definition whose answer was lost may have gone through: then, or

View file

@ -375,6 +375,10 @@ class Instance(models.Model):
def config_on_crash(self) -> str:
return self.proxy.get_on_crash()
@cached_property
def config_crash_devices(self) -> bool:
return self.proxy.has_crash_devices()
@cached_property
def guest_agent_ready(self) -> bool:
return self.proxy.is_agent_ready()

View file

@ -1013,16 +1013,20 @@
</form>
</div>
<form class="list-group-item p-3 p-md-4" action="{% url 'instances:set_on_crash' instance.id %}" method="post" aria-labelledby="options-crash">{% csrf_token %}
<h2 class="h6 mb-2" id="options-crash">{% trans "When the guest crashes" %}</h2>
<h2 class="h6 mb-2" id="options-crash">{% trans "When the guest crashes or hangs" %}</h2>
<div class="d-flex flex-wrap align-items-center column-gap-3 row-gap-2">
{% if instance.config_on_crash == "restart" or instance.config_on_crash == "destroy" %}
<div class="btn-group btn-group-sm" role="radiogroup" aria-labelledby="options-crash">
<input type="radio" class="btn-check" name="on_crash" value="restart" id="on_crash_restart"{% if instance.config_on_crash == "restart" %} checked{% endif %} data-submit-on-change>
<input type="radio" class="btn-check" name="on_crash" value="restart" id="on_crash_restart"{% if instance.config_crash_devices and instance.config_on_crash == "restart" %} checked{% endif %} data-submit-on-change>
<label class="btn btn-outline-primary" for="on_crash_restart">{% trans "Restart" %}</label>
<input type="radio" class="btn-check" name="on_crash" value="destroy" id="on_crash_destroy"{% if instance.config_on_crash == "destroy" %} checked{% endif %} data-submit-on-change>
<input type="radio" class="btn-check" name="on_crash" value="destroy" id="on_crash_destroy"{% if instance.config_crash_devices and instance.config_on_crash == "destroy" %} checked{% endif %} data-submit-on-change>
<label class="btn btn-outline-primary" for="on_crash_destroy">{% trans "Stop" %}</label>
</div>
<span class="small text-body-secondary">{% trans "For a crash the guest reports, not a hang. Stop keeps a VM that crashes again and again down for a look. From the next start." %}</span>
{% if instance.config_crash_devices %}
<span class="small text-body-secondary">{% trans "A hang is noticed once the guest arms its watchdog (Linux: RuntimeWatchdogSec in systemd's system.conf). Stop keeps a VM that crashes again and again down for a look. From the next start." %}</span>
{% else %}
<span class="small d-inline-flex align-items-center gap-2"><span class="power-dot bg-warning" aria-hidden="true"></span>{% trans "This VM cannot report a crash or a hang yet: a choice adds the devices it reports them through, from the next start." %}</span>
{% endif %}
{% else %}
<p class="small mb-0" id="on_crash">{% blocktrans with action=instance.config_on_crash %}{{ action }}: change it in the XML editor.{% endblocktrans %}</p>
{% endif %}

View file

@ -247,6 +247,13 @@ class PendingEditsTestCase(TestCase):
self.assertEqual(doc.xpath("//input[@name='rng']/@checked"), ["checked"])
self.assertEqual(doc.xpath("//input[@name='on_crash'][@checked]/@value"), ["restart"])
def test_a_vm_without_a_panic_device_has_no_crash_action_chosen_yet(self):
# on_crash acts on a crash the guest reports: without the device, a choice adds it
with patch("instances.models.Instance.config_crash_devices", new_callable=PropertyMock, return_value=False):
doc = self.page(get_on_crash=("restart", "restart"))
self.assertEqual(doc.xpath("//input[@name='on_crash'][@checked]"), [])
self.assertIn("This VM cannot report a crash or a hang yet", doc.xpath("string(//form[.//input[@name='on_crash']])"))
def test_the_tpm_switch_is_off_where_it_cannot_change(self):
tpm = "//input[@name='tpm']"
doc = self.page(get_tpm=("emulator", "emulator"))

Binary file not shown.

View file

@ -6714,8 +6714,8 @@ msgid "Not connected: is the agent installed and running in the guest?"
msgstr "Bağlı değil: ajan konuk sistemde kurulu ve çalışıyor mu?"
#: instances/templates/instances/settings_tab.html:1019
msgid "When the guest crashes"
msgstr "Konuk sistem çöktüğünde"
msgid "When the guest crashes or hangs"
msgstr "Konuk sistem çöktüğünde ya da donduğunda"
#: instances/templates/instances/settings_tab.html:1024
msgid "Restart"
@ -6728,13 +6728,8 @@ msgid "Stop"
msgstr "Durdur"
#: instances/templates/instances/settings_tab.html:1028
msgid ""
"For a crash the guest reports, not a hang. Stop keeps a VM that crashes again"
" and again down for a look. From the next start."
msgstr ""
"Konuk sistemin bildirdiği bir çökme içindir, donma için değil. Durdur, tekrar"
" tekrar çöken bir sanal makineyi incelemek için kapalı tutar. Sonraki "
"başlatmadan itibaren."
msgid "A hang is noticed once the guest arms its watchdog (Linux: RuntimeWatchdogSec in systemd's system.conf). Stop keeps a VM that crashes again and again down for a look. From the next start."
msgstr "Donma, konuk sistem watchdog'unu kurduğunda fark edilir (Linux: systemd'nin system.conf dosyasında RuntimeWatchdogSec). Durdur, tekrar tekrar çöken bir sanal makineyi incelemek için kapalı tutar. Sonraki başlatmadan itibaren."
#: instances/templates/instances/settings_tab.html:1030
#, python-format
@ -13094,3 +13089,7 @@ msgstr "Depolamasında yer açın, ardından sanal makineyi devam ettirin."
#: instances/templates/instance.html:55
msgid "An administrator has to free space on its storage and resume it."
msgstr "Bir yöneticinin depolamasında yer açıp sanal makineyi devam ettirmesi gerekir."
#: instances/templates/instances/settings_tab.html:1030
msgid "This VM cannot report a crash or a hang yet: a choice adds the devices it reports them through, from the next start."
msgstr "Bu sanal makine henüz çöktüğünü ya da donduğunu bildiremiyor: bir seçim, bildirdiği aygıtları sonraki başlatmadan itibaren ekler."

Binary file not shown.

View file

@ -6349,8 +6349,8 @@ msgid "Not connected: is the agent installed and running in the guest?"
msgstr "未连接:客户机中是否已安装并运行代理?"
#: instances/templates/instances/settings_tab.html:1019
msgid "When the guest crashes"
msgstr "客户机崩溃时"
msgid "When the guest crashes or hangs"
msgstr "客户机崩溃或挂起时"
#: instances/templates/instances/settings_tab.html:1024
msgid "Restart"
@ -6363,10 +6363,8 @@ msgid "Stop"
msgstr "停止"
#: instances/templates/instances/settings_tab.html:1028
msgid ""
"For a crash the guest reports, not a hang. Stop keeps a VM that crashes again"
" and again down for a look. From the next start."
msgstr "适用于客户机报告的崩溃,而非挂起。“停止”会让反复崩溃的虚拟机保持停止状态以便排查。下次启动时生效。"
msgid "A hang is noticed once the guest arms its watchdog (Linux: RuntimeWatchdogSec in systemd's system.conf). Stop keeps a VM that crashes again and again down for a look. From the next start."
msgstr "客户机启用其看门狗后才能发现挂起(Linux:systemd 的 system.conf 中的 RuntimeWatchdogSec)。“停止”会让反复崩溃的虚拟机保持停止状态以便排查。下次启动时生效。"
#: instances/templates/instances/settings_tab.html:1030
#, python-format
@ -12369,3 +12367,7 @@ msgstr "请在其存储上释放空间,然后恢复它。"
#: instances/templates/instance.html:55
msgid "An administrator has to free space on its storage and resume it."
msgstr "需要管理员在其存储上释放空间并恢复它。"
#: instances/templates/instances/settings_tab.html:1030
msgid "This VM cannot report a crash or a hang yet: a choice adds the devices it reports them through, from the next start."
msgstr "此虚拟机尚无法报告崩溃或挂起:做出选择即会添加其报告所用的设备,下次启动时生效。"

View file

@ -1386,6 +1386,21 @@ class wvmConnect(object):
return util.get_xml_path(self.get_dom_cap_xml(arch, machine), func=tpm_model)
def get_panic_model(self, arch, machine):
"""The panic device a guest reports its crash through (pvpanic: Linux
has it built in, Windows with the virtio-win driver), for on_crash to
act on; None when the machine has none."""
def panic_model(ctx):
if not ctx.xpath("/domainCapabilities/devices/panic"):
# libvirt that does not tell (before 10.x): x86 has the ISA one
return "isa" if arch in ("x86_64", "i686") else None
models = ctx.xpath("/domainCapabilities/devices/panic[@supported='yes']/enum[@name='model']/value/text()")
# x86 ISA pvpanic, the PCI one elsewhere (aarch64), or the machine's own; hyperv needs Hyper-V enlightenments
return next((model for model in ("isa", "pvpanic", "pseries", "s390") if model in models), None)
return util.get_xml_path(self.get_dom_cap_xml(arch, machine), func=panic_model)
def is_supports_virtio(self, arch, machine):
if not self.is_qemu():
return False

View file

@ -4,6 +4,7 @@ import string
import pycdlib
from vrtManager import util
from vrtManager.util import WATCHDOG_ACTIONS, needs_watchdog
from vrtManager.connection import wvmConnect
from vrtManager.storage import rbd_source_children, wvmStorage
@ -103,10 +104,12 @@ class wvmCreate(wvmConnect):
add_cdrom="sata",
add_input="default",
tpm_model=None,
panic_model=None,
):
"""
Create VM function. firmware: BIOS, UEFI or UEFI Secure Boot, of
get_firmwares; tpm_model: an emulated TPM 2.0 of get_tpm_model, or none.
get_firmwares; tpm_model: an emulated TPM 2.0 of get_tpm_model, or none;
panic_model: the guest's panic device (get_panic_model), or none.
"""
caps = self.get_capabilities(arch)
dom_caps = self.get_dom_capabilities(arch, machine)
@ -269,6 +272,11 @@ class wvmCreate(wvmConnect):
</video>"""
if tpm_model:
xml += f"""<tpm model='{tpm_model}'><backend type='emulator' version='2.0'/></tpm>"""
# on_crash restart acts on a crash the guest reports and the watchdog on a hang, once the guest arms it
if panic_model:
xml += f"""<panic model='{panic_model}'/>"""
if needs_watchdog(arch, machine):
xml += f"""<watchdog model='i6300esb' action='{WATCHDOG_ACTIONS["restart"]}'/>"""
# q35 plugs each PCIe device (a virtio disk, a NIC) into a root port of
# its own and libvirt makes only as many as the VM is defined with: as
# virt-install, 14 ports, so a running VM can take more devices

View file

@ -3383,15 +3383,37 @@ class wvmInstance(wvmConnect):
"""What the next start does when the guest crashes; libvirt's default is destroy."""
return etree.fromstring(self._XMLDesc(PERSISTENT_XML)).findtext("on_crash") or "destroy"
def has_crash_devices(self):
"""The next start has the device the guest reports a crash through
(without it on_crash never acts) and a watchdog where its machine
takes one: what set_on_crash adds."""
tree = etree.fromstring(self._XMLDesc(PERSISTENT_XML))
arch, machine = tree.find("os/type").get("arch"), tree.find("os/type").get("machine")
return tree.find("devices/panic") is not None and (
tree.find("devices/watchdog") is not None or not util.takes_watchdog(arch, machine))
def set_on_crash(self, action):
"""restart or destroy (stop) the VM when the guest crashes, from the next start."""
if action not in ("restart", "destroy"):
"""restart or destroy (stop) the VM when the guest crashes or, once it
arms its watchdog, hangs; from the next start. The VM gets the panic
device a crash is reported through, and an i6300esb when it has no
watchdog and its machine takes one (libvirt before 9.1 does not show
q35's iTCO), when it lacks them."""
if action not in util.WATCHDOG_ACTIONS:
raise util.OperationError(gettext_noop("Unknown crash action %(action)s"), action=action)
tree = etree.fromstring(self._XMLDesc(PERSISTENT_XML))
on_crash = tree.find("on_crash")
if on_crash is None:
on_crash = etree.SubElement(tree, "on_crash")
on_crash.text = action
arch, machine = tree.find("os/type").get("arch"), tree.find("os/type").get("machine")
devices = tree.find("devices")
if devices.find("panic") is None and (model := self.get_panic_model(arch, machine)):
etree.SubElement(devices, "panic", model=model)
watchdogs = devices.findall("watchdog")
if not watchdogs and util.takes_watchdog(arch, machine):
watchdogs = [etree.SubElement(devices, "watchdog", model="i6300esb")]
for watchdog in watchdogs:
watchdog.set("action", util.WATCHDOG_ACTIONS[action])
self._defineXML(etree.tostring(tree).decode())
def set_options(self, options):

View file

@ -202,3 +202,41 @@ class NewVmTextTests(SimpleTestCase):
self.assertEqual(devices.find("disk/source").get("file"), f"/srv/{odd}/vm.qcow2")
self.assertEqual(devices.find("interface/source").get("network"), odd)
self.assertEqual(devices.find("interface/filterref").get("filter"), odd)
def defined_crash_devices(machine, panic_model):
conn = wvmCreate.__new__(wvmCreate)
conn.wvm = MagicMock()
with patch.object(wvmCreate, "get_capabilities", return_value={"features": []}), \
patch.object(wvmCreate, "get_dom_capabilities", return_value=PORTS_DOM_CAPS):
conn.create_instance(name="vm-1", memory=512, vcpu=1, vcpu_mode="host-model",
uuid="00000000-0000-4000-8000-0000000000c3", arch="x86_64", machine=machine,
firmware="BIOS", volumes=[], networks="", nwfilter="", virtio=True,
listener_addr="0.0.0.0", add_cdrom="None", add_input="None", panic_model=panic_model)
domain = etree.fromstring(conn.wvm.defineXML.call_args.args[0])
return domain.findtext("on_crash"), [(d.tag, dict(d.attrib)) for d in domain.xpath("devices/panic | devices/watchdog")]
class CrashDevicesTests(SimpleTestCase):
"""A new VM restarts when its guest crashes or hangs: the guest reports a
crash through a panic device, a hang through a watchdog it arms."""
def test_the_host_offers_its_panic_device(self):
caps = "<domainCapabilities><devices><panic supported='yes'><enum name='model'>{}</enum></panic></devices></domainCapabilities>"
for models, chosen in (("<value>hyperv</value><value>isa</value>", "isa"), ("<value>pvpanic</value>", "pvpanic"),
("<value>hyperv</value>", None)):
with self.subTest(models):
self.assertEqual(host(caps.format(models)).get_panic_model("x86_64", "q35"), chosen)
self.assertIsNone(host("<domainCapabilities><devices><panic supported='no'/></devices></domainCapabilities>")
.get_panic_model("x86_64", "q35"))
# libvirt that does not tell: x86 has the ISA one, another machine none known
self.assertEqual(host("<domainCapabilities><devices/></domainCapabilities>").get_panic_model("x86_64", "q35"), "isa")
self.assertIsNone(host("<domainCapabilities><devices/></domainCapabilities>").get_panic_model("aarch64", "virt"))
def test_a_new_vm_gets_a_panic_device_and_a_pc_one_a_watchdog(self):
# q35 has its iTCO watchdog, which libvirt adds with reset
self.assertEqual(defined_crash_devices("pc-q35-rhel10.2.0", "isa"), ("restart", [("panic", {"model": "isa"})]))
self.assertEqual(defined_crash_devices("pc-i440fx-rhel7.6.0", "isa"),
("restart", [("panic", {"model": "isa"}), ("watchdog", {"model": "i6300esb", "action": "reset"})]))
self.assertEqual(defined_crash_devices("pc-q35-rhel10.2.0", None), ("restart", []))
self.assertEqual(defined_crash_devices("microvm", "isa"), ("restart", [("panic", {"model": "isa"})]))

View file

@ -236,11 +236,51 @@ class DeviceEditsTestCase(unittest.TestCase):
def test_the_crash_action_is_restart_or_stop(self):
p = proxy()
self.assertEqual(p.get_on_crash(), "destroy") # libvirt's default
p.set_on_crash("restart")
self.assertEqual(defined(p).findtext("on_crash"), "restart")
with self.assertRaises(util.OperationError):
p.set_on_crash("preserve")
p._defineXML.assert_called_once()
p._defineXML.assert_not_called()
def test_a_crash_action_gives_the_vm_a_panic_device_and_its_watchdog_the_action(self):
def crash_proxy(machine, devices):
p = proxy()
xml = f"<domain><os><type arch='x86_64' machine='{machine}'>hvm</type></os><devices>{devices}</devices></domain>"
p._XMLDesc = lambda flags: xml
p.get_panic_model = MagicMock(return_value="isa")
return p
# a pc machine has no watchdog of its own: it gets an i6300esb
p = crash_proxy("pc-i440fx-9.2", "")
self.assertFalse(p.has_crash_devices())
p.set_on_crash("destroy")
tree = defined(p)
self.assertEqual(tree.findtext("on_crash"), "destroy")
self.assertEqual([(d.tag, dict(d.attrib)) for d in tree.find("devices")],
[("panic", {"model": "isa"}), ("watchdog", {"model": "i6300esb", "action": "poweroff"})])
p.get_panic_model.assert_called_once_with("x86_64", "pc-i440fx-9.2")
# q35's iTCO takes the action; a panic device there is kept, not doubled
p = crash_proxy("pc-q35-9.2", "<panic model='isa'/><watchdog model='itco' action='poweroff'/>")
self.assertTrue(p.has_crash_devices())
p.set_on_crash("restart")
tree = defined(p)
self.assertEqual([(d.tag, dict(d.attrib)) for d in tree.find("devices")],
[("panic", {"model": "isa"}), ("watchdog", {"model": "itco", "action": "reset"})])
p.get_panic_model.assert_not_called()
# libvirt before 9.1 shows no iTCO on q35: a VM with a panic device but no watchdog is not ready, and gets one
p = crash_proxy("pc-q35-9.0", "<panic model='isa'/>")
self.assertFalse(p.has_crash_devices())
p.set_on_crash("restart")
self.assertEqual([(d.tag, dict(d.attrib)) for d in defined(p).find("devices")],
[("panic", {"model": "isa"}), ("watchdog", {"model": "i6300esb", "action": "reset"})])
# microvm has no PCI bus: no watchdog; a host with no panic device for it: the action only
p = crash_proxy("microvm", "")
p.get_panic_model.return_value = None
p.set_on_crash("restart")
self.assertEqual((defined(p).findtext("on_crash"), list(defined(p).find("devices"))), ("restart", []))
p = crash_proxy("microvm", "<panic model='isa'/>")
self.assertTrue(p.has_crash_devices())
def test_cpu_title_and_description_are_read_from_either_definition(self):
p = proxy()

View file

@ -172,3 +172,17 @@ def is_loopback(address):
return ipaddress.ip_address(address).is_loopback
except ValueError:
return address == "localhost"
# the watchdog's action for each crash action (on_crash): a guest that hangs is met as one that crashed
WATCHDOG_ACTIONS = {"restart": "reset", "destroy": "poweroff"}
def takes_watchdog(arch, machine):
"""An x86 machine with a PCI bus takes an i6300esb (microvm has none)."""
return arch in ("x86_64", "i686") and not machine.startswith("microvm")
def needs_watchdog(arch, machine):
"""A new VM's machine has no watchdog of its own (q35 has the iTCO): it gets an i6300esb."""
return takes_watchdog(arch, machine) and "q35" not in machine