403Webshell
Server IP : 23.254.227.96  /  Your IP : 216.73.216.7
Web Server : Apache/2.4.62 (Unix) OpenSSL/1.1.1k
System : Linux hwsrv-1277026.hostwindsdns.com 4.18.0-477.13.1.el8_8.x86_64 #1 SMP Tue May 30 14:53:41 EDT 2023 x86_64
User : viralblo ( 1001)
PHP Version : 8.1.31
Disable Function : NONE
MySQL : OFF  |  cURL : ON  |  WGET : ON  |  Perl : ON  |  Python : OFF  |  Sudo : ON  |  Pkexec : ON
Directory :  /lib/python3.6/site-packages/cloudinit/sources/__pycache__/

Upload File :
current_dir [ Writeable ] document_root [ Writeable ]

 

Command :


[ Back ]     

Current File : /lib/python3.6/site-packages/cloudinit/sources/__pycache__/DataSourceAzure.cpython-36.pyc
3

��b4a�@s�UddlZddlZddlZddlZddlZddlZddljjZ	ddl
mZddlm
Z
mZddlmZmZmZmZddlmZddlZddlmZddlmZddlmZmZmZmZmZdd	lm Z m!Z!dd
l"m#Z#ddl$m%Z%m&Z&ddl'm(Z(dd
l)m*Z*ddl+m,Z,m-Z-m.Z.m/Z/m0Z0m1Z1m2Z2m3Z3m4Z4m5Z5m6Z6m7Z7m8Z8ddl9m:Z:m;Z;m<Z<ej=e>�Z?dZ@ddiZAdZBdZCdZDdZEdZFdZGdZHdZIdZJdZKdZLdZMdZNd ZOGd!d"�d"e�ZPGd#d$�d$e�ZQd%ZReeSRd&d'd(d)gZTd*d+gZUd,d-�ZVd.d/�ZWeSeSeeSd0�d1d2�ZXeSeSd3�d4d5�ZYe/eeSd6�d7d8��ZZd�eSd6�d9d:�Z[d;d<�Z\d=d>�Z]d?d@�Z^eeSd6�dAdB�Z_ej`��r�dCZCdDZDe_dE�Zaeadk	�r�e?jbdF�dGeaZBn
e?jbdH�dZReIdIeBieCdJdK�ZcdIdLdMgdJdN�ieDdOdP�gdQ�ZddRe@gZedSZfdTZgdUZhGdVdW�dWeji�ZjdXdY�ZkdZd[�Zld\d]�Zmd^d_�Znd`da�Zod�dcdd�Zpe/dedf��Zqe/dgdh��Zre/eBdidifdjdk��Zse/d�dldm��Ztdndo�Zue/dpdq��Zve/drds��Zwe/dtdu��Zxe/dvdw��Zye/dxdy��Zzd�d{d|�Z{e/d}d~��Z|e/eRfdd���Z}e/d�d���Z~e/d�d���Ze/e�d6�d�d���Z�e/e�d6�d�d���Z�e/e�d6�d�d���Z�e/ePj�eMe<difd�d���Z�e/ePj�eMdifd�d���Z�e/d�d�d���Z�d�d��Z�Gd�d��d�e��Z�Gd�d��d�e��Z�ejZ�ejej�ffgZ�d�d��Z�dS)��N)�Enum)�sleep�time)�Any�Dict�List�Optional)�minidom)�dmi)�log)�net�sources�ssh_util�subp�util)�
EventScope�	EventType)�
device_driver)�EphemeralDHCPv4�NoDHCPLeaseError)�events)�netlink)
�+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)�UrlError�readurl�retry_on_url_exc�Azurezinstance-idziid-AZURE-NODEz/dev/disk/cloud/azure_resourcez"/var/lib/dhcp/dhclient.eth0.leasesZext4z 7783-7084-3265-9085-8269-3286-77z/var/lib/cloud/data/poll_imdsz /var/lib/cloud/data/nic_detachedz"/var/lib/cloud/data/reported_readyz/var/lib/waagentz/dev/sr0�zhttp://169.254.169.254/metadataz
2019-06-01z
2021-08-01z
2021-03-01c@s*eZdZdje�Zdje�Zdje�ZdS)�MetadataTypez{}/instancez{}/instance/networkz{}/reprovisiondataN)�__name__�
__module__�__qualname__�format�IMDS_URL�ALL�NETWORK�REPROVISION_DATA�r3r3�%/usr/lib/python3.6/DataSourceAzure.pyr*Is

r*c@seZdZdZdZdZdZdS)�PPSType�NoneZRunningZSavableZUnknownN)r+r,r-�NONE�RUNNING�SAVABLE�UNKNOWNr3r3r3r4r5Osr5z/sys/firmware/acpi/tables/OEM0z"/etc/netplan/90-hotplug-azure.yamlz /usr/local/sbin/ephemeral_eth.shz+/etc/udev/rules.d/10-net-device-added.rulesz#/run/network/interfaces.ephemeral.dZ	mlx4_coreZ	mlx5_corecCs�xz|j�D]n}tjd|�r
|j�}t|�dkr
|djd�}t|�dkr
|ddkr
|dj|�r
|djd�}|dSq
Wd	S)
z�
    dev.storvsc.1.%pnpinfo:
        classid=32412632-86cb-44a2-9b5c-50d1417354f5
        deviceid=00000000-0001-8899-0000-000000000000
    Zpnpinfo�r)�=r�deviceid��.N)�
splitlines�re�search�split�len�
startswith)�
sysctl_outr=�lineZfields�columns�compsr3r3r4�"find_storvscid_from_sysctl_pnpinfousrJcCs2x,|j�D] }tj||�r
|j�}|dSq
WdS)z�
    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
    rN)r@rArBrC)�camcontrol_outZdisk_drvrG�itemsr3r3r4�find_busdev_from_disk�s
rM)rK�busdev�returncCsNxH|j�D]<}tj||�r
|jd�}t|�dkr
|djd�}|dSq
WdS)z�
    <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)
    �(r)r>�,rN)r@rArBrCrD)rKrNrGrLZdev_passr3r3r4�find_dev_from_busdev�s
rR)�macrOc	CsZt|�dkrRdj|dd�|dd�|dd�|dd�|dd�|dd�g�}|j�S)	z1Normalize mac address with colons and lower-case.��:rr)����
)rD�join�lower)rSr3r3r4�normalize_mac_address�sBr\)rOcCsdd�tj�D�S)z-Get Hyper-V NICs as normalized MAC addresses.cSs$g|]}|ddkrt|d��qS)r)�	hv_netvscr>)r\)�.0�nr3r3r4�
<listcomp>�sz1get_hv_netvsc_macs_normalized.<locals>.<listcomp>)rZget_interfacesr3r3r3r4�get_hv_netvsc_macs_normalized�sracCs<ytj|�dStjk
r6tjddj|��|SXdS)NrzFailed to execute: %s� )rZProcessExecutionError�LOG�debugrZ)�cmd�fail_retr3r3r4�execute_or_debug�s
rgcCstddgdd�S)NZsysctlzdev.storvsc�)rf)rgr3r3r3r4�get_dev_storvsc_sysctl�sricCstdddg�S)N�
camcontrol�devlistz-b)rgr3r3r3r4�get_camcontrol_dev_bus�srlcCstddg�S)Nrjrk)rgr3r3r3r4�get_camcontrol_dev�srmcCs�d}|dkrd}|d}dt|�}dj||�}t�}t||�}|sRtjd�dSt�}t�}dj|�}t||�}	|	r�t	||	�}
|
dkr�tjd	�dS|
Sd
j|�}t||�}	|	r�t	||	�}
|
dkr�tjd	�dS|
SdS)NZ00000000r>Z00000001r)Z000z{0}-{1}z#Fail to find storvsc id from sysctlz	blkvsc{0}zFail to find /dev/daXz
storvsc{0})
�strr.rirJrcrdrlrmrMrR)Zport_idZg0Zg1Zg0g1rFZ	storvscidZcamcontrol_b_outrKZblkvscZscbusxZdevnameZstorvscr3r3r4�get_resource_disk_on_freebsd�s<









roz/var/db/dhclient.leases.hn0zfreebsd-ufsr>zresource disk is not Nonez/dev/zresource disk is NoneZ
ephemeral0T)�data_dir�disk_aliases�dhclient_lease_file�apply_network_configZgpt�d)Z
table_typeZlayoutZ	overwritezephemeral0.1)Z
filesystemZdevice)�
disk_setupZfs_setup�
datasourceZnever_destroy_ntfszTemporary StorageZREDACTEDcs�eZdZdZejejejhiZ	dZ
ejZ
dZdd�Zedd��fdd	�Zd
d�Zdd
�Zeddd�eeedd�dd��Zedd�dd��Zed�dd�Zedd��Zdd�Zff�fdd�	Zedd��Zeej e!dd �d!d"��Z"d#d$�Z#ee$ed�d%d&��Z%e&e$ed'�d(d)�Z'e$ed�d*d+�Z(d,d-�Z)d.d/�Z*dad0d1�Z+ed2d3��Z,ed4d5��Z-ed6d7��Z.edd�d8d9��Z/ed:d;��Z0ed<d=��Z1ed>d?��Z2ed@dA��Z3edbeeedB�dCdD��Z4eddE�ee$eee$edF�dGdH��Z5e&eed'�dIdJ�Z6e&e&e7dK�dLdM�Z8dNdO�Z9edPdQ��Z:ee&e&ee$edR�dSdT��Z;dUdV�Z<edWdX��Z=e>dYdZ��Z?e>d[d\��Z@e>d]d^��ZAee&ed'�d_d`��ZB�ZCS)c�DataSourceAzurer(Fr>cCsttjj||||�tjj|jd�|_i|_d|_t	j
t	j|ti�t
g�|_|jjd�|_d|_d|_d|_t|_dS)NZazurerr)r
�
DataSource�__init__�os�pathrZ�seed_dir�cfg�seedr�
mergemanydict�get_cfg_by_path�DS_CFG_PATH�BUILTIN_DS_CONFIG�ds_cfg�getrr�_iso_dev�_network_config�_ephemeral_dhcp_ctxr�_wireserver_endpoint)�self�sys_cfg�distro�pathsr3r3r4ry7szDataSourceAzure.__init__N)�ci_pkl_versionrOcs"t�j|�d|_d|_t|_dS)N)�super�	_unpickler�r�rr�)r�r�)�	__class__r3r4r�EszDataSourceAzure._unpicklecCstjj|�}d||jfS)Nz%s [seed=%s])r
rx�__str__r~)r��rootr3r3r4r�LszDataSourceAzure.__str__cCsH|jdkrd}n*|jjd�r"d}n|jj�dkr6d}nd}d||jfS)z/Return the subplatform metadata source details.N�unknownz/devzconfig-disk�imdszseed-dirz%s (%s))r~rEr[)r�Zsubplatform_typer3r3r4�_get_subplatformPs
z DataSourceAzure._get_subplatform�)�iface�timeout_minutes)r�r�rOcCs�|jdk	rtd��tjd|�tjj�}|tj|d�}t|td�|_d}t	j
ddtd���x:tjj�|kr�y|jj�}PWq^t
k
r�w^Yq^Xq^W|dkr�d	|}t|tjd
�d|_t
��n|d|j_d|kr�|d|_WdQRXdS)
a�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.
        Nz/Bringing up networking when already configured.z)Requested ephemeral networking (iface=%s))Zminutes)r�Z
