738010
From 7765776d538e61639d1ea920919211f780b75d13 Mon Sep 17 00:00:00 2001
738010
From: Eduardo Otubo <otubo@redhat.com>
738010
Date: Wed, 15 May 2019 12:15:26 +0200
738010
Subject: [PATCH 2/5] DatasourceAzure: add additional logging for azure
738010
 datasource
738010
738010
RH-Author: Eduardo Otubo <otubo@redhat.com>
738010
Message-id: <20190515121529.11191-3-otubo@redhat.com>
738010
Patchwork-id: 87882
738010
O-Subject: [rhel-7 cloud-init PATCHv2 2/5] DatasourceAzure: add additional logging for azure datasource
738010
Bugzilla: 1687565
738010
RH-Acked-by: Vitaly Kuznetsov <vkuznets@redhat.com>
738010
RH-Acked-by: Mohammed Gamal <mgamal@redhat.com>
738010
738010
From: Anh Vo <anhvo@microsoft.com>
738010
738010
BZ: 1687565
738010
BRANCH: rhel7/master-18.5
738010
UPSTREAM: 0d8c8839
738010
BREW: 21696239
738010
738010
commit 0d8c88393b51db6454491a379dcc2e691551217a
738010
Author: Anh Vo <anhvo@microsoft.com>
738010
Date:   Wed Apr 3 18:23:18 2019 +0000
738010
738010
    DatasourceAzure: add additional logging for azure datasource
738010
738010
    Create an Azure logging decorator and use additional ReportEventStack
738010
    context managers to provide additional logging details.
738010
738010
Signed-off-by: Eduardo Otubo <otubo@redhat.com>
738010
Signed-off-by: Miroslav Rezanina <mrezanin@redhat.com>
738010
---
738010
 cloudinit/sources/DataSourceAzure.py | 231 ++++++++++++++++++++++-------------
738010
 cloudinit/sources/helpers/azure.py   |  31 +++++
738010
 2 files changed, 179 insertions(+), 83 deletions(-)
738010
 mode change 100644 => 100755 cloudinit/sources/DataSourceAzure.py
738010
 mode change 100644 => 100755 cloudinit/sources/helpers/azure.py
738010
738010
diff --git a/cloudinit/sources/DataSourceAzure.py b/cloudinit/sources/DataSourceAzure.py
738010
old mode 100644
738010
new mode 100755
738010
index a768b2c..c827816
738010
--- a/cloudinit/sources/DataSourceAzure.py
738010
+++ b/cloudinit/sources/DataSourceAzure.py
738010
@@ -21,10 +21,14 @@ from cloudinit import net
738010
 from cloudinit.event import EventType
738010
 from cloudinit.net.dhcp import EphemeralDHCPv4
738010
 from cloudinit import sources
738010
-from cloudinit.sources.helpers.azure import get_metadata_from_fabric
738010
 from cloudinit.sources.helpers import netlink
738010
 from cloudinit.url_helper import UrlError, readurl, retry_on_url_exc
738010
 from cloudinit import util
738010
+from cloudinit.reporting import events
738010
+
738010
+from cloudinit.sources.helpers.azure import (azure_ds_reporter,
738010
+                                             azure_ds_telemetry_reporter,
738010
+                                             get_metadata_from_fabric)
738010
 
738010
 LOG = logging.getLogger(__name__)
738010
 
738010
@@ -244,6 +248,7 @@ def set_hostname(hostname, hostname_command='hostname'):
738010
     util.subp(['hostnamectl', 'set-hostname', str(hostname)])
738010
 
738010
 
738010
+@azure_ds_telemetry_reporter
738010
 @contextlib.contextmanager
738010
 def temporary_hostname(temp_hostname, cfg, hostname_command='hostname'):
