-
Notifications
You must be signed in to change notification settings - Fork 908
/
Copy pathDataSourceAzure.py
executable file
·2475 lines (2135 loc) · 87.8 KB
/
DataSourceAzure.py
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
# 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 crypt
import datetime
import os
import os.path
import re
import xml.etree.ElementTree as ET
from collections import namedtuple
from enum import Enum
from functools import partial
from time import sleep, time
from typing import List, Optional
from xml.dom import minidom
import requests
from cloudinit import dmi
from cloudinit import log as logging
from cloudinit import net, sources, ssh_util, subp, util
from cloudinit.event import EventScope, EventType
from cloudinit.net import device_driver
from cloudinit.net.dhcp import EphemeralDHCPv4, NoDHCPLeaseError
from cloudinit.reporting import events
from cloudinit.sources.helpers import netlink
from cloudinit.sources.helpers.azure import (
DEFAULT_REPORT_FAILURE_USER_VISIBLE_MESSAGE,
DEFAULT_WIRESERVER_ENDPOINT,
azure_ds_reporter,
azure_ds_telemetry_reporter,
build_minimal_ovf,
dhcp_log_cb,
get_boot_telemetry,
get_metadata_from_fabric,
get_system_info,
is_byte_swapped,
push_log_to_kvp,
report_diagnostic_event,
report_failure_to_fabric,
)
from cloudinit.url_helper import UrlError, readurl, retry_on_url_exc
LOG = logging.getLogger(__name__)
DS_NAME = "Azure"
DEFAULT_METADATA = {"instance-id": "iid-AZURE-NODE"}
# 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"
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"
REPROVISION_NIC_DETACHED_MARKER_FILE = "/var/lib/cloud/data/nic_detached"
REPORTED_READY_MARKER_FILE = "/var/lib/cloud/data/reported_ready"
AGENT_SEED_DIR = "/var/lib/waagent"
DEFAULT_PROVISIONING_ISO_DEV = "/dev/sr0"
# 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"
IMDS_VER_MIN = "2019-06-01"
IMDS_VER_WANT = "2021-08-01"
IMDS_EXTENDED_VER_MIN = "2021-03-01"
# This holds SSH key data including if the source was
# from IMDS, as well as the SSH key data itself.
SSHKeys = namedtuple("SSHKeys", ("keys_from_imds", "ssh_keys"))
class MetadataType(Enum):
ALL = "{}/instance".format(IMDS_URL)
NETWORK = "{}/instance/network".format(IMDS_URL)
REPROVISION_DATA = "{}/reprovisiondata".format(IMDS_URL)
class PPSType(Enum):
NONE = "None"
RUNNING = "Running"
SAVABLE = "Savable"
UNKNOWN = "Unknown"
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 normalize_mac_address(mac: str):
"""Normalize mac address with colons and lower-case."""
if len(mac) == 12:
mac = ":".join(
[mac[0:2], mac[2:4], mac[4:6], mac[6:8], mac[8:10], mac[10:12]]
)
return mac.lower()
@azure_ds_telemetry_reporter
def get_hv_netvsc_macs_normalized() -> List[str]:
"""Get Hyper-V NICs as normalized MAC addresses."""
return [
normalize_mac_address(n[1])
for n in net.get_interfaces()
if n[2] == "hv_netvsc"
]
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():
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 = {
"data_dir": AGENT_SEED_DIR,
"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_EPHEMERAL_DISK_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"
class DataSourceAzure(sources.DataSource):
dsname = "Azure"
default_update_events = {
EventScope.NETWORK: {
EventType.BOOT_NEW_INSTANCE,
EventType.BOOT,
}
}
_negotiated = False
_metadata_imds = sources.UNSET
_ci_pkl_version = 1
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
self._ephemeral_dhcp_ctx = None
self._wireserver_endpoint = DEFAULT_WIRESERVER_ENDPOINT
self.iso_dev = None
def _unpickle(self, ci_pkl_version: int) -> None:
super()._unpickle(ci_pkl_version)
self._ephemeral_dhcp_ctx = None
if not hasattr(self, "iso_dev"):
self.iso_dev = None
self._wireserver_endpoint = DEFAULT_WIRESERVER_ENDPOINT
def __str__(self):
root = sources.DataSource.__str__(self)
return "%s [seed=%s]" % (root, self.seed)
def _get_subplatform(self):
"""Return the subplatform metadata source details."""
if self.seed.startswith("/dev"):
subplatform_type = "config-disk"
elif self.seed.lower() == "imds":
subplatform_type = "imds"
else:
subplatform_type = "seed-dir"
return "%s (%s)" % (subplatform_type, self.seed)
@azure_ds_telemetry_reporter
def _setup_ephemeral_networking(
self, *, iface: Optional[str] = None, timeout_minutes: int = 5
) -> None:
"""Setup ephemeral networking.
Keep retrying DHCP up to specified number of minutes. This does
not kill dhclient, so the timeout in practice may be up to
timeout_minutes + the system-configured timeout for dhclient.
:param timeout_minutes: Number of minutes to keep retrying for.
:raises NoDHCPLeaseError: If unable to obtain DHCP lease.
"""
if self._ephemeral_dhcp_ctx is not None:
raise RuntimeError(
"Bringing up networking when already configured."
)
LOG.debug("Requested ephemeral networking (iface=%s)", iface)
start = datetime.datetime.utcnow()
timeout = start + datetime.timedelta(minutes=timeout_minutes)
self._ephemeral_dhcp_ctx = EphemeralDHCPv4(
iface=iface, dhcp_log_func=dhcp_log_cb
)
lease = None
with events.ReportEventStack(
name="obtain-dhcp-lease",
description="obtain dhcp lease",
parent=azure_ds_reporter,
):
while datetime.datetime.utcnow() < timeout:
try:
lease = self._ephemeral_dhcp_ctx.obtain_lease()
break
except NoDHCPLeaseError:
continue
if lease is None:
msg = "Failed to obtain DHCP lease (iface=%s)" % iface
report_diagnostic_event(msg, logger_func=LOG.error)
self._ephemeral_dhcp_ctx = None
raise NoDHCPLeaseError()
else:
# Ensure iface is set.
self._ephemeral_dhcp_ctx.iface = lease["interface"]
# Update wireserver IP from DHCP options.
if "unknown-245" in lease:
self._wireserver_endpoint = lease["unknown-245"]
@azure_ds_telemetry_reporter
def _teardown_ephemeral_networking(self) -> None:
"""Teardown ephemeral networking."""
if self._ephemeral_dhcp_ctx is None:
return
self._ephemeral_dhcp_ctx.clean_network()
self._ephemeral_dhcp_ctx = None
def _is_ephemeral_networking_up(self) -> bool:
"""Check if networking is configured."""
return not (
self._ephemeral_dhcp_ctx is None
or self._ephemeral_dhcp_ctx.lease is None
)
@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"]
# The order in which the candidates are inserted matters here, because
# it determines the value of ret. More specifically, the first one in
# the candidate list determines the path to take in order to get the
# metadata we need.
ovf_is_accessible = False
metadata_source = None
md = {}
userdata_raw = ""
cfg = {}
files = {}
iso_dev = None
if os.path.isfile(REPROVISION_MARKER_FILE):
metadata_source = "IMDS"
report_diagnostic_event(
"Reprovision marker file already present "
"before crawling Azure metadata: %s" % REPROVISION_MARKER_FILE,
logger_func=LOG.debug,
)
else:
for src in list_possible_azure_ds(self.seed_dir, ddir):
try:
if src.startswith("/dev/"):
if util.is_FreeBSD():
md, userdata_raw, cfg, files = util.mount_cb(
src, load_azure_ds_dir, mtype="udf"
)
else:
md, userdata_raw, cfg, files = util.mount_cb(
src, load_azure_ds_dir
)
# save the device for ejection later
iso_dev = src
else:
md, userdata_raw, cfg, files = load_azure_ds_dir(src)
ovf_is_accessible = True
metadata_source = src
break
except NonAzureDataSource:
report_diagnostic_event(
"Did not find Azure data source in %s" % src,
logger_func=LOG.debug,
)
continue
except util.MountFailedError:
report_diagnostic_event(
"%s was not mountable" % src, logger_func=LOG.debug
)
md = {"local-hostname": ""}
cfg = {"system_info": {"default_user": {"name": ""}}}
metadata_source = "IMDS"
continue
except BrokenAzureDataSource as exc:
msg = "BrokenAzureDataSource: %s" % exc
report_diagnostic_event(msg, logger_func=LOG.error)
raise sources.InvalidMetaDataException(msg)
report_diagnostic_event(
"Found provisioning metadata in %s" % metadata_source,
logger_func=LOG.debug,
)
# If we read OVF from attached media, we are provisioning. If OVF
# is not found, we are probably provisioning on a system which does
# not have UDF support. In either case, require IMDS metadata.
# If we require IMDS metadata, try harder to obtain networking, waiting
# for at least 20 minutes. Otherwise only wait 5 minutes.
requires_imds_metadata = bool(iso_dev) or not ovf_is_accessible
timeout_minutes = 5 if requires_imds_metadata else 20
try:
self._setup_ephemeral_networking(timeout_minutes=timeout_minutes)
except NoDHCPLeaseError:
pass
if self._is_ephemeral_networking_up():
imds_md = self.get_imds_data_with_api_fallback(retries=10)
else:
imds_md = {}
if not imds_md and not ovf_is_accessible:
msg = "No OVF or IMDS available"
report_diagnostic_event(msg)
raise sources.InvalidMetaDataException(msg)
self.iso_dev = iso_dev
# Refresh PPS type using metadata.
pps_type = self._determine_pps_type(cfg, imds_md)
if pps_type != PPSType.NONE:
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)
self._write_reprovision_marker()
if pps_type == PPSType.SAVABLE:
self._wait_for_all_nics_ready()
md, userdata_raw, cfg, files = self._reprovision()
# fetch metadata again as it has changed after reprovisioning
imds_md = self.get_imds_data_with_api_fallback(retries=10)
# Report errors if IMDS network configuration is missing data.
self.validate_imds_network_metadata(imds_md=imds_md)
self.seed = metadata_source
crawled_data.update(
{
"cfg": cfg,
"files": files,
"metadata": util.mergemanydict([md, {"imds": imds_md}]),
"userdata_raw": userdata_raw,
}
)
imds_username = _username_from_imds(imds_md)
imds_hostname = _hostname_from_imds(imds_md)
imds_disable_password = _disable_password_from_imds(imds_md)
if imds_username:
LOG.debug("Username retrieved from IMDS: %s", imds_username)
cfg["system_info"]["default_user"]["name"] = imds_username
if imds_hostname:
LOG.debug("Hostname retrieved from IMDS: %s", imds_hostname)
crawled_data["metadata"]["local-hostname"] = imds_hostname
if imds_disable_password:
LOG.debug(
"Disable password retrieved from IMDS: %s",
imds_disable_password,
)
crawled_data["metadata"][
"disable_password"
] = imds_disable_password
if metadata_source == "IMDS" and not crawled_data["files"]:
try:
contents = build_minimal_ovf(
username=imds_username,
hostname=imds_hostname,
disableSshPwd=imds_disable_password,
)
crawled_data["files"] = {"ovf-env.xml": contents}
except Exception as e:
report_diagnostic_event(
"Failed to construct OVF from IMDS data %s" % e,
logger_func=LOG.debug,
)
# only use userdata from imds if OVF did not provide custom data
# userdata provided by IMDS is always base64 encoded
if not userdata_raw:
imds_userdata = _userdata_from_imds(imds_md)
if imds_userdata:
LOG.debug("Retrieved userdata from IMDS")
try:
crawled_data["userdata_raw"] = base64.b64decode(
"".join(imds_userdata.split())
)
except Exception:
report_diagnostic_event(
"Bad userdata in IMDS", logger_func=LOG.warning
)
if not metadata_source:
msg = "No Azure metadata found"
report_diagnostic_event(msg, logger_func=LOG.error)
raise sources.InvalidMetaDataException(msg)
else:
report_diagnostic_event(
"found datasource in %s" % metadata_source,
logger_func=LOG.debug,
)
if metadata_source == 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 pps_type != PPSType.NONE:
LOG.info("Reporting ready to Azure after getting ReprovisionData")
self._report_ready()
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 Exception as e:
report_diagnostic_event(
"Could not crawl Azure metadata: %s" % e, logger_func=LOG.error
)
self._report_failure(
description=DEFAULT_REPORT_FAILURE_USER_VISIBLE_MESSAGE
)
return False
finally:
self._teardown_ephemeral_networking()
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
# Only merge in default cloud config related to the ephemeral disk
# if the ephemeral disk exists
devpath = RESOURCE_DISK_PATH
if os.path.exists(devpath):
report_diagnostic_event(
"Ephemeral resource disk '%s' exists. "
"Merging default Azure cloud ephemeral disk configs."
% devpath,
logger_func=LOG.debug,
)
self.cfg = util.mergemanydict(
[crawled_data["cfg"], BUILTIN_CLOUD_EPHEMERAL_DISK_CONFIG]
)
else:
report_diagnostic_event(
"Ephemeral resource disk '%s' does not exist. "
"Not merging default Azure cloud ephemeral disk configs."
% devpath,
logger_func=LOG.debug,
)
self.cfg = crawled_data["cfg"]
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
@azure_ds_telemetry_reporter
def get_imds_data_with_api_fallback(
self,
*,
retries,
md_type=MetadataType.ALL,
exc_cb=retry_on_url_exc,
infinite=False,
):
"""
Wrapper for get_metadata_from_imds so that we can have flexibility
in which IMDS api-version we use. If a particular instance of IMDS
does not have the api version that is desired, we want to make
this fault tolerant and fall back to a good known minimum api
version.
"""
for _ in range(retries):
try:
LOG.info("Attempting IMDS api-version: %s", IMDS_VER_WANT)
return get_metadata_from_imds(
retries=0,
md_type=md_type,
api_version=IMDS_VER_WANT,
exc_cb=exc_cb,
)
except UrlError as err:
LOG.info("UrlError with IMDS api-version: %s", IMDS_VER_WANT)
if err.code == 400:
log_msg = "Fall back to IMDS api-version: {}".format(
IMDS_VER_MIN
)
report_diagnostic_event(log_msg, logger_func=LOG.info)
break
LOG.info("Using IMDS api-version: %s", IMDS_VER_MIN)
return get_metadata_from_imds(
retries=retries,
md_type=md_type,
api_version=IMDS_VER_MIN,
exc_cb=exc_cb,
infinite=infinite,
)
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):
"""
Retrieve public SSH keys.
"""
return self._get_public_ssh_keys_and_source().ssh_keys
def _get_public_ssh_keys_and_source(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 = []
keys_from_imds = True
LOG.debug("Attempting to get SSH keys from IMDS")
try:
ssh_keys = [
public_key["keyData"]
for public_key in self.metadata["imds"]["compute"][
"publicKeys"
]
]
for key in ssh_keys:
if not _key_is_openssh_formatted(key=key):
keys_from_imds = False
break
if not keys_from_imds:
log_msg = "Keys not in OpenSSH format, using OVF"
else:
log_msg = "Retrieved {} keys from IMDS".format(
len(ssh_keys) if ssh_keys is not None else 0
)
except KeyError:
log_msg = "Unable to get keys from IMDS, falling back to OVF"
keys_from_imds = False
finally:
report_diagnostic_event(log_msg, logger_func=LOG.debug)
if not keys_from_imds:
LOG.debug("Attempting to get SSH keys from OVF")
try:
ssh_keys = self.metadata["public-keys"]
log_msg = "Retrieved {} keys from OVF".format(len(ssh_keys))
except KeyError:
log_msg = "No keys available from OVF"
finally:
report_diagnostic_event(log_msg, logger_func=LOG.debug)
return SSHKeys(keys_from_imds=keys_from_imds, ssh_keys=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"
)
# Older kernels than 4.15 will have UPPERCASE product_uuid.
# We don't want Azure to react to an UPPER/lower difference as a new
# instance id as it rewrites SSH host keys.
# LP: #1835584
iid = dmi.read_dmi_data("system-uuid").lower()
if os.path.exists(prev_iid_path):
previous = util.load_file(prev_iid_path).strip()
if previous.lower() == iid:
# If uppercase/lowercase equivalent, return the previous value
# to avoid new instance id.
return previous
if is_byte_swapped(previous.lower(), 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()
)
@azure_ds_telemetry_reporter
def _wait_for_nic_detach(self, nl_sock):
"""Use the netlink socket provided to wait for nic detach event.
NOTE: The function doesn't close the socket. The caller owns closing
the socket and disposing it safely.
"""
try:
ifname = None
# Preprovisioned VM will only have one NIC, and it gets
# detached immediately after deployment.
with events.ReportEventStack(
name="wait-for-nic-detach",
description="wait for nic detach",
parent=azure_ds_reporter,
):
ifname = netlink.wait_for_nic_detach_event(nl_sock)
if ifname is None:
msg = (
"Preprovisioned nic not detached as expected. "
"Proceeding without failing."
)
report_diagnostic_event(msg, logger_func=LOG.warning)
else:
report_diagnostic_event(
"The preprovisioned nic %s is detached" % ifname,
logger_func=LOG.warning,
)
path = REPROVISION_NIC_DETACHED_MARKER_FILE
LOG.info("Creating a marker file for nic detached: %s", path)
util.write_file(
path, "{pid}: {time}\n".format(pid=os.getpid(), time=time())
)
except AssertionError as error:
report_diagnostic_event(error, logger_func=LOG.error)
raise
@azure_ds_telemetry_reporter
def wait_for_link_up(self, ifname):
"""In cases where the link state is still showing down after a nic is
hot-attached, we can attempt to bring it up by forcing the hv_netvsc
drivers to query the link state by unbinding and then binding the
device. This function attempts infinitely until the link is up,
because we cannot proceed further until we have a stable link."""
if self.distro.networking.try_set_link_up(ifname):
report_diagnostic_event(
"The link %s is already up." % ifname, logger_func=LOG.info
)
return
LOG.debug("Attempting to bring %s up", ifname)
attempts = 0
LOG.info("Unbinding and binding the interface %s", ifname)
while True:
devicename = net.read_sys_net(ifname, "device/device_id").strip(
"{}"
)
util.write_file(
"/sys/bus/vmbus/drivers/hv_netvsc/unbind", devicename
)
util.write_file(
"/sys/bus/vmbus/drivers/hv_netvsc/bind", devicename
)
attempts = attempts + 1
if self.distro.networking.try_set_link_up(ifname):
msg = "The link %s is up after %s attempts" % (
ifname,
attempts,
)
report_diagnostic_event(msg, logger_func=LOG.info)
return
if attempts % 10 == 0:
msg = "Link is not up after %d attempts to rebind" % attempts
report_diagnostic_event(msg, logger_func=LOG.info)
LOG.info(msg)
# It could take some time after rebind for the interface to be up.
# So poll for the status for some time before attempting to rebind
# again.
sleep_duration = 0.5
max_status_polls = 20
LOG.debug(
"Polling %d seconds for primary NIC link up after rebind.",
sleep_duration * max_status_polls,
)
for i in range(0, max_status_polls):
if self.distro.networking.is_up(ifname):
msg = (
"After %d attempts to rebind, link is up after "
"polling the link status %d times" % (attempts, i)
)
report_diagnostic_event(msg, logger_func=LOG.info)
LOG.debug(msg)
return
else:
sleep(sleep_duration)
@azure_ds_telemetry_reporter
def _create_report_ready_marker(self):
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,
)
@azure_ds_telemetry_reporter
def _report_ready_for_pps(self) -> None:
"""Report ready for PPS, creating the marker file upon completion.
:raises sources.InvalidMetaDataException: On error reporting ready.
"""
report_ready_succeeded = self._report_ready()
if not report_ready_succeeded:
msg = "Failed reporting ready while in the preprovisioning pool."
report_diagnostic_event(msg, logger_func=LOG.error)
raise sources.InvalidMetaDataException(msg)
self._create_report_ready_marker()
@azure_ds_telemetry_reporter
def _check_if_nic_is_primary(self, ifname):
"""Check if a given interface is the primary nic or not. If it is the