dhcp_log_funczobtain-dhcp-leasezobtain dhcp lease)�name�description�parentz&Failed to obtain DHCP lease (iface=%s))�logger_func�	interfacezunknown-245)r��RuntimeErrorrcrd�datetimeZutcnowZ	timedeltarrr�ReportEventStackrZobtain_leaserr#�errorr�r�)r�r�r��start�timeout�lease�msgr3r3r4�_setup_ephemeral_networking\s6



z+DataSourceAzure._setup_ephemeral_networking)rOcCs"|jdkrdS|jj�d|_dS)zTeardown ephemeral networking.N)r�Z
clean_network)r�r3r3r4�_teardown_ephemeral_networking�s

z.DataSourceAzure._teardown_ephemeral_networkingcCs|jdkp|jjdkS)z"Check if networking is configured.N)r�r�)r�r3r3r4�_is_ephemeral_networking_up�s
z+DataSourceAzure._is_ephemeral_networking_upc)Cs�i}|jd}d}d}i}d}i}i}tjjt�rLd}tdttjd��n2�x.t|j	|�D�]}	yf|	j
d�r�tj�r�tj
|	td	d
�\}}}}ntj
|	t�\}}}}|	|_nt|	�\}}}}d}|	}PWq\tk
r�td|	tjd�w\Yq\tjk
�r6td
|	tjd�ddi}ddddiii}d}w\Yq\tk
�rx}
z&d|
}t|tjd�tj|��WYdd}
~
Xq\Xq\Wtd|tjd�t|j��p�|}|�r�dnd}
y|j|
d�Wntk
�r�YnX|j��r�|jdd�}ni}|�r|�rd}t|�tj|��|j||�}|tjk�r�tj��rXd}t|tjd�tj|��|j�|tjk�rt|j �|j!�\}}}}|jdd�}|j"|d�||_#|j$||tj%|d|ig�|d��t&|�}t'|�}t(|�}|�r�tjd|�||ddd<|�rtjd|�||d d<|�r:tjd!|�||d d"<|dk�r�|d#�r�yt)|||d$�}d%|i|d#<Wn6t*k
�r�}ztd&|tjd�WYdd}~XnX|�st+|�}|�rtjd'�yt,j-dj.|j/���|d(<Wn$t*k
�rtd)tj0d�YnX|�s*d*}t|tjd�tj|��ntd+|tjd�||k�rXtd,|tjd�t1�}|�rp||d d-<|j2�|d d.<|j3dk�r�|j��r�|j4||d/�}y|j5|d0�}Wnt*k
�r�Yn.Xtjd1|�|�r�||d d2<|j6�d|_3|S)3aWalk 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.
        rpFNrhZIMDSzJReprovision marker file already present before crawling Azure metadata: %s)r�z/dev/�udf)�mtypeTz$Did not find Azure data source in %sz%s was not mountablezlocal-hostname�system_info�default_userr�zBrokenAzureDataSource: %sz!Found provisioning metadata in %sr��)r�rY)�retrieszNo OVF or IMDS availablez%Free BSD is not supported for PPS VMs)�imds_mdr�)r}�files�metadata�userdata_rawz Username retrieved from IMDS: %sz Hostname retrieved from IMDS: %sr�z(Disable password retrieved from IMDS: %sZdisable_passwordr�)�username�hostnameZ
