088c30
From 2a2a5cdec0de0b96d503f9357c1641043574f90a Mon Sep 17 00:00:00 2001
088c30
From: Thomas Stringer <thstring@microsoft.com>
088c30
Date: Wed, 3 Mar 2021 11:07:43 -0500
088c30
Subject: [PATCH 1/7] Add flexibility to IMDS api-version (#793)
088c30
088c30
RH-Author: Eduardo Otubo <otubo@redhat.com>
088c30
RH-MergeRequest: 45: Add support for userdata on Azure from IMDS
088c30
RH-Commit: [1/7] 9aa42581c4ff175fb6f8f4a78d94cac9c9971062
088c30
RH-Bugzilla: 2023940
088c30
RH-Acked-by: Emanuele Giuseppe Esposito <eesposit@redhat.com>
088c30
RH-Acked-by: Mohamed Gamal Morsy <mmorsy@redhat.com>
088c30
088c30
Add flexibility to IMDS api-version by having both a desired IMDS
088c30
api-version and a minimum api-version. The desired api-version will
088c30
be used first, and if that fails it will fall back to the minimum
088c30
api-version.
088c30
---
088c30
 cloudinit/sources/DataSourceAzure.py          | 113 ++++++++++++++----
088c30
 tests/unittests/test_datasource/test_azure.py |  42 ++++++-
088c30
 2 files changed, 129 insertions(+), 26 deletions(-)
088c30
088c30
diff --git a/cloudinit/sources/DataSourceAzure.py b/cloudinit/sources/DataSourceAzure.py
088c30
index 553b5a7e..de1452ce 100755
088c30
--- a/cloudinit/sources/DataSourceAzure.py
088c30
+++ b/cloudinit/sources/DataSourceAzure.py
088c30
@@ -78,17 +78,15 @@ AGENT_SEED_DIR = '/var/lib/waagent'
088c30
 # In the event where the IMDS primary server is not
088c30
 # available, it takes 1s to fallback to the secondary one
088c30
 IMDS_TIMEOUT_IN_SECONDS = 2
088c30
-IMDS_URL = "http://169.254.169.254/metadata/"
088c30
-IMDS_VER = "2019-06-01"
088c30
-IMDS_VER_PARAM = "api-version={}".format(IMDS_VER)
088c30
+IMDS_URL = "http://169.254.169.254/metadata"
088c30
+IMDS_VER_MIN = "2019-06-01"
088c30
+IMDS_VER_WANT = "2020-09-01"
088c30
 
088c30
 
088c30
 class metadata_type(Enum):
088c30
-    compute = "{}instance?{}".format(IMDS_URL, IMDS_VER_PARAM)
088c30
-    network = "{}instance/network?{}".format(IMDS_URL,
088c30
-                                             IMDS_VER_PARAM)
088c30
-    reprovisiondata = "{}reprovisiondata?{}".format(IMDS_URL,
088c30
-                                                    IMDS_VER_PARAM)
088c30
+    compute = "{}/instance".format(IMDS_URL)
088c30
+    network = "{}/instance/network".format(IMDS_URL)
088c30
+    reprovisiondata = "{}/reprovisiondata".format(IMDS_URL)
088c30
 
088c30
 
088c30
 PLATFORM_ENTROPY_SOURCE = "/sys/firmware/acpi/tables/OEM0"
088c30
@@ -349,6 +347,8 @@ class DataSourceAzure(sources.DataSource):
088c30
         self.update_events['network'].add(EventType.BOOT)
088c30
         self._ephemeral_dhcp_ctx = None
088c30
 
088c30
+        self.failed_desired_api_version = False
088c30
+
088c30
     def __str__(self):
088c30
         root = sources.DataSource.__str__(self)
088c30
         return "%s [seed=%s]" % (root, self.seed)
088c30
@@ -520,8 +520,10 @@ class DataSourceAzure(sources.DataSource):
088c30
                     self._wait_for_all_nics_ready()
088c30
                 ret = self._reprovision()
088c30
 
088c30
-            imds_md = get_metadata_from_imds(
088c30
-                self.fallback_interface, retries=10)
088c30
+            imds_md = self.get_imds_data_with_api_fallback(
088c30
+                self.fallback_interface,
088c30
+                retries=10
088c30
+            )
088c30
             (md, userdata_raw, cfg, files) = ret
088c30
             self.seed = cdev
088c30
             crawled_data.update({
088c30
@@ -652,6 +654,57 @@ class DataSourceAzure(sources.DataSource):
088c30
             self.ds_cfg['data_dir'], crawled_data['files'], dirmode=0o700)
088c30
         return True
088c30
 
088c30
+    @azure_ds_telemetry_reporter
088c30
+    def get_imds_data_with_api_fallback(
088c30
+            self,
088c30
+            fallback_nic,
088c30
+            retries,
088c30
+            md_type=metadata_type.compute):
088c30
+        """
088c30
+        Wrapper for get_metadata_from_imds so that we can have flexibility
088c30
+        in which IMDS api-version we use. If a particular instance of IMDS
088c30
+        does not have the api version that is desired, we want to make
088c30
+        this fault tolerant and fall back to a good known minimum api
088c30
+        version.
088c30
+        """
088c30
+
088c30
+        if not self.failed_desired_api_version:
088c30
+            for _ in range(retries):
088c30
+                try:
088c30
+                    LOG.info(
088c30
+                        "Attempting IMDS api-version: %s",
088c30
+                        IMDS_VER_WANT
088c30
+                    )
088c30
+                    return get_metadata_from_imds(
088c30
+                        fallback_nic=fallback_nic,
088c30
+                        retries=0,
088c30
+                        md_type=md_type,
088c30
+                        api_version=IMDS_VER_WANT
088c30
+                    )
088c30
+                except UrlError as err:
088c30
+                    LOG.info(
088c30
+                        "UrlError with IMDS api-version: %s",
088c30
+                        IMDS_VER_WANT
088c30
+                    )
088c30
+                    if err.code == 400:
088c30
+                        log_msg = "Fall back to IMDS api-version: {}".format(
088c30
+                            IMDS_VER_MIN
088c30
+                        )
088c30
+                        report_diagnostic_event(
088c30
+                            log_msg,
088c30
+                            logger_func=LOG.info
088c30
+                        )
088c30
+                        self.failed_desired_api_version = True
088c30
+                        break
088c30
+
088c30
+        LOG.info("Using IMDS api-version: %s", IMDS_VER_MIN)
088c30
+        return get_metadata_from_imds(
088c30
+            fallback_nic=fallback_nic,
088c30
+            retries=retries,
088c30
+            md_type=md_type,
088c30
+            api_version=IMDS_VER_MIN
088c30
+        )
088c30
+
088c30
     def device_name_to_device(self, name):
088c30
         return self.ds_cfg['disk_aliases'].get(name)
088c30
 
088c30
@@ -880,10 +933,11 @@ class DataSourceAzure(sources.DataSource):
088c30
         # primary nic is being attached first helps here. Otherwise each nic
088c30
         # could add several seconds of delay.
088c30
         try:
088c30
-            imds_md = get_metadata_from_imds(
088c30
+            imds_md = self.get_imds_data_with_api_fallback(
088c30
                 ifname,
088c30
                 5,
088c30
-                metadata_type.network)
088c30
+                metadata_type.network
088c30
+            )
088c30
         except Exception as e:
088c30
             LOG.warning(
088c30
                 "Failed to get network metadata using nic %s. Attempt to "
088c30
@@ -1017,7 +1071,10 @@ class DataSourceAzure(sources.DataSource):
088c30
     def _poll_imds(self):
088c30
         """Poll IMDS for the new provisioning data until we get a valid
088c30
         response. Then return the returned JSON object."""
088c30
-        url = metadata_type.reprovisiondata.value
088c30
+        url = "{}?api-version={}".format(
088c30
+            metadata_type.reprovisiondata.value,
088c30
+            IMDS_VER_MIN
088c30
+        )
088c30
         headers = {"Metadata": "true"}
088c30
         nl_sock = None
088c30
         report_ready = bool(not os.path.isfile(REPORTED_READY_MARKER_FILE))
088c30
@@ -2059,7 +2116,8 @@ def _generate_network_config_from_fallback_config() -> dict:
088c30
 @azure_ds_telemetry_reporter
088c30
 def get_metadata_from_imds(fallback_nic,
088c30
                            retries,
088c30
-                           md_type=metadata_type.compute):
088c30
+                           md_type=metadata_type.compute,
088c30
+                           api_version=IMDS_VER_MIN):
088c30
     """Query Azure's instance metadata service, returning a dictionary.
088c30
 
088c30
     If network is not up, setup ephemeral dhcp on fallback_nic to talk to the
088c30
@@ -2069,13 +2127,16 @@ def get_metadata_from_imds(fallback_nic,
088c30
     @param fallback_nic: String. The name of the nic which requires active
088c30
         network in order to query IMDS.
088c30
     @param retries: The number of retries of the IMDS_URL.
088c30
+    @param md_type: Metadata type for IMDS request.
088c30
+    @param api_version: IMDS api-version to use in the request.
088c30
 
088c30
     @return: A dict of instance metadata containing compute and network
088c30
         info.
088c30
     """
088c30
     kwargs = {'logfunc': LOG.debug,
088c30
               'msg': 'Crawl of Azure Instance Metadata Service (IMDS)',
088c30
-              'func': _get_metadata_from_imds, 'args': (retries, md_type,)}
088c30
+              'func': _get_metadata_from_imds,
088c30
+              'args': (retries, md_type, api_version,)}
088c30
     if net.is_up(fallback_nic):
088c30
         return util.log_time(**kwargs)
088c30
     else:
088c30
@@ -2091,20 +2152,26 @@ def get_metadata_from_imds(fallback_nic,
088c30
 
088c30
 
088c30
 @azure_ds_telemetry_reporter
088c30
-def _get_metadata_from_imds(retries, md_type=metadata_type.compute):
088c30
-
088c30
-    url = md_type.value
088c30
+def _get_metadata_from_imds(
088c30
+        retries,
088c30
+        md_type=metadata_type.compute,
088c30
+        api_version=IMDS_VER_MIN):
088c30
+    url = "{}?api-version={}".format(md_type.value, api_version)
088c30
     headers = {"Metadata": "true"}
088c30
     try:
088c30
         response = readurl(
088c30
             url, timeout=IMDS_TIMEOUT_IN_SECONDS, headers=headers,
088c30
             retries=retries, exception_cb=retry_on_url_exc)
088c30
     except Exception as e:
088c30
-        report_diagnostic_event(
088c30
-            'Ignoring IMDS instance metadata. '
088c30
-            'Get metadata from IMDS failed: %s' % e,
088c30
-            logger_func=LOG.warning)
088c30
-        return {}
088c30
+        # pylint:disable=no-member
088c30
+        if isinstance(e, UrlError) and e.code == 400:
088c30
+            raise
088c30
+        else:
088c30
+            report_diagnostic_event(
088c30
+                'Ignoring IMDS instance metadata. '
088c30
+                'Get metadata from IMDS failed: %s' % e,
088c30
+                logger_func=LOG.warning)
088c30
+            return {}
088c30
     try:
088c30
         from json.decoder import JSONDecodeError
088c30
         json_decode_error = JSONDecodeError
088c30
diff --git a/tests/unittests/test_datasource/test_azure.py b/tests/unittests/test_datasource/test_azure.py
088c30
index f597c723..dedebeb1 100644
088c30
--- a/tests/unittests/test_datasource/test_azure.py
088c30
+++ b/tests/unittests/test_datasource/test_azure.py
088c30
@@ -408,7 +408,9 @@ class TestGetMetadataFromIMDS(HttprettyTestCase):
088c30
 
088c30
     def setUp(self):
088c30
         super(TestGetMetadataFromIMDS, self).setUp()
088c30
-        self.network_md_url = dsaz.IMDS_URL + "instance?api-version=2019-06-01"
088c30
+        self.network_md_url = "{}/instance?api-version=2019-06-01".format(
088c30
+            dsaz.IMDS_URL
088c30
+        )
088c30
 
088c30
     @mock.patch(MOCKPATH + 'readurl')
088c30
     @mock.patch(MOCKPATH + 'EphemeralDHCPv4', autospec=True)
088c30
@@ -518,7 +520,7 @@ class TestGetMetadataFromIMDS(HttprettyTestCase):
088c30
         """Return empty dict when IMDS network metadata is absent."""
088c30
         httpretty.register_uri(
088c30
             httpretty.GET,
088c30
-            dsaz.IMDS_URL + 'instance?api-version=2017-12-01',
088c30
+            dsaz.IMDS_URL + '/instance?api-version=2017-12-01',
088c30
             body={}, status=404)
088c30
 
088c30
         m_net_is_up.return_value = True  # skips dhcp
088c30
@@ -1877,6 +1879,40 @@ scbus-1 on xpt0 bus 0
088c30
         ssh_keys = dsrc.get_public_ssh_keys()
088c30
         self.assertEqual(ssh_keys, ['key2'])
088c30
 
088c30
+    @mock.patch(MOCKPATH + 'get_metadata_from_imds')
088c30
+    def test_imds_api_version_wanted_nonexistent(
088c30
+            self,
088c30
+            m_get_metadata_from_imds):
088c30
+        def get_metadata_from_imds_side_eff(*args, **kwargs):
088c30
+            if kwargs['api_version'] == dsaz.IMDS_VER_WANT:
088c30
+                raise url_helper.UrlError("No IMDS version", code=400)
088c30
+            return NETWORK_METADATA
088c30
+        m_get_metadata_from_imds.side_effect = get_metadata_from_imds_side_eff
088c30
+        sys_cfg = {'datasource': {'Azure': {'apply_network_config': True}}}
088c30
+        odata = {'HostName': "myhost", 'UserName': "myuser"}
088c30
+        data = {
088c30
+            'ovfcontent': construct_valid_ovf_env(data=odata),
088c30
+            'sys_cfg': sys_cfg
088c30
+        }
088c30
+        dsrc = self._get_ds(data)
088c30
+        dsrc.get_data()
088c30
+        self.assertIsNotNone(dsrc.metadata)
088c30
+        self.assertTrue(dsrc.failed_desired_api_version)
088c30
+
088c30
+    @mock.patch(
088c30
+        MOCKPATH + 'get_metadata_from_imds', return_value=NETWORK_METADATA)
088c30
+    def test_imds_api_version_wanted_exists(self, m_get_metadata_from_imds):
088c30
+        sys_cfg = {'datasource': {'Azure': {'apply_network_config': True}}}
088c30
+        odata = {'HostName': "myhost", 'UserName': "myuser"}
088c30
+        data = {
088c30
+            'ovfcontent': construct_valid_ovf_env(data=odata),
088c30
+            'sys_cfg': sys_cfg
088c30
+        }
088c30
+        dsrc = self._get_ds(data)
088c30
+        dsrc.get_data()
088c30
+        self.assertIsNotNone(dsrc.metadata)
088c30
+        self.assertFalse(dsrc.failed_desired_api_version)
088c30
+
088c30
 
088c30
 class TestAzureBounce(CiTestCase):
088c30
 
088c30
@@ -2657,7 +2693,7 @@ class TestPreprovisioningHotAttachNics(CiTestCase):
088c30
     @mock.patch(MOCKPATH + 'DataSourceAzure.wait_for_link_up')
088c30
     @mock.patch('cloudinit.sources.helpers.netlink.wait_for_nic_attach_event')
088c30
     @mock.patch('cloudinit.sources.net.find_fallback_nic')
088c30
-    @mock.patch(MOCKPATH + 'get_metadata_from_imds')
088c30
+    @mock.patch(MOCKPATH + 'DataSourceAzure.get_imds_data_with_api_fallback')
088c30
     @mock.patch(MOCKPATH + 'EphemeralDHCPv4')
088c30
     @mock.patch(MOCKPATH + 'DataSourceAzure._wait_for_nic_detach')
088c30
     @mock.patch('os.path.isfile')
088c30
-- 
088c30
2.27.0
088c30