File virt-use-dev-kvm-to-detect-kvm-384.patch of Package salt.21019

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

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 4927dd4afe..29385ac64c 100644
--- a/salt/modules/virt.py
+++ b/salt/modules/virt.py
@@ -5646,12 +5646,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 555deb23bb..70e9095387 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",
         },
     ] == virt.node_devices()
+
+
+@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