disableSshPwdzovf-env.xmlz)Failed to construct OVF from IMDS data %szRetrieved userdata from IMDSr�zBad userdata in IMDSzNo Azure metadata foundzfound datasource in %szusing files cached in %sZrandom_seedzinstance-id)r}r�)�pubkey_infoznegotiating returned %szpublic-keys)7r�rzr{�isfile�REPROVISION_MARKER_FILEr#rcrd�list_possible_azure_dsr|rEr�
is_FreeBSD�mount_cb�load_azure_ds_dirr��NonAzureDataSource�MountFailedError�BrokenAzureDataSourcer�r
�InvalidMetaDataException�boolr�rr��get_imds_data_with_api_fallback�_determine_pps_typer5r7�_write_reprovision_markerr9�_wait_for_all_nics_ready�_reprovision�validate_imds_network_metadatar~�updater�_username_from_imds�_hostname_from_imds�_disable_password_from_imdsr�	Exception�_userdata_from_imds�base64�	b64decoderZrC�warning�_get_random_seed�_iid�_negotiated�!_determine_wireserver_pubkey_info�
_report_ready�_cleanup_markers)r��crawled_data�ddirZovf_is_accessibleZmetadata_source�mdr�r}r��src�excr�Zrequires_imds_metadatar�r��pps_typeZ
imds_usernameZ
imds_hostnameZimds_disable_password�contents�eZ
imds_userdatar~r��ssh_keysr3r3r4�crawl_metadata�s


 









zDataSourceAzure.crawl_metadatacCs
t|j�S)z@Check platform environment to report if this datasource may run.)�_is_platform_viabler|)r�r3r3r4r�wsz#DataSourceAzure._is_platform_viablecstt|�j|�tj|_dS)z.Reset any cached class attributes to defaults.N)r�rw�clear_cached_attrsr
�UNSET�_metadata_imds)r�Z
attr_defaults)r�r3r4r�{sz"DataSourceAzure.clear_cached_attrsc5Cs�|j�sdSy
t�Wn.tk
rD}ztjd|�WYdd}~XnXy
t�Wn.tk
r~}ztjd|�WYdd}~XnXt|jj_	z\yt
jtjd|j
d�}Wn>tk
r�}z"td|tjd�|jtd	�dSd}~XnXWd|j�X|j�r|jjd
k�r|jjd��rt�t}tjj|��rVtd|tjd�t
j|d
tg�|_ntd|tjd�|d
|_|dd|_t
j|dtg�|_ |d|_!t
j"|jt#i�}t
j||jg�|_t$|jd|ddd�dS)z�Crawl and process datasource metadata caching metadata as attrs.

        @return: True on success, False on error, invalid or disabled
            datasource.
        Fz Failed to get boot telemetry: %sNz$Failed to get system information: %szCrawl of metadata service)�logfuncr��funcz"Could not crawl Azure metadata: %s)r�)r�ZubunturszXEphemeral resource disk '%s' exists. Merging default Azure cloud ephemeral disk configs.r}zdEphemeral resource disk '%s' does not exist. Not merging default Azure cloud ephemeral disk configs.r�r�r�rpr�i�)�dirmodeT)%r�rr�rcr�r �BLACKLIST_DRIVERSr��
networking�blacklist_driversr�log_timerdr�r#r��_report_failurerr�r�r�r��*maybe_remove_ubuntu_network_config_scripts�RESOURCE_DISK_PATHrzr{�existsr�#BUILTIN_CLOUD_EPHEMERAL_DISK_CONFIGr}r��DEFAULT_METADATAr�r�r�r��write_files)r�r�r��devpathZuser_ds_cfgr3r3r4�	_get_data�sb







zDataSourceAzure._get_data)�md_type�exc_cb�infinitecCs�x�t|�D]t}ytjdt�td|t|d�Stk
r|}z6tjdt�|jdkrldjt�}t	|tjd�PWYdd}~Xq
Xq
Wtjd	t�t||t||d
�S)a=
        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.
        zAttempting IMDS api-version: %sr)r�r��api_versionr�z"UrlError with IMDS api-version: %si�z!Fall back to IMDS api-version: {})r�NzUsing IMDS api-version: %s)r�r�r�r�r�)
�rangerc�info�
IMDS_VER_WANT�get_metadata_from_imdsr%�coder.�IMDS_VER_MINr#)r�r�r�r�r��_�err�log_msgr3r3r4r��s,
z/DataSourceAzure.get_imds_data_with_api_fallbackcCs|jdj|�S)Nrq)r�r�)r�r�r3r3r4�device_name_to_devicesz%DataSourceAzure.device_name_to_devicecCs2y|j|jd�Sttfk
r(YnX|j�S)z+
        Retrieve public SSH keys.
        r�)�_get_public_keys_from_imdsr��KeyError�
ValueError�_get_public_keys_from_ovf)r�r3r3r4�get_public_ssh_keyss
z#DataSourceAzure.get_public_ssh_keys)r�rOcCs�ydd�|ddD�}Wn(tk
rBd}t|tjd��YnXtdd�|D��rpd	}t|tjd�t|��d
jt|��}t|tjd�|S)z�Get SSH keys from IMDS metadata.

        :raises KeyError: if IMDS metadata is malformed/missing.
        :raises ValueError: if key format is not supported.

        :returns: List of keys.
        cSsg|]}|d�qS)ZkeyDatar3)r^Z
