46a734
From 01489fb91f64f6137ddf88c39feabe4296f3a156 Mon Sep 17 00:00:00 2001
46a734
From: Anh Vo <anhvo@microsoft.com>
46a734
Date: Fri, 23 Apr 2021 10:18:05 -0400
46a734
Subject: [PATCH 4/7] Azure: eject the provisioning iso before reporting ready
46a734
 (#861)
46a734
46a734
RH-Author: Eduardo Otubo <otubo@redhat.com>
46a734
RH-MergeRequest: 45: Add support for userdata on Azure from IMDS
46a734
RH-Commit: [4/7] ba830546a62ac5bea33b91d133d364a897b9f6c0
46a734
RH-Bugzilla: 2023940
46a734
RH-Acked-by: Emanuele Giuseppe Esposito <eesposit@redhat.com>
46a734
RH-Acked-by: Mohamed Gamal Morsy <mmorsy@redhat.com>
46a734
46a734
Due to hyper-v implementations, iso ejection is more efficient if performed
46a734
from within the guest. The code will attempt to perform a best-effort ejection.
46a734
Failure during ejection will not prevent reporting ready from happening. If iso
46a734
ejection is successful, later iso ejection from the platform will be a no-op.
46a734
In the event the iso ejection from the guest fails, iso ejection will still happen at
46a734
the platform level.
46a734
---
46a734
 cloudinit/sources/DataSourceAzure.py          | 22 +++++++++++++++---
46a734
 cloudinit/sources/helpers/azure.py            | 23 ++++++++++++++++---
46a734
 .../test_datasource/test_azure_helper.py      | 13 +++++++++--
46a734
 3 files changed, 50 insertions(+), 8 deletions(-)
46a734
46a734
diff --git a/cloudinit/sources/DataSourceAzure.py b/cloudinit/sources/DataSourceAzure.py
46a734
index 020b7006..39e67c4f 100755
46a734
--- a/cloudinit/sources/DataSourceAzure.py
46a734
+++ b/cloudinit/sources/DataSourceAzure.py
46a734
@@ -332,6 +332,7 @@ class DataSourceAzure(sources.DataSource):
46a734
     dsname = 'Azure'
46a734
     _negotiated = False
46a734
     _metadata_imds = sources.UNSET
46a734
+    _ci_pkl_version = 1
46a734
 
46a734
     def __init__(self, sys_cfg, distro, paths):
46a734
         sources.DataSource.__init__(self, sys_cfg, distro, paths)
46a734
@@ -346,8 +347,13 @@ class DataSourceAzure(sources.DataSource):
46a734
         # Regenerate network config new_instance boot and every boot
46a734
         self.update_events['network'].add(EventType.BOOT)
46a734
         self._ephemeral_dhcp_ctx = None
46a734
-
46a734
         self.failed_desired_api_version = False
46a734
+        self.iso_dev = None
46a734
+
46a734
+    def _unpickle(self, ci_pkl_version: int) -> None:
46a734
+        super()._unpickle(ci_pkl_version)
46a734
+        if "iso_dev" not in self.__dict__:
46a734
+            self.iso_dev = None
46a734
 
46a734
     def __str__(self):
46a734
         root = sources.DataSource.__str__(self)
46a734
@@ -459,6 +465,13 @@ class DataSourceAzure(sources.DataSource):
46a734
                     '%s was not mountable' % cdev, logger_func=LOG.warning)
46a734
                 continue
46a734
 
46a734
+            report_diagnostic_event("Found provisioning metadata in %s" % cdev,
46a734
+                                    logger_func=LOG.debug)
46a734
+
46a734
+            # save the iso device for ejection before reporting ready
46a734
+            if cdev.startswith("/dev"):
46a734
+                self.iso_dev = cdev
46a734
+
46a734
             perform_reprovision = reprovision or self._should_reprovision(ret)
