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.
 
Reference:https://github.com/canonical/cloud-init/commit/7f09102ad601cb5225fa0ffe280d77a75f435e93
Conflict:test format diff.
 
Fixes GH-4125
---
 cloudinit/sources/helpers/openstack.py              | 6 +++++-
 tests/unittests/test_datasource/test_configdrive.py | 7 +++++--
 2 files changed, 10 insertions(+), 3 deletions(-)
 
diff --git a/cloudinit/sources/helpers/openstack.py b/cloudinit/sources/helpers/openstack.py
index 51e491f..2adbf5f 100644
--- a/cloudinit/sources/helpers/openstack.py
+++ b/cloudinit/sources/helpers/openstack.py
@@ -702,7 +702,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/test_datasource/test_configdrive.py b/tests/unittests/test_datasource/test_configdrive.py
index 5109723..f6ef537 100644
--- a/tests/unittests/test_datasource/test_configdrive.py
+++ b/tests/unittests/test_datasource/test_configdrive.py
@@ -694,8 +694,11 @@ class TestConvertNetworkData(CiTestCase):
 
     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(NETWORK_DATA_2,
-- 
2.33.0