public_keyr3r3r4r`sz>DataSourceAzure._get_public_keys_from_imds.<locals>.<listcomp>�computeZ
publicKeysz"No SSH keys found in IMDS metadata)r�css|]}t|d�VqdS))�keyN)�_key_is_openssh_formatted)r^rr3r3r4�	<genexpr>!sz=DataSourceAzure._get_public_keys_from_imds.<locals>.<genexpr>zKey(s) not in OpenSSH formatzRetrieved {} keys from IMDS)rr#rcrd�anyrr.rD)r�r�r�rr3r3r4rsz*DataSourceAzure._get_public_keys_from_imdscCsZg}y*|jd}djt|��}t|tjd�Wn&tk
rTd}t|tjd�YnX|S)zYGet SSH keys that were fetched from wireserver.

        :returns: List of keys.
        zpublic-keyszRetrieved {} keys from OVF)r�zNo keys available from OVF)r�r.rDr#rcrdr)r�r�rr3r3r4r*s
z)DataSourceAzure._get_public_keys_from_ovfcCs|jS)N)r})r�r3r3r4�get_config_obj:szDataSourceAzure.get_config_objcCstj|j��S)N)r
Zinstance_id_matches_system_uuidZget_instance_id)r�r�r3r3r4�check_instance_id=sz!DataSourceAzure.check_instance_idcCsxtjj|jjd�d�}tjd�}|dkr0td��|j�}tjj	|�rtt
j|�j�}|j�|krb|St
|j�|�rt|S|S)N�datazinstance-idzsystem-uuidzfailed to read system-uuid)rzr{rZr�Z	get_cpathr
�
read_dmi_datar�r[r�r�	load_file�stripr!)r�ZpreviousZ
prev_iid_pathZsystem_uuidZiidr3r3r4r�As
zDataSourceAzure._iidcCs�y�d}tjddtd��tj|�}WdQRX|dkrHd}t|tjd�ntd|tjd�t}tj	d|�t
j|d	jt
j�t�d
��Wn6tk
r�}ztt|�tjd��WYdd}~XnXdS)z�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.
        Nzwait-for-nic-detachzwait for nic detach)r�r�r�zHPreprovisioned nic not detached as expected. Proceeding without failing.)r�z%The preprovisioned nic %s is detachedz+Creating a marker file for nic detached: %sz{pid}: {time}
)�pidr)rr�rrZwait_for_nic_detach_eventr#rcr��$REPROVISION_NIC_DETACHED_MARKER_FILEr�r�
write_filer.rz�getpidr�AssertionErrorrnr�)r��nl_sock�ifnamer�r{r�r3r3r4�_wait_for_nic_detachXs(

z$DataSourceAzure._wait_for_nic_detachc	Csh|jjj|�r$td|tjd�dStjd|�d}tjd|��x tj|d�}|dksdt	|t
�rptd	|��|jd
�}t
jd|�t
jd|�|d
}|jjj|�r�d||f}t|tjd�dS|ddkr�d|}t|tjd�tj|�d}d}tjd||�xTtd|�D]F}|jjj|��rRd||f}t|tjd�tj|�dSt|��qWqDWdS)ahIn 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.zThe link %s is already up.)r�NzAttempting to bring %s uprz&Unbinding and binding the interface %szdevice/device_idFzUnable to read device ID: %sz{}z'/sys/bus/vmbus/drivers/hv_netvsc/unbindz%/sys/bus/vmbus/drivers/hv_netvsc/bindr>z#The link %s is up after %s attemptsrYz*Link is not up after %d attempts to rebindg�?r�z8Polling %d seconds for primary NIC link up after rebind.zNAfter %d attempts to rebind, link is up after polling the link status %d times)r�r�Ztry_set_link_upr#rcr�rdrZread_sys_net�
isinstancernr�rrrr�Zis_upr)	r�rZattemptsZ	device_idZ
devicenamer�Zsleep_durationZmax_status_polls�ir3r3r4�wait_for_link_up}sP




z DataSourceAzure.wait_for_link_upcCs>t}tjd|�tj|djtj�t�d��t	dtj
d�dS)Nz*Creating a marker file to report ready: %sz{pid}: {time}
)rrzRSuccessfully created reported ready marker file while in the preprovisioning pool.)r�)�REPORTED_READY_MARKER_FILErcr�rrr.rzrrr#rd)r�r{r3r3r4�_create_report_ready_marker�sz+DataSourceAzure._create_report_ready_markercCsZy|j�Wn@tk
rL}z$d}t|tjd�tj|�|�WYdd}~XnX|j�dS)z�Report ready for PPS, creating the marker file upon completion.

        :raises sources.InvalidMetaDataException: On error reporting ready.
        z9Failed reporting ready while in the preprovisioning pool.)r�N)r�r�r#rcr�r
r�r)r�r�r�r3r3r4�_report_ready_for_pps�sz%DataSourceAzure._report_ready_for_ppscs�d}d}d}d�d�d�|j|dd����fdd�}y|jdtj|d	d
�}Wn0tk
r~}ztjd||�WYdd}~XnX|r�tjd|�d	}t|d
�}t	d|tjd�n|j
�||fS)z�Check if a given interface is the primary nic or not. If it is the
        primary nic, then we also get the expected total nic count from IMDS.
        IMDS will process the request and send a response only for primary NIC.
        Fr>Nrr�)r�r�cs��d���krT�d9�td|�ftjd�t|t�rTtd||j|jftjd�|jr~t|jtjtj	f�r~�d��dkSdS)Nr>r)z>Ran into exception when attempting to reach %s after %d polls.)r�z4poll IMDS with %s failed. Exception: %s and code: %srYT)
r#rcr�rr%�causer��requestsZTimeout�ConnectionError)r�r�)�expected_errors_count�metadata_logging_threshold�metadata_poll_countr3r4�network_metadata_exc_cb�s"


zIDataSourceAzure._check_if_nic_is_primary.<locals>.network_metadata_exc_cbT)r�r�r�r�z�Failed to get network metadata using nic %s. Attempt to contact IMDS failed with error %s. Assuming this is not the primary nic.z%s is the primary nicr�zExpected nic count: %d)r����)r�r�r*r1r�rcr�r�rDr#r�)r�rZ
is_primary�expected_nic_countr�r&r�r3)r#r$r%r4�_check_if_nic_is_primary�s8#z(DataSourceAzure._check_if_nic_is_primarycCs�tjd�y�g}d}d}x�d}tjddt|�td��tj||�}WdQRX|j|�t	d|tjd	�|j
|�|s�tjd
|�|j|�\}}|d
krt|�|krtjd�PqWWn4tk
r�}zt	t
|�tjd	�WYdd}~XnXdS)z�Wait until all the expected nics for the vm are hot-attached.
        The expected nic count is obtained by requesting the network metadata
        from IMDS.
        z#Waiting for nics to be hot-attachedFr>Nzwait-for-nic-attachz4wait for nic attach after %d nics have been attached)r�r�r�zDetected nic %s attached.)r�z!Checking if %s is the primary niczFound all the nics for this VM.r'r')rcr�rr�rDrrZwait_for_nic_attach_event�appendr#rr)rrnr�)r�rZ
nics_foundZprimary_nic_foundr(rr�r3r3r4�_wait_for_hot_attached_nics:s6





z+DataSourceAzure._wait_for_hot_attached_nicscCs�d}z�y�tj�}ttjjt��}tjjt�s4|j�ttjjt��}|sdt	j
d�|j�|j|�|j
sv|j|�ntd|t	j
d�Wn8tjk
r�}ztt|�t	jd��WYdd}~XnXWd|r�|j�XdS)aWait for nic(s) to be hot-attached. There may be multiple nics
        depending on the customer request.
        But only primary nic would be able to communicate with wireserver
        and IMDS. So we detect and save the primary nic to be used later.
        NzNIC has not been detached yet.z�Skipping waiting for nic attach because we already have a fallback interface. Report Ready marker present before detaching nics: %s)r�)r�create_bound_netlink_socketr�rzr{r�rrrrcr�r�rZfallback_interfacer+r#�NetlinkCreateSocketErrorrnr��close)r�rZreport_ready_marker_presentZhas_nic_been_detachedr�r3r3r4r�ys0

z(DataSourceAzure._wait_for_all_nics_readyc
>s�djtjjt�}ddi}d}ttjjt	��}d�_
d�_d}d}�fdd�}|�r��j�sh�j
d	d
��z0y��jdks��jjdkr�td���jj}tj�}�j�tjd|�tjd
dtd��Nytj||�Wn6tk
�r}	ztd|	tjd�WYdd}	~	XnXWdQRXWn�tjk
�rZ}	z$td|	tjd�tj d�|	�WYdd}	~	Xn>t!k
�r�}	z tdtjd�tj d�|	�WYdd}	~	XnXWd|�r�|j"�X�j#�x�|�sX�j��s�|d7}y�j
dd
�Wnt!k
�r��w�YnXtjddtd��Dyt$|t%||ddd�j&}Wn"t'k
�rH�j#��w�YnXWdQRX�q�Wtd|tjd�td�jtjd�|S)ztPoll IMDS for the new provisioning data until we get a valid
        response. Then return the returned JSON object.z{}?api-version={}�Metadata�trueNr>rcs�t|t�r�|jdkrj�j�jkrX�jd9_tjd�j�td||j|jftjd��jd7_dStd||j|jftj	d�d	Std
|tj	d�d	S)N��r)z:Backing off logging threshold for the same exception to %dz4poll IMDS with %s failed. Exception: %s and code: %s)r�r>TFz1poll IMDS failed with an unexpected exception: %s)r1r2)
rr%r��imds_poll_counter�imds_logging_thresholdrcrdr#r r�)r�Z	exception)r�r3r4r��s.




z*DataSourceAzure._poll_imds.<locals>.exc_cbr�)r�zMissing ephemeral contextz#Wait for vnetswitch to happen on %sz!wait-for-media-disconnect-connectzwait for vnet switch)r�r�r�z'Error while waiting for vnet switch: %s)r�z)Failed to create bound netlink socket: %sz2Failed to report ready while in provisioning pool.z&DHCP failed while in provisioning poolr�zget-reprovision-data-from-imdszget reprovision data from imdsTF)r��headers�exception_cbr�Zlog_req_respz#attempted dhcp %d times after reusez polled imds %d times after reuse)(r.r*r2�valuer�r�rzr{r�rr4r3r�r�r�r�r�rr,rrcrdrr�rZ!wait_for_media_disconnect_connectrr#r�r-r�r
r�rr.r�r&�IMDS_TIMEOUT_IN_SECONDSr�r%)
r��urlr5rZreport_readyZ
dhcp_attemptsZreprovision_datar�r�r�r3)r�r4�
_poll_imds�s�$

*







zDataSourceAzure._poll_imds)r�rOc Cs�|j�r^y tdtjd�t|j|d�dStk
r\}ztd|tjd�WYdd}~XnXyNtdtjd�|j�y|j	dd	�Wnt
k
r�YnXt|j|d�dStk
r�}ztd
|tjd�WYdd}~XnXdS)z�Tells the Azure fabric that provisioning has failed.

        @param description: A description of the error encountered.
        @return: The success status of sending the failure signal.
        z>Using cached ephemeral dhcp context to report failure to Azure)r�)�	dhcp_optsr�Tz@Failed to report failure using cached ephemeral dhcp context: %sNz3Using new ephemeral dhcp to report failure to Azurer�)r�z5Failed to report failure using new ephemeral dhcp: %sF)r�r#rcrdr$r�r�r�r�r�r)r�r�r�r3r3r4r�Cs>

zDataSourceAzure._report_failure)r�)r�rOcCsZytd|j|j|d�}Wn6tk
rN}ztd|tjd��WYdd}~XnXd|_|S)z�Tells the fabric provisioning has completed.

        :param pubkey_info: Fingerprints of keys to request from Wireserver.

        :raises Exception: if failed to report.

        :returns: List of SSH keys, if requested.
        N)Zfallback_lease_filer;Ziso_devr�zQError communicating with Azure fabric; You may experience connectivity issues: %s)r�)rr�r�r�r#rcr�)r�r�rr�r3r3r4r�ts
zDataSourceAzure._report_readycCsHy|dddStk
rB}ztd|tjd�dSd}~XnXdS)NZextendedrZppsTypez2Could not retrieve pps configuration from IMDS: %s)r�)r�r#rcrd)r�r�r�r3r3r4�_ppstype_from_imds�s
z"DataSourceAzure._ppstype_from_imds)�ovf_cfgr�rOcCs�tjjt�rtj}np|jdd�tjjks:|j	|�tjjkrBtj}nB|jd�dksv|jdd�tj
jksv|j	|�tj
jkr~tj
}ntj}td|jt
jd�|S)z@Determine PPS type using OVF, IMDS data, and reprovision marker.�PreprovisionedVMTypeN�PreprovisionedVmTzPPS type: %s)r�)rzr{r�r�r5r:r�r9r7r<r8r7r#rcr�)r�r=r�r�r3r3r4r��s

z#DataSourceAzure._determine_pps_typecCs,tjdt�tjtdjtj�t�d��dS)z9Write reprovision marker file in case system is rebooted.z'Creating a marker file to poll imds: %sz{pid}: {time}
)rrN)	rcr�r�rrr.rzrr)r�r3r3r4r��s
z)DataSourceAzure._write_reprovision_markercCsB|j�}tjddtd�� t|�\}}}|||d|ifSQRXdS)zrInitiate the reprovisioning workflow.

        Ephemeral networking is up upon successful reprovisioning.
        zreprovisioning-read-azure-ovfz$read azure ovf during reprovisioning)r�r�r�zovf-env.xmlN)r:rr�r�read_azure_ovf)r�r�r��udr}r3r3r4r��s
zDataSourceAzure._reprovision)r}r�rOcCsdd}y|j|�WnLttfk
r^|jdd�}dj|dk	rFt|�nd�}t|tjd�YnX|S)z�Determine the fingerprints we need to retrieve from Wireserver.

        :return: List of keys to request from Wireserver, if any, else None.
        N�_pubkeysz"Retrieved {} fingerprints from OVFr)r�)	rrrr�r.rDr#rcrd)r�r}r�r�rr3r3r4r��sz1DataSourceAzure._determine_wireserver_pubkey_infocCs"tjt�tjt�tjt�dS)zCleanup any marker files.N)r�del_filerr�r)r�r3r3r4r��s

z DataSourceAzure._cleanup_markerscCs0zt||jjtd�d�Wdt|jd�XdS)NF)�is_new_instance�
preserve_ntfsZdef_log_file)�address_ephemeral_resizer�r��DS_CFG_KEY_PRESERVE_NTFSr"r�)r�r}rDr3r3r4�activate�szDataSourceAzure.activatecCs|jjdi�jdi�jd�S)Nr�rZplatformFaultDomain)r�r�)r�r3r3r4�availability_zone�sz!DataSourceAzure.availability_zonecCs<|js|jtjkr6|jjd�r(|j}nd}t|�|_|jS)asGenerate 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.
        rsN)r�r
r�r�r�r��parse_network_config)r�Znc_srcr3r3r4�network_config�s

zDataSourceAzure.network_configcCs|jjdi�jdi�jd�S)Nr�r�location)r�r�)r�r3r3r4�regionszDataSourceAzure.regioncs�t�}y|d}dd�|dD��Wn,tk
rPtd|jd�tjd�dSX�fdd�|D�}|sld	Std
||ftjd�|js�|jjr�dStj	|jj�}|s�t
|t�r�dSt|�}||kr�td||ftjd�dS)z=Validate IMDS network config and report telemetry for errors.�networkcSsg|]}t|d��qS)�
macAddress)r\)r^rr3r3r4r`szBDataSourceAzure.validate_imds_network_metadata.<locals>.<listcomp>r�z6IMDS network metadata has incomplete configuration: %r)r�Fcsg|]}|�kr|�qSr3r3)r^�m)�	imds_macsr3r4r`#sTz>IMDS network metadata is missing configuration for NICs %r: %rz3IMDS network metadata is missing primary NIC %r: %r)
rarr#r�rcr�r�r�rZget_interface_macrrnr\)r�r�Z
local_macsrKZmissing_macsZprimary_macr3)rQr4r�s<



z.DataSourceAzure.validate_imds_network_metadata)N)N)Dr+r,r-Zdsnamerr1rZBOOT_NEW_INSTANCE�BOOTZdefault_update_eventsr�r
r�r�Z_ci_pkl_versionry�intr�r�r�rrrnr�r�r�r�r�r�r�r�r*r0r'r�rrr�dictrrrr
r�rrrrr)r+r�r:r�r�r<r5r�r�r�r�r�rH�propertyrIrKrMr��
__classcell__r3r3)r�r4rw*s~
3VU$
%B
_?60

rwcCs*y|dddStk
r$dSXdS)Nr�	osProfileZ
adminUsername)r)�	imds_datar3r3r4r�Asr�cCs&y|ddStk
r dSXdS)NrZuserData)r)rXr3r3r4r�Hsr�cCs*y|dddStk
r$dSXdS)NrrWZcomputerName)r)rXr3r3r4r�Osr�cCs.y|ddddkStk
r(dSXdS)NrrWZdisablePasswordAuthenticationr0)r)rXr3r3r4r�Vs
r�cCsFd|j�krdStj�}y|j|�}Wntk
r:dSX|jdk	S)z?
    Validate whether or not the key is OpenSSH-formatted.
    z
FN)rrZAuthKeyLineParser�parse�	TypeErrorZkeytype)r�parserZaklr3r3r4r	`sr	�cCsdx^dD]V}g}xDtd|�D]6}||t|�}tjj|�r|j|tjj|�f�qW|r|SqWgS)N�-part�prhr>)r]r^rh)r�rnrzr{r�r*�realpath)r�ZmaxnumZsuff�foundZpnumZppathr3r3r4�_partitions_on_deviceqs
racCs*tjddd�}tjd|�tjj|�|kS)Nz	TYPE=ntfsT)Zno_cachezntfs_devices found = %s)r�find_devs_withrcrdrzr{r_)r�Zntfs_devicesr3r3r4�_has_ntfs_filesystem~srccCs�|rddjt�tf}d|fStjj|�s6dd|fStjd|tjj|��t	|�}t
|�dkrldd|fSt
|�dkr�d	|d
jdd�|D��f}d|fSt
|�dkr�|d
\}}n|d\}}t|�s�d|||f}d|fStdd��}d|||f}t
jddtd���}ytj||dddid�}	WnTtjk
�rz}
z4d|_dt|
�k�r\d|dfSd|d||
ffSd}
~
XnX|	dk�r�d|	|_tjddjt�t�d|d |	fSWdQRXd|d!fS)"a�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.z:config says to never destroy NTFS (%s.%s), skipping checksr?Fzdevice %s does not existzResolving realpath of %s -> %srzdevice %s was not partitionedr)z&device %s had 3 or more partitions: %srbcSsg|]}|d�qS)r>r3)r^r^r3r3r4r`�sz*can_dev_be_reformatted.<locals>.<listcomp>r>z5partition %s (%s) on device %s was not ntfs formattedcs&tdg��t�fdd�tj|�D��S)Nzdataloss_warning_readme.txtcsg|]}|j��kr|�qSr3)r[)r^�f)�ignoredr3r4r`�sz?can_dev_be_reformatted.<locals>.count_files.<locals>.<listcomp>)�setrDrz�listdir)Zmpr3)rer4�count_files�s
z+can_dev_be_reformatted.<locals>.count_filesz1partition %s (%s) on device %s was ntfs formattedzmount-ntfs-and-count)r�r�r�ZntfsZLANG�C)r�Zupdate_env_for_mountzcannot mount ntfszunknown filesystem type 'ntfs'Tz^ but this system cannot mount NTFS, assuming there are no important files. Formatting allowed.z but mount of %s failed: %sNzmounted and counted %d fileszxit looks like you're using NTFS on the ephemeral disk, to ensure that filesystem does not get wiped, set %s.%s in configz but had %d files on it.z3 and had no important files. Safe for reformatting.)rZr�rGrzr{r�rcrdr_rarDrcrrr�rrr�r�r�rnr�)r�rEr�Z
partitionsZ	cand_partZ	cand_pathrh�bmsg�evtZ
file_countr�r3r3r4�can_dev_be_reformatted�sp
 

