File virt-use-dev-kvm-to-detect-kvm-383.patch of Package salt.20998

From 73f474fcc7700abff110e3eac653fea5e320ee4f Mon Sep 17 00:00:00 2001
From: Cedric Bosdonnat <cedric.bosdonnat@free.fr>
Date: Thu, 24 Jun 2021 11:37:41 +0200
Subject: [PATCH] virt: use /dev/kvm to detect KVM (#383)

checking for kvm_* modules to be loaded is not robust enough since the
kernel could be compiled with builtin modules. /dev/kvm is much more
reliable.
---
 changelog/60419.fixed                        |  1 +
 salt/modules/virt.py                         |  7 +------
 tests/pytests/unit/modules/virt/test_host.py | 19 +++++++++++++++++++
 3 files changed, 21 insertions(+), 6 deletions(-)
 create mode 100644 changelog/60419.fixed

diff --git a/changelog/60419.fixed b/changelog/60419.fixed
new file mode 100644
index 0000000000..44c782da48
--- /dev/null
+++ b/changelog/60419.fixed
@@ -0,0 +1 @@
+Check for /dev/kvm to detect KVM hypervisor.
diff --git a/salt/modules/virt.py b/salt/modules/virt.py
index d8a8c51ce5..2f2aa63957 100644
--- a/salt/modules/virt.py
+++ b/salt/modules/virt.py
@@ -5745,12 +5745,7 @@ def _is_kvm_hyper():
     """
     Returns a bool whether or not this node is a KVM hypervisor
     """
-    try:
-        with salt.utils.files.fopen("/proc/modules") as fp_:
-            if "kvm_" not in salt.utils.stringutils.to_unicode(fp_.read()):
-                return False
-    except OSError:
-        # No /proc/modules? Are we on Windows? Or Solaris?
+    if not os.path.exists("/dev/kvm"):
         return False
     return "libvirtd" in __salt__["cmd.run"](__grains__["ps"])
 
diff --git a/tests/pytests/unit/modules/virt/test_host.py b/tests/pytests/unit/modules/virt/test_host.py
index 6c9ac79337..c5cadb8aa0 100644
--- a/tests/pytests/unit/modules/virt/test_host.py
+++ b/tests/pytests/unit/modules/virt/test_host.py
@@ -1,5 +1,8 @@
+import os.path
+
 import pytest
 import salt.modules.virt as virt
+from tests.support.mock import MagicMock, patch
 
 from .conftest import loader_modules_config
 
@@ -217,3 +220,19 @@ def test_node_devices(make_mock_device):
             "device name": "pci_0000_02_10_7",
         },
     ]
+
+
+@pytest.mark.parametrize(
+    "dev_kvm, libvirtd", [(True, True), (False, False), (True, False)]
+)
+def test_is_kvm(dev_kvm, libvirtd):
+    """
+    Test the virt._is_kvm_hyper() function
+    """
+    with patch.dict(os.path.__dict__, {"exists": MagicMock(return_value=dev_kvm)}):
+        processes = ["libvirtd"] if libvirtd else []
+        with patch.dict(virt.__grains__, {"ps": MagicMock(return_value="foo")}):
+            with patch.dict(
+                virt.__salt__, {"cmd.run": MagicMock(return_value=processes)}
+            ):
+                assert virt._is_kvm_hyper() == (dev_kvm and libvirtd)
-- 
2.31.1


openSUSE Build Service is sponsored by