summaryrefslogtreecommitdiff
path: root/cloudinit/sources/DataSourceAzure.py
blob: fa3e0a2b9c71d9dfada23846d6a1b87b4712bbcd (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
# Copyright (C) 2013 Canonical Ltd.
#
# Author: Scott Moser <scott.moser@canonical.com>
#
# This file is part of cloud-init. See LICENSE file for license information.

import base64
import contextlib
import crypt
from functools import partial
import os
import os.path
import re
from time import time
from xml.dom import minidom
import xml.etree.ElementTree as ET

from cloudinit import dmi
from cloudinit import log as logging
from cloudinit import net
from cloudinit.event import EventType
from cloudinit.net import device_driver
from cloudinit.net.dhcp import EphemeralDHCPv4
from cloudinit import sources
from cloudinit.sources.helpers import netlink
from cloudinit import subp
from cloudinit.url_helper import UrlError, readurl, retry_on_url_exc
from cloudinit import util
from cloudinit.reporting import events

from cloudinit.sources.helpers.azure import (
    azure_ds_reporter,
    azure_ds_telemetry_reporter,
    get_metadata_from_fabric,
    get_boot_telemetry,
    get_system_info,
    report_diagnostic_event,
    EphemeralDHCPv4WithReporting,
    is_byte_swapped,
    dhcp_log_cb,
    push_log_to_kvp)

LOG = logging.getLogger(__name__)

DS_NAME = 'Azure'
DEFAULT_METADATA = {"instance-id": "iid-AZURE-NODE"}
AGENT_START = ['service', 'walinuxagent', 'start']
AGENT_START_BUILTIN = "__builtin__"
BOUNCE_COMMAND_IFUP = [
    'sh', '-xc',
    "i=$interface; x=0; ifdown $i || x=$?; ifup $i || x=$?; exit $x"
]
BOUNCE_COMMAND_FREEBSD = [
    'sh', '-xc',
    ("i=$interface; x=0; ifconfig down $i || x=$?; "
     "ifconfig up $i || x=$?; exit $x")
]

# azure systems will always have a resource disk, and 66-azure-ephemeral.rules
# ensures that it gets linked to this path.
RESOURCE_DISK_PATH = '/dev/disk/cloud/azure_resource'
DEFAULT_PRIMARY_NIC = 'eth0'
LEASE_FILE = '/var/lib/dhcp/dhclient.eth0.leases'
DEFAULT_FS = 'ext4'
# DMI chassis-asset-tag is set static for all azure instances
AZURE_CHASSIS_ASSET_TAG = '7783-7084-3265-9085-8269-3286-77'
REPROVISION_MARKER_FILE = "/var/lib/cloud/data/poll_imds"
REPORTED_READY_MARKER_FILE = "/var/lib/cloud/data/reported_ready"
AGENT_SEED_DIR = '/var/lib/waagent'

# In the event where the IMDS primary server is not
# available, it takes 1s to fallback to the secondary one
IMDS_TIMEOUT_IN_SECONDS = 2
IMDS_URL = "http://169.254.169.254/metadata/"

PLATFORM_ENTROPY_SOURCE = "/sys/firmware/acpi/tables/OEM0"

# List of static scripts and network config artifacts created by
# stock ubuntu suported images.
UBUNTU_EXTENDED_NETWORK_SCRIPTS = [
    '/etc/netplan/90-hotplug-azure.yaml',
    '/usr/local/sbin/ephemeral_eth.sh',
    '/etc/udev/rules.d/10-net-device-added.rules',
    '/run/network/interfaces.ephemeral.d',
]

# This list is used to blacklist devices that will be considered
# for renaming or fallback interfaces.
#
# On Azure network devices using these drivers are automatically
# configured by the platform and should not be configured by
# cloud-init's network configuration.
#
# Note:
# Azure Dv4 and Ev4 series VMs always have mlx5 hardware.
# https://docs.microsoft.com/en-us/azure/virtual-machines/dv4-dsv4-series
# https://docs.microsoft.com/en-us/azure/virtual-machines/ev4-esv4-series
# Earlier D and E series VMs (such as Dv2, Dv3, and Ev3 series VMs)
# can have either mlx4 or mlx5 hardware, with the older series VMs
# having a higher chance of coming with mlx4 hardware.
# https://docs.microsoft.com/en-us/azure/virtual-machines/dv2-dsv2-series
# https://docs.microsoft.com/en-us/azure/virtual-machines/dv3-dsv3-series
# https://docs.microsoft.com/en-us/azure/virtual-machines/ev3-esv3-series
BLACKLIST_DRIVERS = ['mlx4_core', 'mlx5_core']


def find_storvscid_from_sysctl_pnpinfo(sysctl_out, deviceid):
    # extract the 'X' from dev.storvsc.X. if deviceid matches
    """
    dev.storvsc.1.%pnpinfo:
        classid=32412632-86cb-44a2-9b5c-50d1417354f5
        deviceid=00000000-0001-8899-0000-000000000000
    """
    for line in sysctl_out.splitlines():
        if re.search(r"pnpinfo", line):
            fields = line.split()
            if len(fields) >= 3:
                columns = fields[2].split('=')
                if (len(columns) >= 2 and
                        columns[0] == "deviceid" and
                        columns[1].startswith(deviceid)):
                    comps = fields[0].split('.')
                    return comps[2]
    return None


def find_busdev_from_disk(camcontrol_out, disk_drv):
    # find the scbusX from 'camcontrol devlist -b' output
    # if disk_drv matches the specified disk driver, i.e. blkvsc1
    """
    scbus0 on ata0 bus 0
    scbus1 on ata1 bus 0
    scbus2 on blkvsc0 bus 0
    scbus3 on blkvsc1 bus 0
    scbus4 on storvsc2 bus 0
    scbus5 on storvsc3 bus 0
    scbus-1 on xpt0 bus 0
    """
    for line in camcontrol_out.splitlines():
        if re.search(disk_drv, line):
            items = line.split()
            return items[0]
    return None


def find_dev_from_busdev(camcontrol_out, busdev):
    # find the daX from 'camcontrol devlist' output
    # if busdev matches the specified value, i.e. 'scbus2'
    """
    <Msft Virtual CD/ROM 1.0>          at scbus1 target 0 lun 0 (cd0,pass0)
    <Msft Virtual Disk 1.0>            at scbus2 target 0 lun 0 (da0,pass1)
    <Msft Virtual Disk 1.0>            at scbus3 target 1 lun 0 (da1,pass2)
    """
    for line in camcontrol_out.splitlines():
        if re.search(busdev, line):
            items = line.split('(')
            if len(items) == 2:
                dev_pass = items[1].split(',')
                return dev_pass[0]
    return None


def execute_or_debug(cmd, fail_ret=None):
    try:
        return subp.subp(cmd)[0]
    except subp.ProcessExecutionError:
        LOG.debug("Failed to execute: %s", ' '.join(cmd))
        return fail_ret


def get_dev_storvsc_sysctl():
    return execute_or_debug(["sysctl", "dev.storvsc"], fail_ret="")


def get_camcontrol_dev_bus():
    return execute_or_debug(['camcontrol', 'devlist', '-b'])


def get_camcontrol_dev():
    return execute_or_debug(['camcontrol', 'devlist'])


def get_resource_disk_on_freebsd(port_id):
    g0 = "00000000"
    if port_id > 1:
        g0 = "00000001"
        port_id = port_id - 2
    g1 = "000" + str(port_id)
    g0g1 = "{0}-{1}".format(g0, g1)

    # search 'X' from
    #  'dev.storvsc.X.%pnpinfo:
    #      classid=32412632-86cb-44a2-9b5c-50d1417354f5
    #      deviceid=00000000-0001-8899-0000-000000000000'
    sysctl_out = get_dev_storvsc_sysctl()

    storvscid = find_storvscid_from_sysctl_pnpinfo(sysctl_out, g0g1)
    if not storvscid:
        LOG.debug("Fail to find storvsc id from sysctl")
        return None

    camcontrol_b_out = get_camcontrol_dev_bus()
    camcontrol_out = get_camcontrol_dev()
    # try to find /dev/XX from 'blkvsc' device
    blkvsc = "blkvsc{0}".format(storvscid)
    scbusx = find_busdev_from_disk(camcontrol_b_out, blkvsc)
    if scbusx:
        devname = find_dev_from_busdev(camcontrol_out, scbusx)
        if devname is None:
            LOG.debug("Fail to find /dev/daX")
            return None
        return devname
    # try to find /dev/XX from 'storvsc' device
    storvsc = "storvsc{0}".format(storvscid)
    scbusx = find_busdev_from_disk(camcontrol_b_out, storvsc)
    if scbusx:
        devname = find_dev_from_busdev(camcontrol_out, scbusx)
        if devname is None:
            LOG.debug("Fail to find /dev/daX")
            return None
        return devname
    return None


# update the FreeBSD specific information
if util.is_FreeBSD():
    DEFAULT_PRIMARY_NIC = 'hn0'
    LEASE_FILE = '/var/db/dhclient.leases.hn0'
    DEFAULT_FS = 'freebsd-ufs'
    res_disk = get_resource_disk_on_freebsd(1)
    if res_disk is not None:
        LOG.debug("resource disk is not None")
        RESOURCE_DISK_PATH = "/dev/" + res_disk
    else:
        LOG.debug("resource disk is None")
    # TODO Find where platform entropy data is surfaced
    PLATFORM_ENTROPY_SOURCE = None

BUILTIN_DS_CONFIG = {
    'agent_command': AGENT_START_BUILTIN,
    'data_dir': AGENT_SEED_DIR,
    'set_hostname': True,
    'hostname_bounce': {
        'interface': DEFAULT_PRIMARY_NIC,
        'policy': True,
        'command': 'builtin',
        'hostname_command': 'hostname',
    },
    'disk_aliases': {'ephemeral0': RESOURCE_DISK_PATH},
    'dhclient_lease_file': LEASE_FILE,
    'apply_network_config': True,  # Use IMDS published network configuration
}
# RELEASE_BLOCKER: Xenial and earlier apply_network_config default is False

BUILTIN_CLOUD_CONFIG = {
    'disk_setup': {
        'ephemeral0': {'table_type': 'gpt',
                       'layout': [100],
                       'overwrite': True},
    },
    'fs_setup': [{'filesystem': DEFAULT_FS,
                  'device': 'ephemeral0.1'}],
}

DS_CFG_PATH = ['datasource', DS_NAME]
DS_CFG_KEY_PRESERVE_NTFS = 'never_destroy_ntfs'
DEF_EPHEMERAL_LABEL = 'Temporary Storage'

# The redacted password fails to meet password complexity requirements
# so we can safely use this to mask/redact the password in the ovf-env.xml
DEF_PASSWD_REDACTION = 'REDACTED'


def get_hostname(hostname_command='hostname'):
    if not isinstance(hostname_command, (list, tuple)):
        hostname_command = (hostname_command,)
    return subp.subp(hostname_command, capture=True)[0].strip()


def set_hostname(hostname, hostname_command='hostname'):
    subp.subp([hostname_command, hostname])


@azure_ds_telemetry_reporter
@contextlib.contextmanager
def temporary_hostname(temp_hostname, cfg, hostname_command='hostname'):
    """
    Set a temporary hostname, restoring the previous hostname on exit.

    Will have the value of the previous hostname when used as a context
    manager, or None if the hostname was not changed.
    """
    policy = cfg['hostname_bounce']['policy']
    previous_hostname = get_hostname(hostname_command)
    if (not util.is_true(cfg.get('set_hostname')) or
       util.is_false(policy) or
       (previous_hostname == temp_hostname and policy != 'force')):
        yield None
        return
    try:
        set_hostname(temp_hostname, hostname_command)
    except Exception as e:
        report_diagnostic_event(
            'Failed setting temporary hostname: %s' % e,
            logger_func=LOG.warning)
        yield None
        return
    try:
        yield previous_hostname
    finally:
        set_hostname(previous_hostname, hostname_command)


class DataSourceAzure(sources.DataSource):

    dsname = 'Azure'
    _negotiated = False
    _metadata_imds = sources.UNSET

    def __init__(self, sys_cfg, distro, paths):
        sources.DataSource.__init__(self, sys_cfg, distro, paths)
        self.seed_dir = os.path.join(paths.seed_dir, 'azure')
        self.cfg = {}
        self.seed = None
        self.ds_cfg = util.mergemanydict([
            util.get_cfg_by_path(sys_cfg, DS_CFG_PATH, {}),
            BUILTIN_DS_CONFIG])
        self.dhclient_lease_file = self.ds_cfg.get('dhclient_lease_file')
        self._network_config = None
        # Regenerate network config new_instance boot and every boot
        self.update_events['network'].add(EventType.BOOT)
        self._ephemeral_dhcp_ctx = None

    def __str__(self):
        root = sources.DataSource.__str__(self)
        return "%s [seed=%s]" % (root, self.seed)

    @azure_ds_telemetry_reporter
    def bounce_network_with_azure_hostname(self):
        # When using cloud-init to provision, we have to set the hostname from
        # the metadata and "bounce" the network to force DDNS to update via
        # dhclient
        azure_hostname = self.metadata.get('local-hostname')
        LOG.debug("Hostname in metadata is %s", azure_hostname)
        hostname_command = self.ds_cfg['hostname_bounce']['hostname_command']

        with temporary_hostname(azure_hostname, self.ds_cfg,
                                hostname_command=hostname_command) \
                as previous_hn:
            if (previous_hn is not None and
                    util.is_true(self.ds_cfg.get('set_hostname'))):
                cfg = self.ds_cfg['hostname_bounce']

                # "Bouncing" the network
                try:
                    return perform_hostname_bounce(hostname=azure_hostname,
                                                   cfg=cfg,
                                                   prev_hostname=previous_hn)
                except Exception as e:
                    report_diagnostic_event(
                        "Failed publishing hostname: %s" % e,
                        logger_func=LOG.warning)
                    util.logexc(LOG, "handling set_hostname failed")
        return False

    @azure_ds_telemetry_reporter
    def get_metadata_from_agent(self):
        temp_hostname = self.metadata.get('local-hostname')
        agent_cmd = self.ds_cfg['agent_command']
        LOG.debug("Getting metadata via agent.  hostname=%s cmd=%s",
                  temp_hostname, agent_cmd)

        self.bounce_network_with_azure_hostname()

        try:
            invoke_agent(agent_cmd)
        except subp.ProcessExecutionError:
            # claim the datasource even if the command failed
            util.logexc(LOG, "agent command '%s' failed.",
                        self.ds_cfg['agent_command'])

        ddir = self.ds_cfg['data_dir']

        fp_files = []
        key_value = None
        for pk in self.cfg.get('_pubkeys', []):
            if pk.get('value', None):
                key_value = pk['value']
                LOG.debug("SSH authentication: using value from fabric")
            else:
                bname = str(pk['fingerprint'] + ".crt")
                fp_files += [os.path.join(ddir, bname)]
                LOG.debug("SSH authentication: "
                          "using fingerprint from fabric")

        with events.ReportEventStack(
                name="waiting-for-ssh-public-key",
                description="wait for agents to retrieve SSH keys",
                parent=azure_ds_reporter):
            # wait very long for public SSH keys to arrive
            # https://bugs.launchpad.net/cloud-init/+bug/1717611
            missing = util.log_time(logfunc=LOG.debug,
                                    msg="waiting for SSH public key files",
                                    func=util.wait_for_files,
                                    args=(fp_files, 900))
            if len(missing):
                LOG.warning("Did not find files, but going on: %s", missing)

        metadata = {}
        metadata['public-keys'] = key_value or pubkeys_from_crt_files(fp_files)
        return metadata

    def _get_subplatform(self):
        """Return the subplatform metadata source details."""
        if self.seed.startswith('/dev'):
            subplatform_type = 'config-disk'
        else:
            subplatform_type = 'seed-dir'
        return '%s (%s)' % (subplatform_type, self.seed)

    @azure_ds_telemetry_reporter
    def crawl_metadata(self):
        """Walk all instance metadata sources returning a dict on success.

        @return: A dictionary of any metadata content for this instance.
        @raise: InvalidMetaDataException when the expected metadata service is
            unavailable, broken or disabled.
        """
        crawled_data = {}
        # azure removes/ejects the cdrom containing the ovf-env.xml
        # file on reboot.  So, in order to successfully reboot we
        # need to look in the datadir and consider that valid
        ddir = self.ds_cfg['data_dir']

        candidates = [self.seed_dir]
        if os.path.isfile(REPROVISION_MARKER_FILE):
            candidates.insert(0, "IMDS")
        candidates.extend(list_possible_azure_ds_devs())
        if ddir:
            candidates.append(ddir)

        found = None
        reprovision = False
        for cdev in candidates:
            try:
                if cdev == "IMDS":
                    ret = None
                    reprovision = True
                elif cdev.startswith("/dev/"):
                    if util.is_FreeBSD():
                        ret = util.mount_cb(cdev, load_azure_ds_dir,
                                            mtype="udf")
                    else:
                        ret = util.mount_cb(cdev, load_azure_ds_dir)
                else:
                    ret = load_azure_ds_dir(cdev)

            except NonAzureDataSource:
                report_diagnostic_event(
                    "Did not find Azure data source in %s" % cdev,
                    logger_func=LOG.debug)
                continue
            except BrokenAzureDataSource as exc:
                msg = 'BrokenAzureDataSource: %s' % exc
                report_diagnostic_event(msg, logger_func=LOG.error)
                raise sources.InvalidMetaDataException(msg)
            except util.MountFailedError:
                report_diagnostic_event(
                    '%s was not mountable' % cdev, logger_func=LOG.warning)
                continue

            perform_reprovision = reprovision or self._should_reprovision(ret)
            if perform_reprovision:
                if util.is_FreeBSD():
                    msg = "Free BSD is not supported for PPS VMs"
                    report_diagnostic_event(msg, logger_func=LOG.error)
                    raise sources.InvalidMetaDataException(msg)
                ret = self._reprovision()
            imds_md = get_metadata_from_imds(
                self.fallback_interface, retries=10)
            (md, userdata_raw, cfg, files) = ret
            self.seed = cdev
            crawled_data.update({
                'cfg': cfg,
                'files': files,
                'metadata': util.mergemanydict(
                    [md, {'imds': imds_md}]),
                'userdata_raw': userdata_raw})
            found = cdev

            report_diagnostic_event(
                'found datasource in %s' % cdev, logger_func=LOG.debug)
            break

        if not found:
            msg = 'No Azure metadata found'
            report_diagnostic_event(msg, logger_func=LOG.error)
            raise sources.InvalidMetaDataException(msg)

        if found == ddir:
            report_diagnostic_event(
                "using files cached in %s" % ddir, logger_func=LOG.debug)

        seed = _get_random_seed()
        if seed:
            crawled_data['metadata']['random_seed'] = seed
        crawled_data['metadata']['instance-id'] = self._iid()

        if perform_reprovision:
            LOG.info("Reporting ready to Azure after getting ReprovisionData")
            use_cached_ephemeral = (net.is_up(self.fallback_interface) and
                                    getattr(self, '_ephemeral_dhcp_ctx', None))
            if use_cached_ephemeral:
                self._report_ready(lease=self._ephemeral_dhcp_ctx.lease)
                self._ephemeral_dhcp_ctx.clean_network()  # Teardown ephemeral
            else:
                try:
                    with EphemeralDHCPv4WithReporting(
                            azure_ds_reporter) as lease:
                        self._report_ready(lease=lease)
                except Exception as e:
                    report_diagnostic_event(
                        "exception while reporting ready: %s" % e,
                        logger_func=LOG.error)
                    raise
        return crawled_data

    def _is_platform_viable(self):
        """Check platform environment to report if this datasource may run."""
        return _is_platform_viable(self.seed_dir)

    def clear_cached_attrs(self, attr_defaults=()):
        """Reset any cached class attributes to defaults."""
        super(DataSourceAzure, self).clear_cached_attrs(attr_defaults)
        self._metadata_imds = sources.UNSET

    @azure_ds_telemetry_reporter
    def _get_data(self):
        """Crawl and process datasource metadata caching metadata as attrs.

        @return: True on success, False on error, invalid or disabled
            datasource.
        """
        if not self._is_platform_viable():
            return False
        try:
            get_boot_telemetry()
        except Exception as e:
            LOG.warning("Failed to get boot telemetry: %s", e)

        try:
            get_system_info()
        except Exception as e:
            LOG.warning("Failed to get system information: %s", e)

        self.distro.networking.blacklist_drivers = BLACKLIST_DRIVERS

        try:
            crawled_data = util.log_time(
                logfunc=LOG.debug, msg='Crawl of metadata service',
                func=self.crawl_metadata
            )
        except sources.InvalidMetaDataException as e:
            LOG.warning('Could not crawl Azure metadata: %s', e)
            return False
        if (self.distro and self.distro.name == 'ubuntu' and
                self.ds_cfg.get('apply_network_config')):
            maybe_remove_ubuntu_network_config_scripts()

        # Process crawled data and augment with various config defaults
        self.cfg = util.mergemanydict(
            [crawled_data['cfg'], BUILTIN_CLOUD_CONFIG])
        self._metadata_imds = crawled_data['metadata']['imds']
        self.metadata = util.mergemanydict(
            [crawled_data['metadata'], DEFAULT_METADATA])
        self.userdata_raw = crawled_data['userdata_raw']

        user_ds_cfg = util.get_cfg_by_path(self.cfg, DS_CFG_PATH, {})
        self.ds_cfg = util.mergemanydict([user_ds_cfg, self.ds_cfg])

        # walinux agent writes files world readable, but expects
        # the directory to be protected.
        write_files(
            self.ds_cfg['data_dir'], crawled_data['files'], dirmode=0o700)
        return True

    def device_name_to_device(self, name):
        return self.ds_cfg['disk_aliases'].get(name)

    @azure_ds_telemetry_reporter
    def get_public_ssh_keys(self):
        """
        Try to get the ssh keys from IMDS first, and if that fails
        (i.e. IMDS is unavailable) then fallback to getting the ssh
        keys from OVF.

        The benefit to getting keys from IMDS is a large performance
        advantage, so this is a strong preference. But we must keep
        OVF as a second option for environments that don't have IMDS.
        """
        LOG.debug('Retrieving public SSH keys')
        ssh_keys = []
        try:
            ssh_keys = [
                public_key['keyData']
                for public_key
                in self.metadata['imds']['compute']['publicKeys']
            ]
            LOG.debug('Retrieved SSH keys from IMDS')
        except KeyError:
            log_msg = 'Unable to get keys from IMDS, falling back to OVF'
            LOG.debug(log_msg)
            report_diagnostic_event(log_msg, logger_func=LOG.debug)
            try:
                ssh_keys = self.metadata['public-keys']
                LOG.debug('Retrieved keys from OVF')
            except KeyError:
                log_msg = 'No keys available from OVF'
                LOG.debug(log_msg)
                report_diagnostic_event(log_msg, logger_func=LOG.debug)

        return ssh_keys

    def get_config_obj(self):
        return self.cfg

    def check_instance_id(self, sys_cfg):
        # quickly (local check only) if self.instance_id is still valid
        return sources.instance_id_matches_system_uuid(self.get_instance_id())

    def _iid(self, previous=None):
        prev_iid_path = os.path.join(
            self.paths.get_cpath('data'), 'instance-id')
        iid = dmi.read_dmi_data('system-uuid')
        if os.path.exists(prev_iid_path):
            previous = util.load_file(prev_iid_path).strip()
            if is_byte_swapped(previous, iid):
                return previous
        return iid

    @azure_ds_telemetry_reporter
    def setup(self, is_new_instance):
        if self._negotiated is False:
            LOG.debug("negotiating for %s (new_instance=%s)",
                      self.get_instance_id(), is_new_instance)
            fabric_data = self._negotiate()
            LOG.debug("negotiating returned %s", fabric_data)
            if fabric_data:
                self.metadata.update(fabric_data)
            self._negotiated = True
        else:
            LOG.debug("negotiating already done for %s",
                      self.get_instance_id())

    def _poll_imds(self):
        """Poll IMDS for the new provisioning data until we get a valid
        response. Then return the returned JSON object."""
        url = IMDS_URL + "reprovisiondata?api-version=2017-04-02"
        headers = {"Metadata": "true"}
        nl_sock = None
        report_ready = bool(not os.path.isfile(REPORTED_READY_MARKER_FILE))
        self.imds_logging_threshold = 1
        self.imds_poll_counter = 1
        dhcp_attempts = 0
        vnet_switched = False
        return_val = None

        def exc_cb(msg, exception):
            if isinstance(exception, UrlError):
                if exception.code in (404, 410):
                    if self.imds_poll_counter == self.imds_logging_threshold:
                        # Reducing the logging frequency as we are polling IMDS
                        self.imds_logging_threshold *= 2
                        LOG.debug("Backing off logging threshold for the same "
                                  "exception to %d",
                                  self.imds_logging_threshold)
                        report_diagnostic_event("poll IMDS with %s failed. "
                                                "Exception: %s and code: %s" %
                                                (msg, exception.cause,
                                                 exception.code),
                                                logger_func=LOG.debug)
                    self.imds_poll_counter += 1
                    return True
                else:
                    # If we get an exception while trying to call IMDS, we call
                    # DHCP and setup the ephemeral network to acquire a new IP.
                    report_diagnostic_event("poll IMDS with %s failed. "
                                            "Exception: %s and code: %s" %
                                            (msg, exception.cause,
                                             exception.code),
                                            logger_func=LOG.warning)
                    return False

            report_diagnostic_event(
                "poll IMDS failed with an "
                "unexpected exception: %s" % exception,
                logger_func=LOG.warning)
            return False

        LOG.debug("Wait for vnetswitch to happen")
        while True:
            try:
                # Save our EphemeralDHCPv4 context to avoid repeated dhcp
                with events.ReportEventStack(
                        name="obtain-dhcp-lease",
                        description="obtain dhcp lease",
                        parent=azure_ds_reporter):
                    self._ephemeral_dhcp_ctx = EphemeralDHCPv4(
                        dhcp_log_func=dhcp_log_cb)
                    lease = self._ephemeral_dhcp_ctx.obtain_lease()

                if vnet_switched:
                    dhcp_attempts += 1
                if report_ready:
                    try:
                        nl_sock = netlink.create_bound_netlink_socket()
                    except netlink.NetlinkCreateSocketError as e:
                        report_diagnostic_event(
                            'Failed to create bound netlink socket: %s' % e,
                            logger_func=LOG.warning)
                        self._ephemeral_dhcp_ctx.clean_network()
                        break

                    report_ready_succeeded = self._report_ready(lease=lease)
                    if not report_ready_succeeded:
                        msg = ('Failed reporting ready while in '
                               'the preprovisioning pool.')
                        report_diagnostic_event(msg, logger_func=LOG.error)
                        self._ephemeral_dhcp_ctx.clean_network()
                        raise sources.InvalidMetaDataException(msg)

                    path = REPORTED_READY_MARKER_FILE
                    LOG.info(
                        "Creating a marker file to report ready: %s", path)
                    util.write_file(path, "{pid}: {time}\n".format(
                        pid=os.getpid(), time=time()))
                    report_diagnostic_event(
                        'Successfully created reported ready marker file '
                        'while in the preprovisioning pool.',
                        logger_func=LOG.debug)
                    report_ready = False

                    with events.ReportEventStack(
                            name="wait-for-media-disconnect-connect",
                            description="wait for vnet switch",
                            parent=azure_ds_reporter):
                        try:
                            netlink.wait_for_media_disconnect_connect(
                                nl_sock, lease['interface'])
                        except AssertionError as e:
                            report_diagnostic_event(
                                'Error while waiting for vnet switch: %s' % e,
                                logger_func=LOG.error)
                            break

                    vnet_switched = True
                    self._ephemeral_dhcp_ctx.clean_network()
                else:
                    with events.ReportEventStack(
                            name="get-reprovision-data-from-imds",
                            description="get reprovision data from imds",
                            parent=azure_ds_reporter):
                        return_val = readurl(url,
                                             timeout=IMDS_TIMEOUT_IN_SECONDS,
                                             headers=headers,
                                             exception_cb=exc_cb,
                                             infinite=True,
                                             log_req_resp=False).contents
                    break
            except UrlError:
                # Teardown our EphemeralDHCPv4 context on failure as we retry
                self._ephemeral_dhcp_ctx.clean_network()
            finally:
                if nl_sock:
                    nl_sock.close()

        if vnet_switched:
            report_diagnostic_event("attempted dhcp %d times after reuse" %
                                    dhcp_attempts,
                                    logger_func=LOG.debug)
            report_diagnostic_event("polled imds %d times after reuse" %
                                    self.imds_poll_counter,
                                    logger_func=LOG.debug)

        return return_val

    @azure_ds_telemetry_reporter
    def _report_ready(self, lease: dict) -> bool:
        """Tells the fabric provisioning has completed.

        @param lease: dhcp lease to use for sending the ready signal.
        @return: The success status of sending the ready signal.
        """
        try:
            get_metadata_from_fabric(None, lease['unknown-245'])
            return True
        except Exception as e:
            report_diagnostic_event(
                "Error communicating with Azure fabric; You may experience "
                "connectivity issues: %s" % e, logger_func=LOG.warning)
            return False

    def _should_reprovision(self, ret):
        """Whether or not we should poll IMDS for reprovisioning data.
        Also sets a marker file to poll IMDS.

        The marker file is used for the following scenario: the VM boots into
        this polling loop, which we expect to be proceeding infinitely until
        the VM is picked. If for whatever reason the platform moves us to a
        new host (for instance a hardware issue), we need to keep polling.
        However, since the VM reports ready to the Fabric, we will not attach
        the ISO, thus cloud-init needs to have a way of knowing that it should
        jump back into the polling loop in order to retrieve the ovf_env."""
        if not ret:
            return False
        (_md, _userdata_raw, cfg, _files) = ret
        path = REPROVISION_MARKER_FILE
        if (cfg.get('PreprovisionedVm') is True or
                os.path.isfile(path)):
            if not os.path.isfile(path):
                LOG.info("Creating a marker file to poll imds: %s",
                         path)
                util.write_file(path, "{pid}: {time}\n".format(
                    pid=os.getpid(), time=time()))
            return True
        return False

    def _reprovision(self):
        """Initiate the reprovisioning workflow."""
        contents = self._poll_imds()
        with events.ReportEventStack(
                name="reprovisioning-read-azure-ovf",
                description="read azure ovf during reprovisioning",
                parent=azure_ds_reporter):
            md, ud, cfg = read_azure_ovf(contents)
            return (md, ud, cfg, {'ovf-env.xml': contents})

    @azure_ds_telemetry_reporter
    def _negotiate(self):
        """Negotiate with fabric and return data from it.

           On success, returns a dictionary including 'public_keys'.
           On failure, returns False.
        """

        if self.ds_cfg['agent_command'] == AGENT_START_BUILTIN:
            self.bounce_network_with_azure_hostname()

            pubkey_info = None
            try:
                public_keys = self.metadata['imds']['compute']['publicKeys']
                LOG.debug(
                    'Successfully retrieved %s key(s) from IMDS',
                    len(public_keys)
                    if public_keys is not None
                    else 0
                )
            except KeyError:
                LOG.debug(
                    'Unable to retrieve SSH keys from IMDS during '
                    'negotiation, falling back to OVF'
                )
                pubkey_info = self.cfg.get('_pubkeys', None)

            metadata_func = partial(get_metadata_from_fabric,
                                    fallback_lease_file=self.
                                    dhclient_lease_file,
                                    pubkey_info=pubkey_info)
        else:
            metadata_func = self.get_metadata_from_agent

        LOG.debug("negotiating with fabric via agent command %s",
                  self.ds_cfg['agent_command'])
        try:
            fabric_data = metadata_func()
        except Exception as e:
            report_diagnostic_event(
                "Error communicating with Azure fabric; You may experience "
                "connectivity issues: %s" % e, logger_func=LOG.warning)
            return False

        util.del_file(REPORTED_READY_MARKER_FILE)
        util.del_file(REPROVISION_MARKER_FILE)
        return fabric_data

    @azure_ds_telemetry_reporter
    def activate(self, cfg, is_new_instance):
        try:
            address_ephemeral_resize(is_new_instance=is_new_instance,
                                     preserve_ntfs=self.ds_cfg.get(
                                         DS_CFG_KEY_PRESERVE_NTFS, False))
        finally:
            push_log_to_kvp(self.sys_cfg['def_log_file'])
        return

    @property
    def availability_zone(self):
        return self.metadata.get(
            'imds', {}).get('compute', {}).get('platformFaultDomain')

    @property
    def network_config(self):
        """Generate a network config like net.generate_fallback_network() with
           the following exceptions.

           1. Probe the drivers of the net-devices present and inject them in
              the network configuration under params: driver: <driver> value
           2. Generate a fallback network config that does not include any of
              the blacklisted devices.
        """
        if not self._network_config or self._network_config == sources.UNSET:
            if self.ds_cfg.get('apply_network_config'):
                nc_src = self._metadata_imds
            else:
                nc_src = None
            self._network_config = parse_network_config(nc_src)
        return self._network_config

    @property
    def region(self):
        return self.metadata.get('imds', {}).get('compute', {}).get('location')


def _partitions_on_device(devpath, maxnum=16):
    # return a list of tuples (ptnum, path) for each part on devpath
    for suff in ("-part", "p", ""):
        found = []
        for pnum in range(1, maxnum):
            ppath = devpath + suff + str(pnum)
            if os.path.exists(ppath):
                found.append((pnum, os.path.realpath(ppath)))
        if found:
            return found
    return []


@azure_ds_telemetry_reporter
def _has_ntfs_filesystem(devpath):
    ntfs_devices = util.find_devs_with("TYPE=ntfs", no_cache=True)
    LOG.debug('ntfs_devices found = %s', ntfs_devices)
    return os.path.realpath(devpath) in ntfs_devices


@azure_ds_telemetry_reporter
def can_dev_be_reformatted(devpath, preserve_ntfs):
    """Determine if the ephemeral drive at devpath should be reformatted.

    A fresh ephemeral disk is formatted by Azure and will:
      a.) have a partition table (dos or gpt)
      b.) have 1 partition that is ntfs formatted, or
          have 2 partitions with the second partition ntfs formatted.
          (larger instances with >2TB ephemeral disk have gpt, and will
           have a microsoft reserved partition as part 1.  LP: #1686514)
      c.) the ntfs partition will have no files other than possibly
          'dataloss_warning_readme.txt'

    User can indicate that NTFS should never be destroyed by setting
    DS_CFG_KEY_PRESERVE_NTFS in dscfg.
    If data is found on NTFS, user is warned to set DS_CFG_KEY_PRESERVE_NTFS
    to make sure cloud-init does not accidentally wipe their data.
    If cloud-init cannot mount the disk to check for data, destruction
    will be allowed, unless the dscfg key is set."""
    if preserve_ntfs:
        msg = ('config says to never destroy NTFS (%s.%s), skipping checks' %
               (".".join(DS_CFG_PATH), DS_CFG_KEY_PRESERVE_NTFS))
        return False, msg

    if not os.path.exists(devpath):
        return False, 'device %s does not exist' % devpath

    LOG.debug('Resolving realpath of %s -> %s', devpath,
              os.path.realpath(devpath))

    # devpath of /dev/sd[a-z] or /dev/disk/cloud/azure_resource
    # where partitions are "<devpath>1" or "<devpath>-part1" or "<devpath>p1"
    partitions = _partitions_on_device(devpath)
    if len(partitions) == 0:
        return False, 'device %s was not partitioned' % devpath
    elif len(partitions) > 2:
        msg = ('device %s had 3 or more partitions: %s' %
               (devpath, ' '.join([p[1] for p in partitions])))
        return False, msg
    elif len(partitions) == 2:
        cand_part, cand_path = partitions[1]
    else:
        cand_part, cand_path = partitions[0]

    if not _has_ntfs_filesystem(cand_path):
        msg = ('partition %s (%s) on device %s was not ntfs formatted' %
               (cand_part, cand_path, devpath))
        return False, msg

    @azure_ds_telemetry_reporter
    def count_files(mp):
        ignored = set(['dataloss_warning_readme.txt'])
        return len([f for f in os.listdir(mp) if f.lower() not in ignored])

    bmsg = ('partition %s (%s) on device %s was ntfs formatted' %
            (cand_part, cand_path, devpath))

    with events.ReportEventStack(
        name="mount-ntfs-and-count",
        description="mount-ntfs-and-count",
        parent=azure_ds_reporter
    ) as evt:
        try:
            file_count = util.mount_cb(cand_path, count_files, mtype="ntfs",
                                       update_env_for_mount={'LANG': 'C'})
        except util.MountFailedError as e:
            evt.description = "cannot mount ntfs"
            if "unknown filesystem type 'ntfs'" in str(e):
                return True, (bmsg + ' but this system cannot mount NTFS,'
                              ' assuming there are no important files.'
                              ' Formatting allowed.')
            return False, bmsg + ' but mount of %s failed: %s' % (cand_part, e)

        if file_count != 0:
            evt.description = "mounted and counted %d files" % file_count
            LOG.warning("it looks like you're using NTFS on the ephemeral"
                        " disk, to ensure that filesystem does not get wiped,"
                        " set %s.%s in config", '.'.join(DS_CFG_PATH),
                        DS_CFG_KEY_PRESERVE_NTFS)
            return False, bmsg + ' but had %d files on it.' % file_count

    return True, bmsg + ' and had no important files. Safe for reformatting.'


@azure_ds_telemetry_reporter
def address_ephemeral_resize(devpath=RESOURCE_DISK_PATH, maxwait=120,
                             is_new_instance=False, preserve_ntfs=False):
    # wait for ephemeral disk to come up
    naplen = .2
    with events.ReportEventStack(
        name="wait-for-ephemeral-disk",
        description="wait for ephemeral disk",
        parent=azure_ds_reporter
    ):
        missing = util.wait_for_files([devpath],
                                      maxwait=maxwait,
                                      naplen=naplen,
                                      log_pre="Azure ephemeral disk: ")

        if missing:
            report_diagnostic_event(
                "ephemeral device '%s' did not appear after %d seconds." %
                (devpath, maxwait),
                logger_func=LOG.warning)
            return

    result = False
    msg = None
    if is_new_instance:
        result, msg = (True, "First instance boot.")
    else:
        result, msg = can_dev_be_reformatted(devpath, preserve_ntfs)

    LOG.debug("reformattable=%s: %s", result, msg)
    if not result:
        return

    for mod in ['disk_setup', 'mounts']:
        sempath = '/var/lib/cloud/instance/sem/config_' + mod
        bmsg = 'Marker "%s" for module "%s"' % (sempath, mod)
        if os.path.exists(sempath):
            try:
                os.unlink(sempath)
                LOG.debug('%s removed.', bmsg)
            except Exception as e:
                # python3 throws FileNotFoundError, python2 throws OSError
                LOG.warning('%s: remove failed! (%s)', bmsg, e)
        else:
            LOG.debug('%s did not exist.', bmsg)
    return


@azure_ds_telemetry_reporter
def perform_hostname_bounce(hostname, cfg, prev_hostname):
    # set the hostname to 'hostname' if it is not already set to that.
    # then, if policy is not off, bounce the interface using command
    # Returns True if the network was bounced, False otherwise.
    command = cfg['command']
    interface = cfg['interface']
    policy = cfg['policy']

    msg = ("hostname=%s policy=%s interface=%s" %
           (hostname, policy, interface))
    env = os.environ.copy()
    env['interface'] = interface
    env['hostname'] = hostname
    env['old_hostname'] = prev_hostname

    if command == "builtin":
        if util.is_FreeBSD():
            command = BOUNCE_COMMAND_FREEBSD
        elif subp.which('ifup'):
            command = BOUNCE_COMMAND_IFUP
        else:
            LOG.debug(
                "Skipping network bounce: ifupdown utils aren't present.")
            # Don't bounce as networkd handles hostname DDNS updates
            return False
    LOG.debug("pubhname: publishing hostname [%s]", msg)
    shell = not isinstance(command, (list, tuple))
    # capture=False, see comments in bug 1202758 and bug 1206164.
    util.log_time(logfunc=LOG.debug, msg="publishing hostname",
                  get_uptime=True, func=subp.subp,
                  kwargs={'args': command, 'shell': shell, 'capture': False,
                          'env': env})
    return True


@azure_ds_telemetry_reporter
def crtfile_to_pubkey(fname, data=None):
    pipeline = ('openssl x509 -noout -pubkey < "$0" |'
                'ssh-keygen -i -m PKCS8 -f /dev/stdin')
    (out, _err) = subp.subp(['sh', '-c', pipeline, fname],
                            capture=True, data=data)
    return out.rstrip()


@azure_ds_telemetry_reporter
def pubkeys_from_crt_files(flist):
    pubkeys = []
    errors = []
    for fname in flist:
        try:
            pubkeys.append(crtfile_to_pubkey(fname))
        except subp.ProcessExecutionError:
            errors.append(fname)

    if errors:
        report_diagnostic_event(
            "failed to convert the crt files to pubkey: %s" % errors,
            logger_func=LOG.warning)

    return pubkeys


@azure_ds_telemetry_reporter
def write_files(datadir, files, dirmode=None):

    def _redact_password(cnt, fname):
        """Azure provides the UserPassword in plain text. So we redact it"""
        try:
            root = ET.fromstring(cnt)
            for elem in root.iter():
                if ('UserPassword' in elem.tag and
                   elem.text != DEF_PASSWD_REDACTION):
                    elem.text = DEF_PASSWD_REDACTION
            return ET.tostring(root)
        except Exception:
            LOG.critical("failed to redact userpassword in %s", fname)
            return cnt

    if not datadir:
        return
    if not files:
        files = {}
    util.ensure_dir(datadir, dirmode)
    for (name, content) in files.items():
        fname = os.path.join(datadir, name)
        if 'ovf-env.xml' in name:
            content = _redact_password(content, fname)
        util.write_file(filename=fname, content=content, mode=0o600)


@azure_ds_telemetry_reporter
def invoke_agent(cmd):
    # this is a function itself to simplify patching it for test
    if cmd:
        LOG.debug("invoking agent: %s", cmd)
        subp.subp(cmd, shell=(not isinstance(cmd, list)))
    else:
        LOG.debug("not invoking agent")


def find_child(node, filter_func):
    ret = []
    if not node.hasChildNodes():
        return ret
    for child in node.childNodes:
        if filter_func(child):
            ret.append(child)
    return ret


@azure_ds_telemetry_reporter
def load_azure_ovf_pubkeys(sshnode):
    # This parses a 'SSH' node formatted like below, and returns
    # an array of dicts.
    #  [{'fingerprint': '6BE7A7C3C8A8F4B123CCA5D0C2F1BE4CA7B63ED7',
    #    'path': '/where/to/go'}]
    #
    # <SSH><PublicKeys>
    #   <PublicKey><Fingerprint>ABC</FingerPrint><Path>/x/y/z</Path>
    #   ...
    # </PublicKeys></SSH>
    # Under some circumstances, there may be a <Value> element along with the
    # Fingerprint and Path. Pass those along if they appear.
    results = find_child(sshnode, lambda n: n.localName == "PublicKeys")
    if len(results) == 0:
        return []
    if len(results) > 1:
        raise BrokenAzureDataSource("Multiple 'PublicKeys'(%s) in SSH node" %
                                    len(results))

    pubkeys_node = results[0]
    pubkeys = find_child(pubkeys_node, lambda n: n.localName == "PublicKey")

    if len(pubkeys) == 0:
        return []

    found = []
    text_node = minidom.Document.TEXT_NODE

    for pk_node in pubkeys:
        if not pk_node.hasChildNodes():
            continue

        cur = {'fingerprint': "", 'path': "", 'value': ""}
        for child in pk_node.childNodes:
            if child.nodeType == text_node or not child.localName:
                continue

            name = child.localName.lower()

            if name not in cur.keys():
                continue

            if (len(child.childNodes) != 1 or
                    child.childNodes[0].nodeType != text_node):
                continue

            cur[name] = child.childNodes[0].wholeText.strip()
        found.append(cur)

    return found


@azure_ds_telemetry_reporter
def read_azure_ovf(contents):
    try:
        dom = minidom.parseString(contents)
    except Exception as e:
        error_str = "Invalid ovf-env.xml: %s" % e
        report_diagnostic_event(error_str, logger_func=LOG.warning)
        raise BrokenAzureDataSource(error_str) from e

    results = find_child(dom.documentElement,
                         lambda n: n.localName == "ProvisioningSection")

    if len(results) == 0:
        raise NonAzureDataSource("No ProvisioningSection")
    if len(results) > 1:
        raise BrokenAzureDataSource("found '%d' ProvisioningSection items" %
                                    len(results))
    provSection = results[0]

    lpcs_nodes = find_child(provSection,
                            lambda n:
                            n.localName == "LinuxProvisioningConfigurationSet")

    if len(lpcs_nodes) == 0:
        raise NonAzureDataSource("No LinuxProvisioningConfigurationSet")
    if len(lpcs_nodes) > 1:
        raise BrokenAzureDataSource("found '%d' %ss" %
                                    (len(lpcs_nodes),
                                     "LinuxProvisioningConfigurationSet"))
    lpcs = lpcs_nodes[0]

    if not lpcs.hasChildNodes():
        raise BrokenAzureDataSource("no child nodes of configuration set")

    md_props = 'seedfrom'
    md = {'azure_data': {}}
    cfg = {}
    ud = ""
    password = None
    username = None

    for child in lpcs.childNodes:
        if child.nodeType == dom.TEXT_NODE or not child.localName:
            continue

        name = child.localName.lower()

        simple = False
        value = ""
        if (len(child.childNodes) == 1 and
                child.childNodes[0].nodeType == dom.TEXT_NODE):
            simple = True
            value = child.childNodes[0].wholeText

        attrs = dict([(k, v) for k, v in child.attributes.items()])

        # we accept either UserData or CustomData.  If both are present
        # then behavior is undefined.
        if name == "userdata" or name == "customdata":
            if attrs.get('encoding') in (None, "base64"):
                ud = base64.b64decode(''.join(value.split()))
            else:
                ud = value
        elif name == "username":
            username = value
        elif name == "userpassword":
            password = value
        elif name == "hostname":
            md['local-hostname'] = value
        elif name == "dscfg":
            if attrs.get('encoding') in (None, "base64"):
                dscfg = base64.b64decode(''.join(value.split()))
            else:
                dscfg = value
            cfg['datasource'] = {DS_NAME: util.load_yaml(dscfg, default={})}
        elif name == "ssh":
            cfg['_pubkeys'] = load_azure_ovf_pubkeys(child)
        elif name == "disablesshpasswordauthentication":
            cfg['ssh_pwauth'] = util.is_false(value)
        elif simple:
            if name in md_props:
                md[name] = value
            else:
                md['azure_data'][name] = value

    defuser = {}
    if username:
        defuser['name'] = username
    if password:
        defuser['lock_passwd'] = False
        if DEF_PASSWD_REDACTION != password:
            defuser['passwd'] = encrypt_pass(password)

    if defuser:
        cfg['system_info'] = {'default_user': defuser}

    if 'ssh_pwauth' not in cfg and password:
        cfg['ssh_pwauth'] = True

    cfg['PreprovisionedVm'] = _extract_preprovisioned_vm_setting(dom)

    return (md, ud, cfg)


@azure_ds_telemetry_reporter
def _extract_preprovisioned_vm_setting(dom):
    """Read the preprovision flag from the ovf. It should not
       exist unless true."""
    platform_settings_section = find_child(
        dom.documentElement,
        lambda n: n.localName == "PlatformSettingsSection")
    if not platform_settings_section or len(platform_settings_section) == 0:
        LOG.debug("PlatformSettingsSection not found")
        return False
    platform_settings = find_child(
        platform_settings_section[0],
        lambda n: n.localName == "PlatformSettings")
    if not platform_settings or len(platform_settings) == 0:
        LOG.debug("PlatformSettings not found")
        return False
    preprovisionedVm = find_child(
        platform_settings[0],
        lambda n: n.localName == "PreprovisionedVm")
    if not preprovisionedVm or len(preprovisionedVm) == 0:
        LOG.debug("PreprovisionedVm not found")
        return False
    return util.translate_bool(preprovisionedVm[0].firstChild.nodeValue)


def encrypt_pass(password, salt_id="$6$"):
    return crypt.crypt(password, salt_id + util.rand_str(strlen=16))


@azure_ds_telemetry_reporter
def _check_freebsd_cdrom(cdrom_dev):
    """Return boolean indicating path to cdrom device has content."""
    try:
        with open(cdrom_dev) as fp:
            fp.read(1024)
            return True
    except IOError:
        LOG.debug("cdrom (%s) is not configured", cdrom_dev)
    return False


@azure_ds_telemetry_reporter
def _get_random_seed(source=PLATFORM_ENTROPY_SOURCE):
    """Return content random seed file if available, otherwise,
       return None."""
    # azure / hyper-v provides random data here
    # now update ds_cfg to reflect contents pass in config
    if source is None:
        return None
    seed = util.load_file(source, quiet=True, decode=False)

    # The seed generally contains non-Unicode characters. load_file puts
    # them into a str (in python 2) or bytes (in python 3). In python 2,
    # bad octets in a str cause util.json_dumps() to throw an exception. In
    # python 3, bytes is a non-serializable type, and the handler load_file
    # uses applies b64 encoding *again* to handle it. The simplest solution
    # is to just b64encode the data and then decode it to a serializable
    # string. Same number of bits of entropy, just with 25% more zeroes.
    # There's no need to undo this base64-encoding when the random seed is
    # actually used in cc_seed_random.py.
    seed = base64.b64encode(seed).decode()

    return seed


@azure_ds_telemetry_reporter
def list_possible_azure_ds_devs():
    devlist = []
    if util.is_FreeBSD():
        cdrom_dev = "/dev/cd0"
        if _check_freebsd_cdrom(cdrom_dev):
            return [cdrom_dev]
    else:
        for fstype in ("iso9660", "udf"):
            devlist.extend(util.find_devs_with("TYPE=%s" % fstype))

    devlist.sort(reverse=True)
    return devlist


@azure_ds_telemetry_reporter
def load_azure_ds_dir(source_dir):
    ovf_file = os.path.join(source_dir, "ovf-env.xml")

    if not os.path.isfile(ovf_file):
        raise NonAzureDataSource("No ovf-env file found")

    with open(ovf_file, "rb") as fp:
        contents = fp.read()

    md, ud, cfg = read_azure_ovf(contents)
    return (md, ud, cfg, {'ovf-env.xml': contents})


@azure_ds_telemetry_reporter
def parse_network_config(imds_metadata) -> dict:
    """Convert imds_metadata dictionary to network v2 configuration.
    Parses network configuration from imds metadata if present or generate
    fallback network config excluding mlx4_core devices.

    @param: imds_metadata: Dict of content read from IMDS network service.
    @return: Dictionary containing network version 2 standard configuration.
    """
    if imds_metadata != sources.UNSET and imds_metadata:
        try:
            return _generate_network_config_from_imds_metadata(imds_metadata)
        except Exception as e:
            LOG.error(
                'Failed generating network config '
                'from IMDS network metadata: %s', str(e))
    try:
        return _generate_network_config_from_fallback_config()
    except Exception as e:
        LOG.error('Failed generating fallback network config: %s', str(e))
    return {}


@azure_ds_telemetry_reporter
def _generate_network_config_from_imds_metadata(imds_metadata) -> dict:
    """Convert imds_metadata dictionary to network v2 configuration.
    Parses network configuration from imds metadata.

    @param: imds_metadata: Dict of content read from IMDS network service.
    @return: Dictionary containing network version 2 standard configuration.
    """
    netconfig = {'version': 2, 'ethernets': {}}
    network_metadata = imds_metadata['network']
    for idx, intf in enumerate(network_metadata['interface']):
        # First IPv4 and/or IPv6 address will be obtained via DHCP.
        # Any additional IPs of each type will be set as static
        # addresses.
        nicname = 'eth{idx}'.format(idx=idx)
        dhcp_override = {'route-metric': (idx + 1) * 100}
        dev_config = {'dhcp4': True, 'dhcp4-overrides': dhcp_override,
                      'dhcp6': False}
        for addr_type in ('ipv4', 'ipv6'):
            addresses = intf.get(addr_type, {}).get('ipAddress', [])
            if addr_type == 'ipv4':
                default_prefix = '24'
            else:
                default_prefix = '128'
                if addresses:
                    dev_config['dhcp6'] = True
                    # non-primary interfaces should have a higher
                    # route-metric (cost) so default routes prefer
                    # primary nic due to lower route-metric value
                    dev_config['dhcp6-overrides'] = dhcp_override
            for addr in addresses[1:]:
                # Append static address config for ip > 1
                netPrefix = intf[addr_type]['subnet'][0].get(
                    'prefix', default_prefix)
                privateIp = addr['privateIpAddress']
                if not dev_config.get('addresses'):
                    dev_config['addresses'] = []
                dev_config['addresses'].append(
                    '{ip}/{prefix}'.format(
                        ip=privateIp, prefix=netPrefix))
        if dev_config:
            mac = ':'.join(re.findall(r'..', intf['macAddress']))
            dev_config.update({
                'match': {'macaddress': mac.lower()},
                'set-name': nicname
            })
            # With netvsc, we can get two interfaces that
            # share the same MAC, so we need to make sure
            # our match condition also contains the driver
            driver = device_driver(nicname)
            if driver and driver == 'hv_netvsc':
                dev_config['match']['driver'] = driver
            netconfig['ethernets'][nicname] = dev_config
    return netconfig


@azure_ds_telemetry_reporter
def _generate_network_config_from_fallback_config() -> dict:
    """Generate fallback network config excluding blacklisted devices.

    @return: Dictionary containing network version 2 standard configuration.
    """
    return net.generate_fallback_config(
        blacklist_drivers=BLACKLIST_DRIVERS, config_driver=True)


@azure_ds_telemetry_reporter
def get_metadata_from_imds(fallback_nic, retries):
    """Query Azure's network metadata service, returning a dictionary.

    If network is not up, setup ephemeral dhcp on fallback_nic to talk to the
    IMDS. For more info on IMDS:
        https://docs.microsoft.com/en-us/azure/virtual-machines/windows/instance-metadata-service

    @param fallback_nic: String. The name of the nic which requires active
        network in order to query IMDS.
    @param retries: The number of retries of the IMDS_URL.

    @return: A dict of instance metadata containing compute and network
        info.
    """
    kwargs = {'logfunc': LOG.debug,
              'msg': 'Crawl of Azure Instance Metadata Service (IMDS)',
              'func': _get_metadata_from_imds, 'args': (retries,)}
    if net.is_up(fallback_nic):
        return util.log_time(**kwargs)
    else:
        try:
            with EphemeralDHCPv4WithReporting(
                    azure_ds_reporter, fallback_nic):
                return util.log_time(**kwargs)
        except Exception as e:
            report_diagnostic_event(
                "exception while getting metadata: %s" % e,
                logger_func=LOG.warning)
            raise


@azure_ds_telemetry_reporter
def _get_metadata_from_imds(retries):

    url = IMDS_URL + "instance?api-version=2019-06-01"
    headers = {"Metadata": "true"}
    try:
        response = readurl(
            url, timeout=IMDS_TIMEOUT_IN_SECONDS, headers=headers,
            retries=retries, exception_cb=retry_on_url_exc)
    except Exception as e:
        report_diagnostic_event(
            'Ignoring IMDS instance metadata. '
            'Get metadata from IMDS failed: %s' % e,
            logger_func=LOG.warning)
        return {}
    try:
        from json.decoder import JSONDecodeError
        json_decode_error = JSONDecodeError
    except ImportError:
        json_decode_error = ValueError

    try:
        return util.load_json(str(response))
    except json_decode_error as e:
        report_diagnostic_event(
            'Ignoring non-json IMDS instance metadata response: %s. '
            'Loading non-json IMDS response failed: %s' % (str(response), e),
            logger_func=LOG.warning)
    return {}


@azure_ds_telemetry_reporter
def maybe_remove_ubuntu_network_config_scripts(paths=None):
    """Remove Azure-specific ubuntu network config for non-primary nics.

    @param paths: List of networking scripts or directories to remove when
        present.

    In certain supported ubuntu images, static udev rules or netplan yaml
    config is delivered in the base ubuntu image to support dhcp on any
    additional interfaces which get attached by a customer at some point
    after initial boot. Since the Azure datasource can now regenerate
    network configuration as metadata reports these new devices, we no longer
    want the udev rules or netplan's 90-hotplug-azure.yaml to configure
    networking on eth1 or greater as it might collide with cloud-init's
    configuration.

    Remove the any existing extended network scripts if the datasource is
    enabled to write network per-boot.
    """
    if not paths:
        paths = UBUNTU_EXTENDED_NETWORK_SCRIPTS
    logged = False
    for path in paths:
        if os.path.exists(path):
            if not logged:
                LOG.info(
                    'Removing Ubuntu extended network scripts because'
                    ' cloud-init updates Azure network configuration on the'
                    ' following event: %s.',
                    EventType.BOOT)
                logged = True
            if os.path.isdir(path):
                util.del_dir(path)
            else:
                util.del_file(path)


def _is_platform_viable(seed_dir):
    """Check platform environment to report if this datasource may run."""
    with events.ReportEventStack(
        name="check-platform-viability",
        description="found azure asset tag",
        parent=azure_ds_reporter
    ) as evt:
        asset_tag = dmi.read_dmi_data('chassis-asset-tag')
        if asset_tag == AZURE_CHASSIS_ASSET_TAG:
            return True
        msg = "Non-Azure DMI asset tag '%s' discovered." % asset_tag
        evt.description = msg
        report_diagnostic_event(msg, logger_func=LOG.debug)
        if os.path.exists(os.path.join(seed_dir, 'ovf-env.xml')):
            return True
        return False


class BrokenAzureDataSource(Exception):
    pass


class NonAzureDataSource(Exception):
    pass


# Legacy: Must be present in case we load an old pkl object
DataSourceAzureNet = DataSourceAzure

# Used to match classes to dependencies
datasources = [
    (DataSourceAzure, (sources.DEP_FILESYSTEM, )),
]


# Return a list of data sources that match this set of dependencies
def get_datasource_list(depends):
    return sources.list_from_depends(depends, datasources)

# vi: ts=4 expandtab