rlFc	Cs�tjj|�s"td|tjd�dStd|tjd�d}d}|rJd\}}nt||�\}}tjd||�|sndSx�dD]~}d
|}d||f}tjj|�r�ytj|�tjd|�Wn0tk
r�}ztj	d
||�WYdd}~XnXqttjd|�qtWdS)Nz,Ephemeral resource disk '%s' does not exist.)r�z$Ephemeral resource disk '%s' exists.FT�First instance boot.zreformattable=%s: %sru�mountsz#/var/lib/cloud/instance/sem/config_zMarker "%s" for module "%s"z%s removed.z%s: remove failed! (%s)z%s did not exist.)Trm)rurn)
rzr{r�r#rcrdrl�unlinkr�r�)	r�rDrE�resultr��modZsempathrjr�r3r3r4rF�s6




"rFcCsndd�}|sdS|si}tj||�xD|j�D]8\}}tjj||�}d|krV|||�}tj||dd�q.WdS)NcSsfy@tj|�}x*|j�D]}d|jkr|jtkrt|_qWtj|�Stk
r`tj	d|�|SXdS)z>Azure provides the UserPassword in plain text. So we redact itZUserPasswordz#failed to redact userpassword in %sN)
�ETZ
fromstring�iter�tag�text�DEF_PASSWD_REDACTIONZtostringr�rcZcritical)Zcnt�fnamer��elemr3r3r4�_redact_passwords




z%write_files.<locals>._redact_passwordzovf-env.xmli�)�filename�content�mode)rZ
ensure_dirrLrzr{rZr)Zdatadirr�r�ryr�r{rwr3r3r4r�s
r�cCs6g}|j�s|Sx |jD]}||�r|j|�qW|S)N)�
hasChildNodes�
childNodesr*)ZnodeZfilter_func�ret�childr3r3r4�
find_child7sr�c
Cst|dd��}t|�dkrgSt|�dkr:tdt|���|d}t|dd��}t|�dkr`gSg}tjj}x�|D]�}|j�s�qrdddd�}xn|jD]d}|j|ks�|j	r�q�|j	j
�}	|	|j�kr�q�t|j�dks�|jdj|kr�q�|jdjj
�||	<q�W|j|�qrW|S)	NcSs
|jdkS)NZ
PublicKeys)�	localName)r_r3r3r4�<lambda>Nsz(load_azure_ovf_pubkeys.<locals>.<lambda>rr>z%Multiple 'PublicKeys'(%s) in SSH nodecSs
|jdkS)NZ	PublicKey)r�)r_r3r3r4r�Wsrh)Zfingerprintr{r7)r�rDr�r	ZDocument�	TEXT_NODEr}r~�nodeTyper�r[�keys�	wholeTextrr*)
Zsshnode�resultsZpubkeys_nodeZpubkeysr`Z	text_nodeZpk_nodeZcurr�r�r3r3r4�load_azure_ovf_pubkeysAs8


r�cCs@ytj|�}WnBtk
rP}z&d|}t|tjd�t|�|�WYdd}~XnXt|jdd��}t	|�dkrvt
d��t	|�dkr�tdt	|���|d}t|d	d��}t	|�dkr�t
d
��t	|�dkr�tdt	|�df��|d}|j�s�td
��d}dii}	i}
d}d}d}
�x�|jD�]�}|j
|jk�s|j�r<�q|jj�}d}d}t	|j�dk�r�|jdj
|jk�r�d}|jdj}tdd�|jj�D��}|dk�s�|dk�r�|jd�d*k�r�tjdj|j���}n|}n�|dk�r�|}
n�|dk�r�|}n�|dk�r||	d<n�|dk�rZ|jd�d+k�r>tjdj|j���}n|}ttj|id�i|
d<nX|d k�rrt|�|
d!<n@|d"k�r�tj|�|
d#<n&|�r||k�r�||	|<n||	d|<�qWi}|
�r�|
|d$<|�r�d|d%<t|k�r�t |�|d&<|
d'<|�rd(|i|
d)<d#|
k�r |�r d|
d#<t!|�}tj"|
|g�}
|	||
fS),NzInvalid ovf-env.xml: %s)r�cSs
|jdkS)NZProvisioningSection)r�)r_r3r3r4r��sz read_azure_ovf.<locals>.<lambda>rzNo ProvisioningSectionr>z$found '%d' ProvisioningSection itemscSs
|jdkS)N�!LinuxProvisioningConfigurationSet)r�)r_r3r3r4r��sz$No LinuxProvisioningConfigurationSetzfound '%d' %ssr�z#no child nodes of configuration setZseedfromZ
azure_datarhFTcSsg|]\}}||f�qSr3r3)r^�k�vr3r3r4r`�sz"read_azure_ovf.<locals>.<listcomp>ZuserdataZ
customdata�encodingr�r�Zuserpasswordr�zlocal-hostname�dscfg)�defaultrvZsshrBZ disablesshpasswordauthenticationZ
ssh_pwauthr�Zlock_passwdZpasswd�passwordr�r�)Nr�)Nr�)#r	ZparseStringr�r#rcr�r�r��documentElementrDr�r}r~r�r�r�r[r�rTZ
attributesrLr�r�r�rZrC�DS_NAMErZ	load_yamlr�Zis_falserv�encrypt_pass�_get_preprovisioning_cfgsr)r��domr�Z	error_strr�ZprovSectionZ
lpcs_nodesZlpcsZmd_propsr�r}rAr�r�r�r�Zsimpler7Zattrsr�ZdefuserZpreprovisioning_cfgr3r3r4r@ys�











