Blame SOURCES/ci-DatasourceAzure-add-additional-logging-for-azure-dat.patch

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