738010
     """
738010
@@ -290,6 +295,7 @@ class DataSourceAzure(sources.DataSource):
738010
         root = sources.DataSource.__str__(self)
738010
         return "%s [seed=%s]" % (root, self.seed)
738010
 
738010
+    @azure_ds_telemetry_reporter
738010
     def bounce_network_with_azure_hostname(self):
738010
         # When using cloud-init to provision, we have to set the hostname from
738010
         # the metadata and "bounce" the network to force DDNS to update via
738010
@@ -315,6 +321,7 @@ class DataSourceAzure(sources.DataSource):
738010
                     util.logexc(LOG, "handling set_hostname failed")
738010
         return False
738010
 
738010
+    @azure_ds_telemetry_reporter
738010
     def get_metadata_from_agent(self):
738010
         temp_hostname = self.metadata.get('local-hostname')
738010
         agent_cmd = self.ds_cfg['agent_command']
738010
@@ -344,15 +351,18 @@ class DataSourceAzure(sources.DataSource):
738010
                 LOG.debug("ssh authentication: "
738010
                           "using fingerprint from fabirc")
738010
 
738010
-        # wait very long for public SSH keys to arrive
738010
-        # https://bugs.launchpad.net/cloud-init/+bug/1717611
738010
-        missing = util.log_time(logfunc=LOG.debug,
738010
-                                msg="waiting for SSH public key files",
738010
-                                func=util.wait_for_files,
738010
-                                args=(fp_files, 900))
738010
-
738010
-        if len(missing):
738010
-            LOG.warning("Did not find files, but going on: %s", missing)
738010
+        with events.ReportEventStack(
738010
+                name="waiting-for-ssh-public-key",
738010
+                description="wait for agents to retrieve ssh keys",
738010
+                parent=azure_ds_reporter):
738010
+            # wait very long for public SSH keys to arrive
738010
+            # https://bugs.launchpad.net/cloud-init/+bug/1717611
738010
+            missing = util.log_time(logfunc=LOG.debug,
738010
+                                    msg="waiting for SSH public key files",
738010
+                                    func=util.wait_for_files,
738010
+                                    args=(fp_files, 900))
738010
+            if len(missing):
738010
+                LOG.warning("Did not find files, but going on: %s", missing)
738010
 
738010
         metadata = {}
738010
         metadata['public-keys'] = key_value or pubkeys_from_crt_files(fp_files)
738010
@@ -366,6 +376,7 @@ class DataSourceAzure(sources.DataSource):
738010
             subplatform_type = 'seed-dir'
738010
         return '%s (%s)' % (subplatform_type, self.seed)
738010
 
738010
+    @azure_ds_telemetry_reporter
738010
     def crawl_metadata(self):
738010
         """Walk all instance metadata sources returning a dict on success.
738010
 
738010
@@ -467,6 +478,7 @@ class DataSourceAzure(sources.DataSource):
738010
         super(DataSourceAzure, self).clear_cached_attrs(attr_defaults)
738010
         self._metadata_imds = sources.UNSET
738010
 
738010
+    @azure_ds_telemetry_reporter
738010
     def _get_data(self):
738010
         """Crawl and process datasource metadata caching metadata as attrs.
738010
 
738010
@@ -513,6 +525,7 @@ class DataSourceAzure(sources.DataSource):
738010
         # quickly (local check only) if self.instance_id is still valid
738010
         return sources.instance_id_matches_system_uuid(self.get_instance_id())
738010
 
738010
+    @azure_ds_telemetry_reporter
738010
     def setup(self, is_new_instance):
738010
         if self._negotiated is False:
738010
             LOG.debug("negotiating for %s (new_instance=%s)",
738010
@@ -580,6 +593,7 @@ class DataSourceAzure(sources.DataSource):
738010
                 if nl_sock:
738010
                     nl_sock.close()
738010
 
738010
+    @azure_ds_telemetry_reporter
738010
     def _report_ready(self, lease):
738010
         """Tells the fabric provisioning has completed """
738010
         try:
738010
@@ -617,9 +631,14 @@ class DataSourceAzure(sources.DataSource):
738010
     def _reprovision(self):
738010
         """Initiate the reprovisioning workflow."""
738010
         contents = self._poll_imds()
738010
-        md, ud, cfg = read_azure_ovf(contents)
738010
-        return (md, ud, cfg, {'ovf-env.xml': contents})
738010
-
738010
+        with events.ReportEventStack(
738010
+                name="reprovisioning-read-azure-ovf",
738010
+                description="read azure ovf during reprovisioning",
738010
+                parent=azure_ds_reporter):
738010
+            md, ud, cfg = read_azure_ovf(contents)
738010
+            return (md, ud, cfg, {'ovf-env.xml': contents})
738010
+
738010
+    @azure_ds_telemetry_reporter
738010
     def _negotiate(self):
738010
         """Negotiate with fabric and return data from it.