46a734
             perform_reprovision_after_nic_attach = (
46a734
                 reprovision_after_nic_attach or
46a734
@@ -1226,7 +1239,9 @@ class DataSourceAzure(sources.DataSource):
46a734
         @return: The success status of sending the ready signal.
46a734
         """
46a734
         try:
46a734
-            get_metadata_from_fabric(None, lease['unknown-245'])
46a734
+            get_metadata_from_fabric(fallback_lease_file=None,
46a734
+                                     dhcp_opts=lease['unknown-245'],
46a734
+                                     iso_dev=self.iso_dev)
46a734
             return True
46a734
         except Exception as e:
46a734
             report_diagnostic_event(
46a734
@@ -1332,7 +1347,8 @@ class DataSourceAzure(sources.DataSource):
46a734
         metadata_func = partial(get_metadata_from_fabric,
46a734
                                 fallback_lease_file=self.
46a734
                                 dhclient_lease_file,
46a734
-                                pubkey_info=pubkey_info)
46a734
+                                pubkey_info=pubkey_info,
46a734
+                                iso_dev=self.iso_dev)
46a734
 
46a734
         LOG.debug("negotiating with fabric via agent command %s",
46a734
                   self.ds_cfg['agent_command'])
46a734
diff --git a/cloudinit/sources/helpers/azure.py b/cloudinit/sources/helpers/azure.py
46a734
index 03e7156b..ad476076 100755
46a734
--- a/cloudinit/sources/helpers/azure.py
46a734
+++ b/cloudinit/sources/helpers/azure.py
46a734
@@ -865,7 +865,19 @@ class WALinuxAgentShim:
46a734
         return endpoint_ip_address
46a734
 
46a734
     @azure_ds_telemetry_reporter
46a734
-    def register_with_azure_and_fetch_data(self, pubkey_info=None) -> dict:
46a734
+    def eject_iso(self, iso_dev) -> None:
46a734
+        try:
46a734
+            LOG.debug("Ejecting the provisioning iso")
46a734
+            subp.subp(['eject', iso_dev])
46a734
+        except Exception as e:
46a734
+            report_diagnostic_event(
46a734
+                "Failed ejecting the provisioning iso: %s" % e,
46a734
+                logger_func=LOG.debug)
46a734
+
46a734
+    @azure_ds_telemetry_reporter
46a734
+    def register_with_azure_and_fetch_data(self,
46a734
+                                           pubkey_info=None,
46a734
+                                           iso_dev=None) -> dict:
46a734
         """Gets the VM's GoalState from Azure, uses the GoalState information
46a734
         to report ready/send the ready signal/provisioning complete signal to
46a734
         Azure, and then uses pubkey_info to filter and obtain the user's
46a734
@@ -891,6 +903,10 @@ class WALinuxAgentShim:
46a734
             ssh_keys = self._get_user_pubkeys(goal_state, pubkey_info)
46a734
         health_reporter = GoalStateHealthReporter(
46a734
             goal_state, self.azure_endpoint_client, self.endpoint)
46a734
+
46a734
+        if iso_dev is not None:
46a734
+            self.eject_iso(iso_dev)
46a734
+
46a734
         health_reporter.send_ready_signal()
46a734
         return {'public-keys': ssh_keys}
46a734
 
46a734
@@ -1046,11 +1062,12 @@ class WALinuxAgentShim:
46a734
 
46a734
 @azure_ds_telemetry_reporter
46a734
 def get_metadata_from_fabric(fallback_lease_file=None, dhcp_opts=None,
46a734
-                             pubkey_info=None):
46a734
+                             pubkey_info=None, iso_dev=None):
46a734
     shim = WALinuxAgentShim(fallback_lease_file=fallback_lease_file,
46a734
                             dhcp_options=dhcp_opts)
46a734
     try:
46a734
-        return shim.register_with_azure_and_fetch_data(pubkey_info=pubkey_info)
46a734
+        return shim.register_with_azure_and_fetch_data(
46a734
+            pubkey_info=pubkey_info, iso_dev=iso_dev)
46a734
     finally:
46a734
         shim.clean_up()
46a734
 
46a734
diff --git a/tests/unittests/test_datasource/test_azure_helper.py b/tests/unittests/test_datasource/test_azure_helper.py
46a734
index 63482c6c..552c7905 100644
46a734
--- a/tests/unittests/test_datasource/test_azure_helper.py
46a734
+++ b/tests/unittests/test_datasource/test_azure_helper.py
46a734
@@ -1009,6 +1009,14 @@ class TestWALinuxAgentShim(CiTestCase):
46a734
         self.GoalState.return_value.container_id = self.test_container_id
46a734
         self.GoalState.return_value.instance_id = self.test_instance_id
46a734
 
46a734
+    def test_eject_iso_is_called(self):
46a734
+        shim = wa_shim()
46a734
+        with mock.patch.object(
46a734
+            shim, 'eject_iso', autospec=True
46a734
+        ) as m_eject_iso:
46a734
+            shim.register_with_azure_and_fetch_data(iso_dev="/dev/sr0")
46a734
+            m_eject_iso.assert_called_once_with("/dev/sr0")
46a734
+
46a734
     def test_http_client_does_not_use_certificate_for_report_ready(self):
46a734
         shim = wa_shim()
46a734
         shim.register_with_azure_and_fetch_data()
46a734
@@ -1283,13 +1291,14 @@ class TestGetMetadataGoalStateXMLAndReportReadyToFabric(CiTestCase):
46a734
 
46a734
     def test_calls_shim_register_with_azure_and_fetch_data(self):
46a734
         m_pubkey_info = mock.MagicMock()
46a734
-        azure_helper.get_metadata_from_fabric(pubkey_info=m_pubkey_info)
46a734
+        azure_helper.get_metadata_from_fabric(
46a734
+            pubkey_info=m_pubkey_info, iso_dev="/dev/sr0")
46a734
         self.assertEqual(
46a734
             1,
46a734
             self.m_shim.return_value
46a734
                 .register_with_azure_and_fetch_data.call_count)
46a734
         self.assertEqual(
46a734
-            mock.call(pubkey_info=m_pubkey_info),
46a734
+            mock.call(iso_dev="/dev/sr0", pubkey_info=m_pubkey_info),
46a734
             self.m_shim.return_value
46a734
                 .register_with_azure_and_fetch_data.call_args)
46a734
 
46a734
-- 
46a734
2.27.0
46a734