From 7f09102ad601cb5225fa0ffe280d77a75f435e93 Mon Sep 17 00:00:00 2001
From: Robert Schweikert <rjschwei@suse.com>
From 7f09102ad601cb5225fa0ffe280d77a75f435e93 Mon Sep 17 00:00:00 2001
From: Robert Schweikert <rjschwei@suse.com>
Date: Tue, 7 Jan 2025 15:59:26 -0500
Subject: [PATCH] fix: Wait for udev on openstack (#5947)

It is possible that we outrun udev and when we try to enumerate the macs
any given mac may not yet be present. If we detect the condition give
udev a chance to catch up and check the system macs again before
triggering an error.

Fixes GH-4125
---
 cloudinit/sources/helpers/openstack.py      |  6 +++++-
 tests/unittests/sources/test_configdrive.py | 15 +++++++++------
 2 files changed, 14 insertions(+), 7 deletions(-)

diff --git a/cloudinit/sources/helpers/openstack.py b/cloudinit/sources/helpers/openstack.py
index 97ec18faf98..bea1a2ce29f 100644
--- a/cloudinit/sources/helpers/openstack.py
+++ b/cloudinit/sources/helpers/openstack.py
@@ -771,7 +771,11 @@ def convert_net_json(network_json=None, known_macs=None):
             if not mac:
                 raise ValueError("No mac_address or name entry for %s" % d)
             if mac not in known_macs:
-                raise ValueError("Unable to find a system nic for %s" % d)
+                # Let's give udev a chance to catch up
+                util.udevadm_settle()
+                known_macs = net.get_interfaces_by_mac()
+                if mac not in known_macs:
+                    raise ValueError("Unable to find a system nic for %s" % d)
             d["name"] = known_macs[mac]

         for cfg, key, fmt, targets in link_updates:
diff --git a/tests/unittests/sources/test_configdrive.py b/tests/unittests/sources/test_configdrive.py
index 70da4812aee..a724f7613a0 100644
--- a/tests/unittests/sources/test_configdrive.py
+++ b/tests/unittests/sources/test_configdrive.py
@@ -896,12 +896,15 @@ def test_convert_reads_system_prefers_name(self, get_interfaces_by_mac):

     def test_convert_raises_value_error_on_missing_name(self):
         macs = {"aa:aa:aa:aa:aa:00": "ens1"}
-        self.assertRaises(
-            ValueError,
-            openstack.convert_net_json,
-            NETWORK_DATA,
-            known_macs=macs,
-        )
+        with mock.patch(
+            "cloudinit.sources.helpers.openstack.util.udevadm_settle"
+        ):
+            self.assertRaises(
+                ValueError,
+                openstack.convert_net_json,
+                NETWORK_DATA,
+                known_macs=macs,
+            )

     def test_conversion_with_route(self):
         ncfg = openstack.convert_net_json(
-- 
2.33.0