r@cCs�ddd�}t|jdd��}|s,t|�dkr:tjd�|St|ddd��}|s^t|�dkrltjd	�|St|�|d
<t|�|d<|S)a�Read the preprovisioning related flags from ovf and populates a dict
    with the info.

    Two flags are in use today: PreprovisionedVm bool and
    PreprovisionedVMType enum. In the long term, the PreprovisionedVm bool
    will be deprecated in favor of PreprovisionedVMType string/enum.

    Only these combinations of values are possible today:
        - PreprovisionedVm=True and PreprovisionedVMType=Running
        - PreprovisionedVm=False and PreprovisionedVMType=Savable
        - PreprovisionedVm is missing and PreprovisionedVMType=Running/Savable
        - PreprovisionedVm=False and PreprovisionedVMType is missing

    More specifically, this will never happen:
        - PreprovisionedVm=True and PreprovisionedVMType=Savable
    FN)r?r>cSs
|jdkS)NZPlatformSettingsSection)r�)r_r3r3r4r��sz+_get_preprovisioning_cfgs.<locals>.<lambda>rz!PlatformSettingsSection not foundcSs
|jdkS)NZPlatformSettings)r�)r_r3r3r4r�szPlatformSettings not foundr?r>)r�r�rDrcrd�_get_preprovisionedvm_cfg_value�#_get_preprovisionedvmtype_cfg_value)r�r}Zplatform_settings_section�platform_settingsr3r3r4r��s"