738010
 
738010
@@ -652,6 +671,7 @@ class DataSourceAzure(sources.DataSource):
738010
         util.del_file(REPROVISION_MARKER_FILE)
738010
         return fabric_data
738010
 
738010
+    @azure_ds_telemetry_reporter
738010
     def activate(self, cfg, is_new_instance):
738010
         address_ephemeral_resize(is_new_instance=is_new_instance,
738010
                                  preserve_ntfs=self.ds_cfg.get(
738010
@@ -690,12 +710,14 @@ def _partitions_on_device(devpath, maxnum=16):
738010
     return []
738010
 
738010
 
738010
+@azure_ds_telemetry_reporter
738010
 def _has_ntfs_filesystem(devpath):
738010
     ntfs_devices = util.find_devs_with("TYPE=ntfs", no_cache=True)
738010
     LOG.debug('ntfs_devices found = %s', ntfs_devices)
738010
     return os.path.realpath(devpath) in ntfs_devices
738010
 
738010
 
738010
+@azure_ds_telemetry_reporter
738010
 def can_dev_be_reformatted(devpath, preserve_ntfs):
738010
     """Determine if the ephemeral drive at devpath should be reformatted.
738010
 
738010
@@ -744,43 +766,59 @@ def can_dev_be_reformatted(devpath, preserve_ntfs):
738010
                (cand_part, cand_path, devpath))
738010
         return False, msg
738010
 
738010
+    @azure_ds_telemetry_reporter
738010
     def count_files(mp):
738010
         ignored = set(['dataloss_warning_readme.txt'])
738010
         return len([f for f in os.listdir(mp) if f.lower() not in ignored])
738010
 
738010
     bmsg = ('partition %s (%s) on device %s was ntfs formatted' %
738010
             (cand_part, cand_path, devpath))
738010
-    try:
738010
-        file_count = util.mount_cb(cand_path, count_files, mtype="ntfs",
738010
-                                   update_env_for_mount={'LANG': 'C'})
738010
-    except util.MountFailedError as e:
738010
-        if "unknown filesystem type 'ntfs'" in str(e):
738010
-            return True, (bmsg + ' but this system cannot mount NTFS,'
738010
-                          ' assuming there are no important files.'
738010
-                          ' Formatting allowed.')
738010
-        return False, bmsg + ' but mount of %s failed: %s' % (cand_part, e)
738010
-
738010
-    if file_count != 0:
738010
-        LOG.warning("it looks like you're using NTFS on the ephemeral disk, "
738010
-                    'to ensure that filesystem does not get wiped, set '
738010
-                    '%s.%s in config', '.'.join(DS_CFG_PATH),
738010
-                    DS_CFG_KEY_PRESERVE_NTFS)
738010
-        return False, bmsg + ' but had %d files on it.' % file_count
738010
+
738010
+    with events.ReportEventStack(
738010
+                name="mount-ntfs-and-count",
738010
+                description="mount-ntfs-and-count",
738010
+                parent=azure_ds_reporter) as evt:
738010
+        try:
738010
+            file_count = util.mount_cb(cand_path, count_files, mtype="ntfs",
738010
+                                       update_env_for_mount={'LANG': 'C'})
738010
+        except util.MountFailedError as e:
738010
+            evt.description = "cannot mount ntfs"
738010
+            if "unknown filesystem type 'ntfs'" in str(e):
738010
+                return True, (bmsg + ' but this system cannot mount NTFS,'
738010
+                              ' assuming there are no important files.'
738010
+                              ' Formatting allowed.')
738010
+            return False, bmsg + ' but mount of %s failed: %s' % (cand_part, e)
738010
+
738010
+        if file_count != 0:
738010
+            evt.description = "mounted and counted %d files" % file_count
738010
+            LOG.warning("it looks like you're using NTFS on the ephemeral"
738010
+                        " disk, to ensure that filesystem does not get wiped,"
738010
+                        " set %s.%s in config", '.'.join(DS_CFG_PATH),
738010
+                        DS_CFG_KEY_PRESERVE_NTFS)
738010
+            return False, bmsg + ' but had %d files on it.' % file_count
738010
 
738010
     return True, bmsg + ' and had no important files. Safe for reformatting.'
738010
 
738010
 
738010
+@azure_ds_telemetry_reporter
738010
 def address_ephemeral_resize(devpath=RESOURCE_DISK_PATH, maxwait=120,
738010
                              is_new_instance=False, preserve_ntfs=False):
738010
     # wait for ephemeral disk to come up
738010
     naplen = .2
738010
-    missing = util.wait_for_files([devpath], maxwait=maxwait, naplen=naplen,
738010
-                                  log_pre="Azure ephemeral disk: ")
738010
-
738010
-    if missing:
738010
-        LOG.warning("ephemeral device '%s' did not appear after %d seconds.",
738010
-                    devpath, maxwait)
738010
-        return
738010
+    with events.ReportEventStack(
738010
+                name="wait-for-ephemeral-disk",
738010
+                description="wait for ephemeral disk",
738010
+                parent=azure_ds_reporter):
738010
+        missing = util.wait_for_files([devpath],
738010
+                                      maxwait=maxwait,
738010
+                                      naplen=naplen,
738010
+                                      log_pre="Azure ephemeral disk: ")
738010
+
738010
+        if missing:
738010
+            LOG.warning("ephemeral device '%s' did"
738010
+                        " not appear after %d seconds.",
738010
+                        devpath, maxwait)
738010
+            return
738010
 
738010
     result = False
738010
     msg = None
738010
@@ -808,6 +846,7 @@ def address_ephemeral_resize(devpath=RESOURCE_DISK_PATH, maxwait=120,
738010
     return
738010
 
738010
 
738010
+@azure_ds_telemetry_reporter
738010
 def perform_hostname_bounce(hostname, cfg, prev_hostname):
738010
     # set the hostname to 'hostname' if it is not already set to that.
738010
     # then, if policy is not off, bounce the interface using command
738010
@@ -843,6 +882,7 @@ def perform_hostname_bounce(hostname, cfg, prev_hostname):
738010
     return True
738010
 
738010
 
738010
+@azure_ds_telemetry_reporter
738010
 def crtfile_to_pubkey(fname, data=None):
738010
     pipeline = ('openssl x509 -noout -pubkey < "$0" |'
738010
                 'ssh-keygen -i -m PKCS8 -f /dev/stdin')
738010
@@ -851,6 +891,7 @@ def crtfile_to_pubkey(fname, data=None):
738010
     return out.rstrip()
738010
 
738010
 
738010
+@azure_ds_telemetry_reporter
738010
 def pubkeys_from_crt_files(flist):
738010
     pubkeys = []
738010
     errors = []
738010
@@ -866,6 +907,7 @@ def pubkeys_from_crt_files(flist):
738010
     return pubkeys
738010
 
738010
 
738010
+@azure_ds_telemetry_reporter
738010
 def write_files(datadir, files, dirmode=None):
738010
 
738010
     def _redact_password(cnt, fname):
738010
@@ -893,6 +935,7 @@ def write_files(datadir, files, dirmode=None):
738010
         util.write_file(filename=fname, content=content, mode=0o600)
738010
 
738010
 
738010
+@azure_ds_telemetry_reporter
738010
 def invoke_agent(cmd):
738010
     # this is a function itself to simplify patching it for test
738010
     if cmd:
738010
@@ -912,6 +955,7 @@ def find_child(node, filter_func):
738010
     return ret
738010
 
738010
 
738010
+@azure_ds_telemetry_reporter
738010
 def load_azure_ovf_pubkeys(sshnode):
738010
     # This parses a 'SSH' node formatted like below, and returns
738010
     # an array of dicts.
738010
@@ -964,6 +1008,7 @@ def load_azure_ovf_pubkeys(sshnode):
738010
     return found
738010
 
738010
 
738010
+@azure_ds_telemetry_reporter
738010
 def read_azure_ovf(contents):
738010
     try:
738010
         dom = minidom.parseString(contents)
738010
@@ -1064,6 +1109,7 @@ def read_azure_ovf(contents):
738010
     return (md, ud, cfg)
738010
 
738010
 
738010
+@azure_ds_telemetry_reporter
738010
 def _extract_preprovisioned_vm_setting(dom):
738010
     """Read the preprovision flag from the ovf. It should not
738010
        exist unless true."""
738010
@@ -1092,6 +1138,7 @@ def encrypt_pass(password, salt_id="$6$"):
738010
     return crypt.crypt(password, salt_id + util.rand_str(strlen=16))
738010
 
738010
 
738010
+@azure_ds_telemetry_reporter
738010
 def _check_freebsd_cdrom(cdrom_dev):
738010
     """Return boolean indicating path to cdrom device has content."""
738010
     try:
738010
@@ -1103,6 +1150,7 @@ def _check_freebsd_cdrom(cdrom_dev):
738010
     return False
738010
 
738010
 
738010
+@azure_ds_telemetry_reporter
738010
 def _get_random_seed(source=PLATFORM_ENTROPY_SOURCE):
738010
     """Return content random seed file if available, otherwise,
738010
        return None."""
738010
@@ -1126,6 +1174,7 @@ def _get_random_seed(source=PLATFORM_ENTROPY_SOURCE):
738010
     return seed
738010
 
738010
 
738010
+@azure_ds_telemetry_reporter
738010
 def list_possible_azure_ds_devs():
738010
     devlist = []
738010
     if util.is_FreeBSD():
738010
@@ -1140,6 +1189,7 @@ def list_possible_azure_ds_devs():
738010
     return devlist
738010
 
738010
 
738010
+@azure_ds_telemetry_reporter
738010
 def load_azure_ds_dir(source_dir):
738010
     ovf_file = os.path.join(source_dir, "ovf-env.xml")
738010
 
738010
@@ -1162,47 +1212,54 @@ def parse_network_config(imds_metadata):
738010
     @param: imds_metadata: Dict of content read from IMDS network service.
738010
     @return: Dictionary containing network version 2 standard configuration.
738010
     """
738010
-    if imds_metadata != sources.UNSET and imds_metadata:
738010
-        netconfig = {'version': 2, 'ethernets': {}}
738010
-        LOG.debug('Azure: generating network configuration from IMDS')
738010
-        network_metadata = imds_metadata['network']
738010
-        for idx, intf in enumerate(network_metadata['interface']):
738010
-            nicname = 'eth{idx}'.format(idx=idx)
738010
-            dev_config = {}
738010
-            for addr4 in intf['ipv4']['ipAddress']:
738010
-                privateIpv4 = addr4['privateIpAddress']
738010
-                if privateIpv4:
738010
-                    if dev_config.get('dhcp4', False):
738010
-                        # Append static address config for nic > 1
738010
-                        netPrefix = intf['ipv4']['subnet'][0].get(
738010
-                            'prefix', '24')
738010
-                        if not dev_config.get('addresses'):
738010
-                            dev_config['addresses'] = []
738010
-                        dev_config['addresses'].append(
738010
-                            '{ip}/{prefix}'.format(
738010
-                                ip=privateIpv4, prefix=netPrefix))
738010
-                    else:
738010
-                        dev_config['dhcp4'] = True
738010
-            for addr6 in intf['ipv6']['ipAddress']:
738010
-                privateIpv6 = addr6['privateIpAddress']
738010
-                if privateIpv6:
738010
-                    dev_config['dhcp6'] = True
738010
-                    break
738010
-            if dev_config:
738010
-                mac = ':'.join(re.findall(r'..', intf['macAddress']))
738010
-                dev_config.update(
738010
-                    {'match': {'macaddress': mac.lower()},
738010
-                     'set-name': nicname})
738010
-                netconfig['ethernets'][nicname] = dev_config
738010
-    else:
738010
-        blacklist = ['mlx4_core']
738010
-        LOG.debug('Azure: generating fallback configuration')
738010
-        # generate a network config, blacklist picking mlx4_core devs
738010
-        netconfig = net.generate_fallback_config(
738010
-            blacklist_drivers=blacklist, config_driver=True)
738010
-    return netconfig
738010
+    with events.ReportEventStack(
738010
+                name="parse_network_config",
738010
+                description="",
738010
+                parent=azure_ds_reporter) as evt:
738010
+        if imds_metadata != sources.UNSET and imds_metadata:
738010
+            netconfig = {'version': 2, 'ethernets': {}}
738010
+            LOG.debug('Azure: generating network configuration from IMDS')
738010
+            network_metadata = imds_metadata['network']
738010
+            for idx, intf in enumerate(network_metadata['interface']):
738010
+                nicname = 'eth{idx}'.format(idx=idx)
738010
+                dev_config = {}
738010
+                for addr4 in intf['ipv4']['ipAddress']:
738010
+                    privateIpv4 = addr4['privateIpAddress']
738010
+                    if privateIpv4:
738010
+                        if dev_config.get('dhcp4', False):
738010
+                            # Append static address config for nic > 1
738010
+                            netPrefix = intf['ipv4']['subnet'][0].get(
738010
+                                'prefix', '24')
738010
+                            if not dev_config.get('addresses'):
738010
+                                dev_config['addresses'] = []
738010
+                            dev_config['addresses'].append(
738010
+                                '{ip}/{prefix}'.format(
738010
+                                    ip=privateIpv4, prefix=netPrefix))
738010
+                        else:
738010
+                            dev_config['dhcp4'] = True
738010
+                for addr6 in intf['ipv6']['ipAddress']:
738010
+                    privateIpv6 = addr6['privateIpAddress']
738010
+                    if privateIpv6:
738010
+                        dev_config['dhcp6'] = True
738010
+                        break
738010
+                if dev_config:
738010
+                    mac = ':'.join(re.findall(r'..', intf['macAddress']))
738010
+                    dev_config.update(
738010
+                        {'match': {'macaddress': mac.lower()},
738010
+                         'set-name': nicname})
738010
+                    netconfig['ethernets'][nicname] = dev_config
738010
+            evt.description = "network config from imds"
738010
+        else:
738010
+            blacklist = ['mlx4_core']
738010
+            LOG.debug('Azure: generating fallback configuration')
738010
+            # generate a network config, blacklist picking mlx4_core devs
738010
+            netconfig = net.generate_fallback_config(
738010
+                blacklist_drivers=blacklist, config_driver=True)
738010
+            evt.description = "network config from fallback"
738010
+        return netconfig
738010
 
738010
 
738010
+@azure_ds_telemetry_reporter
738010
 def get_metadata_from_imds(fallback_nic, retries):
738010
     """Query Azure's network metadata service, returning a dictionary.
738010
 
738010
@@ -1227,6 +1284,7 @@ def get_metadata_from_imds(fallback_nic, retries):
738010
             return util.log_time(**kwargs)
738010
 
738010
 
738010
+@azure_ds_telemetry_reporter
738010
 def _get_metadata_from_imds(retries):
738010
 
738010
     url = IMDS_URL + "instance?api-version=2017-12-01"
738010
@@ -1246,6 +1304,7 @@ def _get_metadata_from_imds(retries):
738010
     return {}
738010
 
738010
 
738010
+@azure_ds_telemetry_reporter
738010
 def maybe_remove_ubuntu_network_config_scripts(paths=None):
738010
     """Remove Azure-specific ubuntu network config for non-primary nics.
738010
 
738010
@@ -1283,14 +1342,20 @@ def maybe_remove_ubuntu_network_config_scripts(paths=None):
738010
 
738010
 
738010
 def _is_platform_viable(seed_dir):
738010
-    """Check platform environment to report if this datasource may run."""
738010
-    asset_tag = util.read_dmi_data('chassis-asset-tag')
738010
-    if asset_tag == AZURE_CHASSIS_ASSET_TAG:
738010
-        return True
738010
-    LOG.debug("Non-Azure DMI asset tag '%s' discovered.", asset_tag)
738010
-    if os.path.exists(os.path.join(seed_dir, 'ovf-env.xml')):
738010
-        return True
738010
-    return False
738010
+    with events.ReportEventStack(
738010
+                name="check-platform-viability",
738010
+                description="found azure asset tag",
738010
+                parent=azure_ds_reporter) as evt:
738010
+
738010
+        """Check platform environment to report if this datasource may run."""
738010
+        asset_tag = util.read_dmi_data('chassis-asset-tag')
738010
+        if asset_tag == AZURE_CHASSIS_ASSET_TAG:
738010
+            return True
738010
+        LOG.debug("Non-Azure DMI asset tag '%s' discovered.", asset_tag)
738010
+        evt.description = "Non-Azure DMI asset tag '%s' discovered.", asset_tag
738010
+        if os.path.exists(os.path.join(seed_dir, 'ovf-env.xml')):
738010
+            return True
738010
+        return False
738010
 
738010
 
738010
 class BrokenAzureDataSource(Exception):
738010
diff --git a/cloudinit/sources/helpers/azure.py b/cloudinit/sources/helpers/azure.py
738010
old mode 100644
738010
new mode 100755
738010
index 2829dd2..d3af05e
738010
--- a/cloudinit/sources/helpers/azure.py
738010
+++ b/cloudinit/sources/helpers/azure.py
738010
@@ -16,10 +16,27 @@ from xml.etree import ElementTree
738010
 
738010
 from cloudinit import url_helper
738010
 from cloudinit import util
738010
+from cloudinit.reporting import events
738010
 
738010
 LOG = logging.getLogger(__name__)
738010
 
738010
 
738010
+azure_ds_reporter = events.ReportEventStack(
738010
+    name="azure-ds",
738010
+    description="initialize reporter for azure ds",
738010
+    reporting_enabled=True)
738010
+
738010
+
738010
+def azure_ds_telemetry_reporter(func):
738010
+    def impl(*args, **kwargs):
738010
+        with events.ReportEventStack(
738010
+                name=func.__name__,
738010
+                description=func.__name__,
738010
+                parent=azure_ds_reporter):
738010
+            return func(*args, **kwargs)
738010
+    return impl
738010
+
738010
+
738010
 @contextmanager
738010
 def cd(newdir):
738010
     prevdir = os.getcwd()
738010
@@ -119,6 +136,7 @@ class OpenSSLManager(object):
738010
     def clean_up(self):
738010
         util.del_dir(self.tmpdir)
738010
 
738010
+    @azure_ds_telemetry_reporter
738010
     def generate_certificate(self):
738010
         LOG.debug('Generating certificate for communication with fabric...')
738010
         if self.certificate is not None:
738010
@@ -139,17 +157,20 @@ class OpenSSLManager(object):
738010
         LOG.debug('New certificate generated.')
738010
 
738010
     @staticmethod
738010
+    @azure_ds_telemetry_reporter
738010
     def _run_x509_action(action, cert):
738010
         cmd = ['openssl', 'x509', '-noout', action]
738010
         result, _ = util.subp(cmd, data=cert)
738010
         return result
738010
 
738010
+    @azure_ds_telemetry_reporter
738010
     def _get_ssh_key_from_cert(self, certificate):
738010
         pub_key = self._run_x509_action('-pubkey', certificate)
738010
         keygen_cmd = ['ssh-keygen', '-i', '-m', 'PKCS8', '-f', '/dev/stdin']
738010
         ssh_key, _ = util.subp(keygen_cmd, data=pub_key)
738010
         return ssh_key
738010
 
738010
+    @azure_ds_telemetry_reporter
738010
     def _get_fingerprint_from_cert(self, certificate):
738010
         """openssl x509 formats fingerprints as so:
738010
         'SHA1 Fingerprint=07:3E:19:D1:4D:1C:79:92:24:C6:A0:FD:8D:DA:\
738010
@@ -163,6 +184,7 @@ class OpenSSLManager(object):
738010
         octets = raw_fp[eq+1:-1].split(':')
738010
         return ''.join(octets)
738010
 
738010
+    @azure_ds_telemetry_reporter
738010
     def _decrypt_certs_from_xml(self, certificates_xml):
738010
         """Decrypt the certificates XML document using the our private key;
738010
            return the list of certs and private keys contained in the doc.
738010
@@ -185,6 +207,7 @@ class OpenSSLManager(object):
738010
                 shell=True, data=b'\n'.join(lines))
738010
         return out
738010
 
738010
+    @azure_ds_telemetry_reporter
738010
     def parse_certificates(self, certificates_xml):
738010
         """Given the Certificates XML document, return a dictionary of
738010
            fingerprints and associated SSH keys derived from the certs."""
738010
@@ -265,11 +288,13 @@ class WALinuxAgentShim(object):
738010
         return socket.inet_ntoa(packed_bytes)
738010
 
738010
     @staticmethod
738010
+    @azure_ds_telemetry_reporter
738010
     def _networkd_get_value_from_leases(leases_d=None):
738010
         return dhcp.networkd_get_option_from_leases(
738010
             'OPTION_245', leases_d=leases_d)
738010
 
738010
     @staticmethod
738010
+    @azure_ds_telemetry_reporter
738010
     def _get_value_from_leases_file(fallback_lease_file):
738010
         leases = []
738010
         content = util.load_file(fallback_lease_file)
738010
@@ -287,6 +312,7 @@ class WALinuxAgentShim(object):
738010
             return leases[-1]
738010
 
738010
     @staticmethod
738010
+    @azure_ds_telemetry_reporter
738010
     def _load_dhclient_json():
738010
         dhcp_options = {}
738010
         hooks_dir = WALinuxAgentShim._get_hooks_dir()
738010
@@ -305,6 +331,7 @@ class WALinuxAgentShim(object):
738010
         return dhcp_options
738010
 
738010
     @staticmethod
738010
+    @azure_ds_telemetry_reporter
738010
     def _get_value_from_dhcpoptions(dhcp_options):
738010
         if dhcp_options is None:
738010
             return None
738010
@@ -318,6 +345,7 @@ class WALinuxAgentShim(object):
738010
         return _value
738010
 
738010
     @staticmethod
738010
+    @azure_ds_telemetry_reporter
738010
     def find_endpoint(fallback_lease_file=None, dhcp245=None):
738010
         value = None
738010
         if dhcp245 is not None:
738010
@@ -352,6 +380,7 @@ class WALinuxAgentShim(object):
738010
         LOG.debug('Azure endpoint found at %s', endpoint_ip_address)
738010
         return endpoint_ip_address
738010
 
738010
+    @azure_ds_telemetry_reporter
738010
     def register_with_azure_and_fetch_data(self, pubkey_info=None):
738010
         if self.openssl_manager is None:
738010
             self.openssl_manager = OpenSSLManager()
738010
@@ -404,6 +433,7 @@ class WALinuxAgentShim(object):
738010
 
738010
         return keys
738010
 
738010
+    @azure_ds_telemetry_reporter
738010
     def _report_ready(self, goal_state, http_client):
738010
         LOG.debug('Reporting ready to Azure fabric.')
738010
         document = self.REPORT_READY_XML_TEMPLATE.format(
738010
@@ -419,6 +449,7 @@ class WALinuxAgentShim(object):
738010
         LOG.info('Reported ready to Azure fabric.')
738010
 
738010
 
738010
+@azure_ds_telemetry_reporter
738010
 def get_metadata_from_fabric(fallback_lease_file=None, dhcp_opts=None,
738010
                              pubkey_info=None):
738010
     shim = WALinuxAgentShim(fallback_lease_file=fallback_lease_file,
738010
-- 
738010
1.8.3.1
738010