r�cCs^d}t|ddd��}|s(t|�dkr6tjd�|Stj|djj�}td|tj	d�|S)NFrcSs
|jdkS)Nr?)r�)r_r3r3r4r�sz1_get_preprovisionedvm_cfg_value.<locals>.<lambda>zPreprovisionedVm not foundzPreprovisionedVm: %s)r�)
r�rDrcrdrZtranslate_bool�
firstChild�	nodeValuer#r�)r�ZpreprovisionedVmZpreprovisionedVmValr3r3r4r�s
r�cCsfd}t|ddd��}|s6t|�dks6|djdkrDtjd�|S|djj}td|tjd�|S)NrcSs
|jdkS)Nr>)r�)r_r3r3r4r�=sz5_get_preprovisionedvmtype_cfg_value.<locals>.<lambda>zPreprovisionedVMType not foundzPreprovisionedVMType: %s)r�)r�rDr�rcrdr�r#r�)r�ZpreprovisionedVMTypeZpreprovisionedVMTypeValr3r3r4r�/s
r��$6$cCstj||tjdd��S)Nr\)Zstrlen)�cryptrZrand_str)r�Zsalt_idr3r3r4r�Psr�cCsHy"t|��}|jd�dSQRXWn tk
rBtjd|�YnXdS)z;Return boolean indicating path to cdrom device has content.iTNzcdrom (%s) is not configuredF)�open�read�IOErrorrcrd)�	cdrom_dev�fpr3r3r4�_check_freebsd_cdromTs

r�cCs*|dkrdStj|ddd�}tj|�j�S)zIReturn content random seed file if available, otherwise,
    return None.NTF)�quiet�decode)rrr�Z	b64encoder�)�sourcer~r3r3r4r�`sr�ccsX|VtVtj�r(d}t|�rJ|Vn"x dD]}tjd|�EdHq.W|rT|VdS)Nz/dev/cd0�iso9660r�zTYPE=%s)r�r�)�DEFAULT_PROVISIONING_ISO_DEVrr�r�rb)r~�	cache_dirr�Zfstyper3r3r4r�vs
r�cCs^tjj|d�}tjj|�s"td��t|d��}|j�}WdQRXt|�\}}}|||d|ifS)Nzovf-env.xmlzNo ovf-env file found�rb)rzr{rZr�r�r�r�r@)Z
source_dirZovf_filer�r�r�rAr}r3r3r4r��sr�cCs�|tjkrJ|rJyt|�Stk
rH}ztjdt|��WYdd}~XnXyt�Stk
r�}ztjdt|��WYdd}~XnXiS)a_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.
    z?Failed generating network config from IMDS network metadata: %sNz-Failed generating fallback network config: %s)r
r��+_generate_network_config_from_imds_metadatar�rcr�rn�-_generate_network_config_from_fallback_config)�
imds_metadatar�r3r3r4rJ�s	"rJcCs�did�}|d}�xzt|d�D�]h\}}d}dj|d�}d|d	d
i}d|dd�}x�d%D]�}	|j|	i�jdg�}
|
s�tjd|	|�q^d}|	d
kr�d}nd}|
r�d|d<||d<x`|
d	d�D]P}||	ddjd|�}
|d}|jd��s�g|d<|djdj||
d��q�Wq^W|�r||�r|t|d�}|jd|j�i|d��t	|�}|�rn|d k�rn||d!d"<||d#|<q"tjd$|||�q"W|S)&aConvert 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.
    r))�version�	ethernetsrNr�Fzeth{idx})�idxzroute-metricr>rtT)Zdhcp4zdhcp4-overrides�dhcp6�ipv4�ipv6Z	ipAddresszNo %s addresses found for: %rZ24Z128r�zdhcp6-overridesNZsubnetr�prefixZprivateIpAddress�	addressesz
{ip}/{prefix})Zipr�rOZ
macaddress)�matchzset-namer]r��driverr�z<No configuration for: %s (dev_config=%r) (has_ip_address=%r))r�r�)
�	enumerater.r�rcrdr*r\r�r[r)r�Z	netconfigZnetwork_metadatar�ZintfZhas_ip_addressZnicnameZ
dhcp_overrideZ
dev_configZ	addr_typer�Zdefault_prefixZaddrZ	netPrefixZ	privateIprSr�r3r3r4r��sX


r�cCstjtdd�}|dkriS|S)z�Generate fallback network config excluding blacklisted devices.

    @return: Dictionary containing network version 2 standard configuration.
    T)r�Z
config_driverN)rZgenerate_fallback_configr�)r}r3r3r4r��s

r�cCsbtjdt|||||fd�}ytjf|�Stk
r\}ztd|tjd��WYdd}~XnXdS)a�Query Azure's instance metadata service, returning a dictionary.

    For more info on IMDS:
        https://docs.microsoft.com/en-us/azure/virtual-machines/windows/instance-metadata-service

    @param retries: The number of retries of the IMDS_URL.
    @param md_type: Metadata type for IMDS request.
    @param api_version: IMDS api-version to use in the request.

    @return: A dict of instance metadata containing compute and network
        info.
    z/Crawl of Azure Instance Metadata Service (IMDS))r�r�r��argsz$exception while getting metadata: %s)r�N)rcrd�_get_metadata_from_imdsrr�r�r#r�)r�r�r�r�r��kwargsr�r3r3r4r�	s
r�c&Csdj|j|�}ddi}|tkr0|tjkr0|d}yt|t||||d�}WnPtk
r�}z4t|t	�rr|j
dkrr�ntd|tj
d�iSWYdd}~XnXyd	d
lm}	|	}
Wntk
r�t}
YnXytj|j�S|
k
�r}ztd|j|ftj
d�WYdd}~XnXiS)Nz{}?api-version={}r/r0z&extended=true)r�r5r�r6r�i�zBIgnoring IMDS instance metadata. Get metadata from IMDS failed: %s)r�r)�JSONDecodeErrorz`Ignoring non-json IMDS instance metadata response: %s. Loading non-json IMDS response failed: %s)r.r7�IMDS_EXTENDED_VER_MINr*r0r&r8r�rr%r�r#rcr�Zjson.decoderr��ImportErrorrrZ	load_jsonr�)r�r�r�r�r�r9r5Zresponser�r�Zjson_decode_errorr3r3r4r�(	sB


r�cCsl|st}d}xZ|D]R}tjj|�r|sBtjdtjjtj	jg�d}tjj
|�rZtj|�qtj
|�qWdS)a(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.
    Fz|Removing Ubuntu extended network scripts because cloud-init updates Azure network configuration on the following events: %s.TN)�UBUNTU_EXTENDED_NETWORK_SCRIPTSrzr{r�rcr�rrRr7ZBOOT_LEGACY�isdirrZdel_dirrC)r�Zloggedr{r3r3r4r�^	s
r�cCsltjddtd��R}tjd�}|tkr(dSd|}||_t|tj	d�t
jjt
jj
|d��r^dSd	SQRXd
S)z@Check platform environment to report if this datasource may run.zcheck-platform-viabilityzfound azure asset tag)r�r�r�zchassis-asset-tagTz(Non-Azure DMI asset tag '%s' discovered.)r�zovf-env.xmlFN)rr�rr
r�AZURE_CHASSIS_ASSET_TAGr�r#rcrdrzr{r�rZ)r|rkZ	asset_tagr�r3r3r4r��	s
r�c@seZdZdS)r�N)r+r,r-r3r3r3r4r��	sr�c@seZdZdS)r�N)r+r,r-r3r3r3r4r��	sr�cCstj|t�S)N)r
Zlist_from_depends�datasources)Zdependsr3r3r4�get_datasource_list�	sr�)N)r\)N)r�)N)�r�r�r�rzZos.pathrAZxml.etree.ElementTreeZetreeZElementTreerr�enumrrrZtypingrrrrZxml.domr	r!Z	cloudinitr
rZloggingrr
rrrZcloudinit.eventrrZ
cloudinit.netrZcloudinit.net.dhcprrZcloudinit.reportingrZcloudinit.sources.helpersrZcloudinit.sources.helpers.azurerrrrrrrrr r!r"r#r$Zcloudinit.url_helperr%r&r'Z	getLoggerr+rcr�r�r�Z
LEASE_FILEZ
DEFAULT_FSr�r�rrZAGENT_SEED_DIRr�r8r/r�r�r�r*r5ZPLATFORM_ENTROPY_SOURCErnr�r�rJrMrRr\rargrirlrmror�Zres_diskrdr�r�r�rGZDEF_EPHEMERAL_LABELrvrxrwr�r�r�r�r	rarcrlrFr�r�r�r@r�r�r�r�r�r�r�r�rTrJr�r�r0r�r�r�r�r�r�r�ZDataSourceAzureNetZDEP_FILESYSTEMr�r�r3r3r3r4�<module>s<

	+




!


k(
8o/!
I
0%

Youez - 2016 - github.com/yon3zu
LinuXploit