o
    w7e                    @   s~  U d dl Z d dlZd dlZd dlZd dlZd dlZd dlm  mZ	 d dl
mZ d dlmZ d dlmZmZ d dlmZmZmZmZ d dlmZ d dlmZmZmZmZmZ d dlmZmZ d d	l m!Z!m"Z"m#Z# d d
l$m%Z% d dl&m'Z' d dl(m)Z)m*Z*m+Z+m,Z, d dl-m.Z. d dl/m0Z0m1Z1m2Z2m3Z3m4Z4m5Z5m6Z6m7Z7m8Z8m9Z9m:Z:m;Z;m<Z<m=Z=m>Z> d dl?m@Z@ zd dlAZAejBeAjAdejCdd dZDeeEd< W n$ eFeGfy   zd dlHZHeHjIjJjIZDW n eFy   dd ZDY nw Y nw eKeLZMdZNddiZOdZPdZQdZRdZSG dd deZTdZUeeV eEd < g d!ZWd"d# ZXd$d% ZYd&eVd'eVd(eeV fd)d*ZZd+eVd(eVfd,d-Z[e5d(eeV fd.d/Z\e5d+eVd(eeV fd0d1Z]d~d(eVfd2d3Z^d4d5 Z_d6d7 Z`d8d9 Zad(eeV fd:d;Zbec rd<ZQebd=ZdeddureMed> d?ed ZPneMed@ dZUeRdAePidBdCZfdAdDdEgdBdFieQdGdHgdIZgdJeNgZhdKZidLZjdMZkG dNdO dOejlZmdPdQ ZndRdS ZodTdU ZpdVdW ZqdXdY ZrddZd[Zse5d\d] Zte5d^d_ Zue5ePd`d`fdaeVdbeVdcevddevfdedfZwe5d~dgdhZxe5didj Zydkdl Zze5dmdn Z{e5eUfdodpZ|e5dqdr Z}e5dsdt Z~e5dued(efdvdwZe5d(efdxdyZe5d~dzd{ZemZemejffgZd|d} ZdS )    N)Enum)Path)sleeptime)AnyDictListOptional)log)netsourcesssh_utilsubputil)
EventScope	EventType)NoDHCPLeaseErrorNoDHCPLeaseInterfaceErrorNoDHCPLeaseMissingDhclientError)EphemeralDHCPv4)events)errorsidentityimdskvp)netlink)DEFAULT_WIRESERVER_ENDPOINTBrokenAzureDataSourceNonAzureDataSource	OvfEnvXmlazure_ds_reporterazure_ds_telemetry_reporterbuild_minimal_ovfdhcp_log_cbget_boot_telemetryget_ip_from_lease_valueget_metadata_from_fabricget_system_infopush_log_to_kvpreport_diagnostic_eventreport_failure_to_fabric)UrlErrorz$6$   )strlen)saltblowfish_hashc                 C   s   t d)zRaise when called so that importing this module doesn't throw
            ImportError when ds_detect() returns false. In this case, crypt
            and passlib are not needed.
            z/crypt and passlib not found, missing dependency)ImportError)_ r2   C/usr/lib/python3/dist-packages/cloudinit/sources/DataSourceAzure.pyr/   ?   s   Azureinstance-idziid-AZURE-NODEz/dev/disk/cloud/azure_resourceext4z/var/lib/waagentz/dev/sr0c                   @   s    e Zd ZdZdZdZdZdZdS )PPSTypeNonePreprovisionedOSDiskRunningSavableUnknownN)__name__
__module____qualname__NONEOS_DISKRUNNINGSAVABLEUNKNOWNr2   r2   r2   r3   r7   V   s    r7   z/sys/firmware/acpi/tables/OEM0PLATFORM_ENTROPY_SOURCE)z"/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.dc                 C   s   |   D ]9}td|r=| }t|dkr=|d d}t|dkr=|d dkr=|d |r=|d d}|d   S qd	S )
z
    dev.storvsc.1.%pnpinfo:
        classid=32412632-86cb-44a2-9b5c-50d1417354f5
        deviceid=00000000-0001-8899-0000-000000000000
    pnpinfo      =r   deviceid   .N)
splitlinesresearchsplitlen
startswith)
sysctl_outrJ   linefieldscolumnscompsr2   r2   r3   "find_storvscid_from_sysctl_pnpinfoj   s   rX   c                 C   s2   |   D ]}t||r| }|d   S qdS )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
    r   N)rM   rN   rO   rP   )camcontrol_outdisk_drvrT   itemsr2   r2   r3   find_busdev_from_disk   s   r\   rY   busdevreturnc                 C   sN   |   D ] }t||r$|d}t|dkr$|d d}|d   S qdS )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)
    (rH   rK   ,r   N)rM   rN   rO   rP   rQ   )rY   r]   rT   r[   dev_passr2   r2   r3   find_dev_from_busdev   s   
rb   macc              
   C   sZ   t | dkr)d| dd | dd | dd | dd | dd | dd g} |  S )	z1Normalize mac address with colons and lower-case.   :r   rH            
   )rQ   joinlowerrc   r2   r2   r3   normalize_mac_address   s
   >rm   c                   C   s   dd t  D S )z-Get Hyper-V NICs as normalized MAC addresses.c                 S   s$   g | ]}|d  dkrt |d qS )rH   	hv_netvscrK   rm   ).0nr2   r2   r3   
<listcomp>   s
    
z1get_hv_netvsc_macs_normalized.<locals>.<listcomp>)r   get_interfacesr2   r2   r2   r3   get_hv_netvsc_macs_normalized   s   rt   c                    sf    fddt  D }d|v rdS t|dkr&td |f tjd |d S td |f tjd d	S )
z0Determine the device driver to match on, if any.c                    s$   g | ]} t |d  kr|d qS )rK   rH   ro   rp   irl   r2   r3   rr      s
    z3determine_device_driver_for_mac.<locals>.<listcomp>rn   rK   z4Assuming driver for interface with mac=%s drivers=%rlogger_funcr   z=Unable to specify driver for interface with mac=%s drivers=%rN)r   rs   rQ   r)   LOGdebugwarning)rc   driversr2   rl   r3   determine_device_driver_for_mac   s(   
r}   c              	   C   s:   zt  | jW S  t jy   tdd|  | Y S w )NzFailed to execute: %s )r   stdoutProcessExecutionErrorry   rz   rj   )cmdfail_retr2   r2   r3   execute_or_debug   s   r   c                   C   s   t ddgddS )Nsysctlzdev.storvsc )r   r   r2   r2   r2   r3   get_dev_storvsc_sysctl      r   c                   C   s   t g dS )N)
camcontroldevlistz-br   r2   r2   r2   r3   get_camcontrol_dev_bus      r   c                   C   s   t ddgS )Nr   r   r   r2   r2   r2   r3   get_camcontrol_dev   r   r   c                 C   s   d}| dkrd}| d } dt |  }d||}t }t||}|s)td d S t }t }d|}t||}	|	rMt	||	}
|
d u rKtd	 d S |
S d
|}t||}	|	rkt	||	}
|
d u ritd	 d S |
S d S )N00000000rK   00000001rH   000z{0}-{1}z#Fail to find storvsc id from sysctlz	blkvsc{0}zFail to find /dev/daXz
storvsc{0})
strformatr   rX   ry   rz   r   r   r\   rb   )port_idg0g1g0g1rS   	storvscidcamcontrol_b_outrY   blkvscscbusxdevnamestorvscr2   r2   r3   get_resource_disk_on_freebsd   s<   









r   zfreebsd-ufsrK   zresource disk is not None/dev/zresource disk is None
ephemeral0T)data_dirdisk_aliasesapply_network_configgptd   )
table_typelayout	overwritezephemeral0.1)
filesystemdevice)
disk_setupfs_setup
datasourcenever_destroy_ntfszTemporary StorageREDACTEDc                
       s,  e Zd ZdZejejejhiZ	dZ
ejZdZdd Zdeddf fd	d
Zdd Zdd Zedddddee dededdfddZedwddZdefddZedd ZededefddZdx fd d!	Zed"d# Zed$d% Z d&d' Z!d(d) Z"ede#e fd*d+Z$d,e%de#e fd-d.Z&de#e fd/d0Z'd1d2 Z(d3d4 Z)dyd5d6Z*ed7d8 Z+e	:dzd;ed<ede,fd=d>Z-ed?d@ Z.edAddBdCedDeddfdEdFZ/ed;edefdGdHZ0edIdJ Z1ede2j2fdKdLZ3edMdN Z4edwdOdPZ5edQdR Z6edSdT Z7ede8fdUdVZ9e	d{dWe:j;dXedefdYdZZ<edd[d\ee#e  dee#e  fd]d^Z=d,e%dee fd_d`Z>dae%d,e%de?fdbdcZ@eddde ZAedfe%d,e%dee#e  fdgdhZBdidj ZCedkdl ZDeEdmdn ZFedodp ZGeEdqdr ZHeEdsdt ZIed,e%defdudvZJ  ZKS )|DataSourceAzurer4   FrK   c                 C   sz   t j| ||| tj|jd| _i | _d | _t	
t	|ti tg| _d | _d | _d | _t| _tj|jdd| _d S )Nazuredatareported_ready)r   
DataSource__init__ospathrj   seed_dircfgseedr   mergemanydictget_cfg_by_pathDS_CFG_PATHBUILTIN_DS_CONFIGds_cfg_iso_dev_network_config_ephemeral_dhcp_ctxr   _wireserver_endpoint	cloud_dir_reported_ready_marker_file)selfsys_cfgdistropathsr2   r2   r3   r   D  s   
zDataSourceAzure.__init__ci_pkl_versionr^   Nc                    s8   t  | d | _d | _t| _tj| j	j
dd| _d S )Nr   r   )super	_unpickler   r   r   r   r   r   rj   r   r   r   )r   r   	__class__r2   r3   r   T  s   

zDataSourceAzure._unpicklec                 C   s   t j| }d|| jf S )Nz%s [seed=%s])r   r   __str__r   )r   rootr2   r2   r3   r   ^  s   zDataSourceAzure.__str__c                 C   sH   | j du rd}n| j drd}n| j  dkrd}nd}d|| j f S )z/Return the subplatform metadata source details.Nunknownz/devzconfig-diskr   zseed-dirz%s (%s))r   rR   rk   )r   subplatform_typer2   r2   r3   _get_subplatformb  s   
z DataSourceAzure._get_subplatform   )ifaceretry_sleeptimeout_minutesr   r   r   c                C   s  | j dur	tdtd| t| j|td| _ d}t }||d  }tj	ddt
d |du rz| j  }W nr tyU   td	tjd
 | jtjt | ddd Y nU tyf   tdtjd
 d| _   ty   td| tjd
 | jtjt | |ddd Y n$ tjy } ztd|j|j|j|jf tjd
 W Y d}~nd}~ww |du rt | |k rt| nn|du s0|du rd| _ t |d | j _d|v rt|d | _W d   dS W d   dS 1 sw   Y  dS )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))r   dhcp_log_func<   zobtain-dhcp-leasezobtain dhcp leasenamedescriptionparentzInterface not found for DHCPrw   )durationT	host_onlyzdhclient executable not foundz&Failed to obtain DHCP lease (iface=%s))r   	interfacez7Command failed: cmd=%r stderr=%r stdout=%r exit_code=%sr   zunknown-245) r   RuntimeErrorry   rz   r   r   r#   r   r   ReportEventStackr    obtain_leaser   r)   r{   _report_failurer   $ReportableErrorDhcpInterfaceNotFoundr   errorr   ReportableErrorDhcpLeaser   r   r   stderrr   	exit_coder   r   r%   r   )r   r   r   r   lease
start_timedeadliner   r2   r2   r3   _setup_ephemeral_networkingn  s   




5B"z+DataSourceAzure._setup_ephemeral_networkingc                 C   s"   | j du rdS | j   d| _ dS )zTeardown ephemeral networking.N)r   clean_networkr   r2   r2   r3   _teardown_ephemeral_networking  s   


z.DataSourceAzure._teardown_ephemeral_networkingc                 C   s   | j du p
| j jdu  S )z"Check if networking is configured.N)r   r   r   r2   r2   r3   _is_ephemeral_networking_up  s   

z+DataSourceAzure._is_ephemeral_networking_upc                 C   s  i }| j d }d}ddi}ddddiii}d}i }t| j|D ]{}z:|drFt r8tj|td	d
\}}}}n
t|t\}}}}|| _nt|\}}}}|}t	d| t
jd W  nH tym   t	d| t
jd Y q tjy   t	d| t
jd Y q ty }	 zd|	 }
t	|
t
jd t|
d}	~	ww d}
t	|
t
jd t| jp|du }|rdnd}z| j|d W n	 ty   Y nw i }|  r| jdd}|s|du rd}
t	|
 t|
| ||}|tjkrGt rd}
t	|
t
jd t|
|  sd}
t	|
t
jd t|
|tjkr|   n|tjkr*|   n|tjkr5|    n| !  | " \}}}}| jdd}| j#|d |pQd| _$|%||t&|d|ig|d t'|}t(|}t)|}|rt
d| ||d d d< |rt
d| ||d d< |rt
d | ||d d!< | j$dkr|d" szt*|||d#}d$|i|d"< W n t+y } zt	d%| t
jd W Y d}~nd}~ww |st,|}|rt
d& zt-.d/|0 |d'< W n t+y   t	d(t
jd Y nw ||krt	d)| t
jd t1 }|r||d d*< | 2 |d d+< | j3d,u rc|  rc| j4||d-}z| j5|d.}W n t+yL   Y |S w t
d/| |r\||d d0< | 6  d| _3|S )1a  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.
        r   Nlocal-hostnamer   system_infodefault_userr   r   udf)mtypez!Found provisioning metadata in %srw   z$Did not find Azure data source in %sz%s was not mountablezBrokenAzureDataSource: %szUnable to find provisioning media, falling back to IMDS metadata. Be aware that IMDS metadata does not support admin passwords or custom-data (user-data only).   r   r   Treport_failurezNo OVF or IMDS availablez%Free BSD is not supported for PPS VMszDHCP failed while in source PPS)imds_mdIMDSr   )r   filesmetadatauserdata_rawz Username retrieved from IMDS: %sz Hostname retrieved from IMDS: %sr   z(Disable password retrieved from IMDS: %sdisable_passwordr   )usernamehostnamedisableSshPwdovf-env.xmlz)Failed to construct OVF from IMDS data %szRetrieved userdata from IMDSr   zBad userdata in IMDSzusing files cached in %srandom_seedr5   F)r   r   pubkey_infoznegotiating returned %spublic-keys)7r   list_possible_azure_dsr   rR   r   
is_FreeBSDmount_cbload_azure_ds_dirr   r)   ry   rz   r   MountFailedErrorr   r   r   InvalidMetaDataExceptionr{   boolr   r   r   get_metadata_from_imds_determine_pps_typer7   r@   rB   _wait_for_pps_running_reuserC   _wait_for_pps_savable_reuserA   _wait_for_pps_os_disk_shutdown_wait_for_pps_unknown_reuse_reprovisionvalidate_imds_network_metadatar   updater   _username_from_imds_hostname_from_imds_disable_password_from_imdsr"   	Exception_userdata_from_imdsbase64	b64decoderj   rP   _get_random_seed_iid_negotiated!_determine_wireserver_pubkey_info_report_ready_cleanup_markers)r   crawled_dataddir
ovf_sourcemdr   r   r   srcexcmsgrequires_imds_metadatar   r   pps_typeimds_usernameimds_hostnameimds_disable_passwordcontentseimds_userdatar   r  ssh_keysr2   r2   r3   crawl_metadata  s:  















	zDataSourceAzure.crawl_metadatar   c              
   C   s   t  }|d }d }d }ztj|dW S  ty4 } zt|}t  | }tj||d}W Y d }~n d }~w tyO } zt|}tj|d}W Y d }~nd }~ww | j	|| d t
d| tjd i S )Ni,  )retry_deadline)	exceptionr   )r8  r   z!Ignoring IMDS metadata due to: %srw   )r   r    fetch_metadata_with_api_fallbackr+   r   r   ReportableErrorImdsUrlError
ValueError+ReportableErrorImdsMetadataParsingExceptionr   r)   ry   r{   )r   r   r   r7  error_stringerror_reportr   r   r2   r2   r3   r    s8   
z&DataSourceAzure.get_metadata_from_imdsr2   c                    s   t t| | tj| _dS )z.Reset any cached class attributes to defaults.N)r   r   clear_cached_attrsr   UNSET_metadata_imds)r   attr_defaultsr   r2   r3   r?    s   z"DataSourceAzure.clear_cached_attrsc                 C   s4   t j }|durdS | jdu rdS t| jd S )zQCheck platform environment to report if this datasource may
        run.
        NTFr  )r   ChassisAssetTagquery_systemr   r   exists)r   chassis_tagr2   r2   r3   	ds_detect  s   

zDataSourceAzure.ds_detectc              
   C   s  zt   W n ty } ztd| W Y d}~nd}~ww zt  W n ty; } ztd| W Y d}~nd}~ww zRztjtjd| jd}W n? t	j
yg } z| | W Y d}~W |   dS d}~w ty } zt	|}| | W Y d}~W |   dS d}~ww W |   n|   w | jr| jjdkr| jdrt  t}tj|rtd	| tjd
 t|d tg| _ntd| tjd
 |d | _|d d | _t|d tg| _|d | _t| jd |d dd dS )zCrawl and process datasource metadata caching metadata as attrs.

        @return: True on success, False on error, invalid or disabled
            datasource.
        z Failed to get boot telemetry: %sNz$Failed to get system information: %szCrawl of metadata service)logfuncr,  funcFubuntur   zXEphemeral resource disk '%s' exists. Merging default Azure cloud ephemeral disk configs.rw   r   zdEphemeral resource disk '%s' does not exist. Not merging default Azure cloud ephemeral disk configs.r   r   r   r   r   i  )dirmodeT) r$   r  ry   r{   r'   r   log_timerz   r6  r   ReportableErrorr   r   !ReportableErrorUnhandledExceptionr   r   r   get*maybe_remove_ubuntu_network_config_scriptsRESOURCE_DISK_PATHr   r   rE  r)   r   #BUILTIN_CLOUD_EPHEMERAL_DISK_CONFIGr   rA  DEFAULT_METADATAr   r   write_files)r   r3  r&  r   reportable_errordevpathr2   r2   r3   	_get_data  s   










zDataSourceAzure._get_datac                 C   s&   | j rd| j vr|  S t| j d S )Nr5   )r   r!  r   r   r2   r2   r3   get_instance_id2  s   zDataSourceAzure.get_instance_idc                 C   s   | j d |S )Nr   )r   rO  )r   r   r2   r2   r3   device_name_to_device7  r   z%DataSourceAzure.device_name_to_devicec              	   C   s0   z	|  | jd W S  ttfy   Y |  S w )z+
        Retrieve public SSH keys.
        r   )_get_public_keys_from_imdsr   KeyErrorr;  _get_public_keys_from_ovfr   r2   r2   r3   get_public_ssh_keys:  s   z#DataSourceAzure.get_public_ssh_keysr   c                 C   s   zdd |d d D }W n t y   d}t|tjd  w tdd |D r5d	}t|tjd t|d
t|}t|tjd |S )zGet 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.
        c                 S      g | ]}|d  qS )keyDatar2   )rp   
public_keyr2   r2   r3   rr   O  s    z>DataSourceAzure._get_public_keys_from_imds.<locals>.<listcomp>compute
publicKeysz"No SSH keys found in IMDS metadatarw   c                 s   s    | ]	}t |d  V  qdS ))keyN)_key_is_openssh_formatted)rp   rc  r2   r2   r3   	<genexpr>X  s    z=DataSourceAzure._get_public_keys_from_imds.<locals>.<genexpr>zKey(s) not in OpenSSH formatzRetrieved {} keys from IMDS)r[  r)   ry   rz   anyr;  r   rQ   )r   r   r5  log_msgr2   r2   r3   rZ  F  s    

z*DataSourceAzure._get_public_keys_from_imdsc                 C   sX   g }z| j d }dt|}t|tjd W |S  ty+   d}t|tjd Y |S w )zYGet SSH keys that were fetched from wireserver.

        :returns: List of keys.
        r  zRetrieved {} keys from OVFrw   zNo keys available from OVF)r   r   rQ   r)   ry   rz   r[  )r   r5  rg  r2   r2   r3   r\  a  s   
z)DataSourceAzure._get_public_keys_from_ovfc                 C   s   | j S Nr   r   r2   r2   r3   get_config_objq  s   zDataSourceAzure.get_config_objc                 C   s   t |  S rh  )r   instance_id_matches_system_uuidrX  )r   r   r2   r2   r3   check_instance_idt  s   z!DataSourceAzure.check_instance_idc                 C   sZ   t j| jdd}t }t j|r+t	|
 }t|}| ||fv r+|S |S )Nr   r5   )r   r   rj   r   	get_cpathr   query_system_uuidrE  r   	load_filestripbyte_swap_system_uuidrk   )r   previousprev_iid_pathsystem_uuid
swapped_idr2   r2   r3   r!  x  s   
zDataSourceAzure._iidc              
   C   s   z;d}t jddtd t|}W d   n1 sw   Y  |du r0d}t|tjd W dS td| tjd W dS  tyQ } z
tt	|tj
d  d}~ww )zUse 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.
        Nzwait-for-nic-detachzwait for nic detachr   zHPreprovisioned nic not detached as expected. Proceeding without failing.rw   z%The preprovisioned nic %s is detached)r   r   r    r   wait_for_nic_detach_eventr)   ry   r{   AssertionErrorr   r   )r   nl_sockifnamer,  r   r2   r2   r3   _wait_for_nic_detach  s,   z$DataSourceAzure._wait_for_nic_detachr   皙?ry  retriesc                 C   sf   t |D ]}| jj|rtd| tjd  d S |d |k r#t| qtd||| f tjd d S )NzThe link %s is up.rw   rK   z;The link %s is not up after %f seconds, continuing anyways.)ranger   
networkingtry_set_link_upr)   ry   infor   )r   ry  r|  r   rv   r2   r2   r3   wait_for_link_up  s   


z DataSourceAzure.wait_for_link_upc                 C   s@   | j }td| t|djt t d t	dtj
d d S )Nz*Creating a marker file to report ready: %sz{pid}: {time}
)pidr   zRSuccessfully created reported ready marker file while in the preprovisioning pool.rw   )r   ry   r  r   
write_filer   r   getpidr   r)   rz   )r   r   r2   r2   r3   _create_report_ready_marker  s   
z+DataSourceAzure._create_report_ready_markerT)create_markerexpect_url_errorr  r  c             
   C   s   z|    W n3 ty9 } z'|r t|tr tdtjd d| _nd}t|tjd t	
||W Y d}~nd}~ww |rB|   dS dS )zReport ready for PPS, creating the marker file upon completion.

        :raises sources.InvalidMetaDataException: On error reporting ready.
        z,Ignoring http call failure, it was expected.rw   Nz9Failed reporting ready while in the preprovisioning pool.)r$  r  
isinstancer+   r)   ry   rz   r   r   r   r  r  )r   r  r  r   r,  r2   r2   r3   _report_ready_for_pps  s&   z%DataSourceAzure._report_ready_for_ppsc                 C   sF   | j |dd | jdd}|rtd| dS td| |   dS )z5Check if a given interface is the primary nic or not.r   )r   r   Fr   z%s is the primary nicTzQFailed to fetch IMDS metadata using nic %s. Assuming this is not the primary nic.)r   r  ry   r  r{   r   )r   ry  r   r2   r2   r3   _check_if_nic_is_primary  s   z(DataSourceAzure._check_if_nic_is_primaryc              
   C   s   t d zTg }d}	 d}tjddt| td t||}W d   n1 s*w   Y  || t	d| t jd	 | 
| |sOt d
| | |}|rYt d W dS q tyu } zt	t|t jd	 W Y d}~dS d}~ww )z6Wait until the primary nic for the vm is hot-attached.z*Waiting for primary nic to be hot-attachedFTNzwait-for-nic-attachz4wait for nic attach after %d nics have been attachedr   zDetected nic %s attached.rw   z!Checking if %s is the primary niczFound primary nic for this VM.)ry   r  r   r   rQ   r    r   wait_for_nic_attach_eventappendr)   r  r  rw  r   r   )r   rx  
nics_foundprimary_nic_foundry  r   r2   r2   r3   "_wait_for_hot_attached_primary_nic  sB   





$ z2DataSourceAzure._wait_for_hot_attached_primary_nicc              
   C   s<   zt  W S  t jy } ztd| tjd  d }~ww )Nz!Failed to create netlink socket: rw   )r   create_bound_netlink_socketNetlinkCreateSocketErrorr)   ry   r   )r   r   r2   r2   r3   _create_bound_netlink_socket;  s   
z,DataSourceAzure._create_bound_netlink_socketc                 C   s*   | j dd tdtjd td td)z4Report ready and wait for host to initiate shutdown.F)r  z"Waiting for host to shutdown VM...rw   i3zShutdown failure for PPS disk.)r  r)   ry   r  r   r   r   r2   r2   r3   r  F  s   z.DataSourceAzure._wait_for_pps_os_disk_shutdownc                 C   s   |   }z_| jdu s| jjdu rtd| jj}|   td| tjddt	d, zt
|| W n tyN } ztd| tjd W Y d}~nd}~ww W d   n1 sYw   Y  W |  n|  w |   dS )	z9Report ready and wait for nic link to switch upon re-use.Nzmissing ephemeral contextz#Wait for vnetswitch to happen on %sz!wait-for-media-disconnect-connectzwait for vnet switchr   z'Error while waiting for vnet switch: %srw   )r  r   r   r   r  ry   rz   r   r   r    r   !wait_for_media_disconnect_connectrw  r)   r   closer   )r   rx  r   r3  r2   r2   r3   r  R  s<   
z+DataSourceAzure._wait_for_pps_running_reusec              
   C   s   |   }z=| jdd z|   W n tjy0 } ztd| tjd d| _W Y d}~nd}~ww | 	| | 
| W |  dS |  w )z@Report ready and wait for nic(s) to be hot-attached upon re-use.T)r  zLIgnoring failure while tearing down networking, NIC was likely unplugged: %rrw   N)r  r  r   r   r   r)   ry   r  r   rz  r  r  )r   rx  r3  r2   r2   r3   r  w  s$   
z+DataSourceAzure._wait_for_pps_savable_reusec                 C   s&   t j| jr	dS |   |   dS )z0Report ready if needed for unknown/recovery PPS.N)r   r   isfiler   r  r   r   r2   r2   r3   r    s   z+DataSourceAzure._wait_for_pps_unknown_reusec              	   C   s   d}d}|sT|   s |d7 }z| jdd W n	 ty   Y qw tjddtd" zt }W n tyB   | 	  Y W d   qw W d   n1 sMw   Y  |rt
d	| tjd
 |S )z0Poll IMDs for reprovisiondata XML document data.r   NrK   r   r   zget-reprovision-data-from-imdszget reprovision data from imdsr   z#attempted dhcp %d times after reuserw   )r   r   r   r   r   r    r   fetch_reprovision_datar+   r   r)   ry   rz   )r   dhcp_attemptsreprovision_datar2   r2   r3   
_poll_imds  s<   zDataSourceAzure._poll_imdsr   r   c              
   C   s  t d|  tjd t|}|r|S |  rFzt dtjd t| j	|d W dS  t
yE } zt d| tjd W Y d}~nd}~ww z't dtjd |   z| jd	d
 W n	 tyc   Y nw t| j	|d W dS  t
y } zt d| tjd W Y d}~dS d}~ww )a  Report failure to Azure host and fabric.

        For errors that may be recoverable (e.g. DHCP), host_only provides a
        mechanism to report the failure that can be updated later with success.
        DHCP will not be attempted if host_only=True and networking is down.

        @param error: Error to report.
        @param host_only: Only report to host (error may be recoverable).
        @return: The success status of sending the failure signal.
        z#Azure datasource failure occurred: rw   z>Using cached ephemeral dhcp context to report failure to Azure)endpointr   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)   as_encoded_reportry   r   r   report_failure_to_hostr   rz   r*   r   r  r   r   r   )r   r   r   reportedr3  r2   r2   r3   r     sb   
zDataSourceAzure._report_failurer  r  c             
   C   sV   t   zt| j| j|d}W n ty% } z
td| tjd  d}~ww d| _|S )zTells 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.
        )r  iso_devr  zQError communicating with Azure fabric; You may experience connectivity issues: %srw   N)	r   report_success_to_hostr&   r   r   r  r)   ry   r{   )r   r  r   r3  r2   r2   r3   r$    s&   
	zDataSourceAzure._report_readyc              
   C   sL   z	|d d d W S  t y% } ztd| tjd W Y d }~d S d }~ww )Nextendedra  ppsTypez2Could not retrieve pps configuration from IMDS: %srw   )r  r)   ry   rz   )r   r   r3  r2   r2   r3   _ppstype_from_imds  s   z"DataSourceAzure._ppstype_from_imdsovf_cfgc                 C   s   t j| jrtj}nO|ddtjjks| 	|tjjkr"tj}n8|ddtj
jks5| 	|tj
jkr9tj
}n!|ddu sS|ddtjjksS| 	|tjjkrWtj}ntj}td|j tjd |S )z@Determine PPS type using OVF, IMDS data, and reprovision marker.PreprovisionedVMTypeNPreprovisionedVmTzPPS type: %srw   )r   r   r  r   r7   rD   rO  rC   valuer  rA   rB   r@   r)   ry   r  )r   r  r   r.  r2   r2   r3   r     s&   
z#DataSourceAzure._determine_pps_typec                 C   sZ   |   }tjddtd t|\}}}|||d|ifW  d   S 1 s&w   Y  dS )zrInitiate the reprovisioning workflow.

        Ephemeral networking is up upon successful reprovisioning.
        zreprovisioning-read-azure-ovfz$read azure ovf during reprovisioningr   r  N)r  r   r   r    read_azure_ovf)r   r2  r)  udr   r2   r2   r3   r  =  s   $zDataSourceAzure._reprovisionr   c             	   C   sb   d}z|  | W |S  ttfy0   |dd}d|dur#t|nd}t|tjd Y |S w )zDetermine 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   rw   )	rZ  r[  r;  rO  r   rQ   r)   ry   rz   )r   r   r   r  rg  r2   r2   r3   r#  L  s   z1DataSourceAzure._determine_wireserver_pubkey_infoc                 C   s   t | j dS )zCleanup any marker files.N)r   del_filer   r   r2   r2   r3   r%  _  s   z DataSourceAzure._cleanup_markersc              	   C   sH   | j  }zt||| jtdd W t| jd  d S t| jd  w )NF)is_new_instancepreserve_ntfsdef_log_file)r   get_ipath_curaddress_ephemeral_resizer   rO  DS_CFG_KEY_PRESERVE_NTFSr(   r   )r   r   r  instance_dirr2   r2   r3   activatec  s   
zDataSourceAzure.activatec                 C      | j di di dS )Nr   ra  platformFaultDomainr   rO  r   r2   r2   r3   availability_zonep  s   z!DataSourceAzure.availability_zonec              
   C   s   | j r2| j tjkr2| jdr2zt| j d W S  ty1 } ztdt	| W Y d}~nd}~ww zt
 W S  tyQ } ztdt	| W Y d}~i S d}~ww )z:Generate network configuration according to configuration.r   networkz?Failed generating network config from IMDS network metadata: %sNz-Failed generating fallback network config: %s)rA  r   r@  r   rO  6generate_network_config_from_instance_network_metadatar  ry   r   r   -_generate_network_config_from_fallback_config)r   r3  r2   r2   r3   _generate_network_configx  s.   
z(DataSourceAzure._generate_network_configc                 C   s(   | j r| j tjkr| j S |  | _ | j S )z,Provide network configuration v2 dictionary.)r   r   r@  r  r   r2   r2   r3   network_config  s   
zDataSourceAzure.network_configc                 C   r  )Nr   ra  locationr  r   r2   r2   r3   region  s   zDataSourceAzure.regionc                    s   t  }z|d }dd |d D  W n ty(   td|d tjd Y dS w  fdd|D }|s6d	S td
||f tjd | jrH| jjsJdS t	| jj}|rXt
|tsZdS t|}||v rmtd||f tjd dS )z=Validate IMDS network config and report telemetry for errors.r  c                 S   s   g | ]}t |d  qS )
macAddressro   ru   r2   r2   r3   rr     s    
zBDataSourceAzure.validate_imds_network_metadata.<locals>.<listcomp>r   z6IMDS network metadata has incomplete configuration: %rrw   Fc                    s   g | ]}| vr|qS r2   r2   )rp   m	imds_macsr2   r3   rr     s    Tz>IMDS network metadata is missing configuration for NICs %r: %rz3IMDS network metadata is missing primary NIC %r: %r)rt   r[  r)   rO  ry   r{   r   r   r   get_interface_macr  r   rm   )r   r   
local_macsr  missing_macsprimary_macr2   r  r3   r    sL   
z.DataSourceAzure.validate_imds_network_metadata)r^   N)r2   rh  )r   r{  )F)Lr=   r>   r?   dsnamer   NETWORKr   BOOT_NEW_INSTANCEBOOTdefault_update_eventsr"  r   r@  rA  _ci_pkl_versionr   intr   r   r   r!   r	   r   r   r   r  r   r6  r   r  r?  rG  rW  rX  rY  r   r]  dictrZ  r\  rj  rl  r!  rz  floatr  r  r  r  r  socketr  r  r  r  r  bytesr  r   rM  r   r$  r  r7   r  r  r#  r%  r  propertyr  r  r  r  r  __classcell__r2   r2   r   r3   r   7  s   
g
 N

L


#
2

$

>








	
r   c                 C   (   z	| d d d W S  t y   Y d S w )Nra  	osProfileadminUsernamer[  	imds_datar2   r2   r3   r    
   r  c                 C   s$   z| d d W S  t y   Y d S w )Nra  userDatar  r  r2   r2   r3   r    s
   r  c                 C   r  )Nra  r  computerNamer  r  r2   r2   r3   r    r  r  c                 C   s,   z| d d d dkW S  t y   Y d S w )Nra  r  disablePasswordAuthenticationtruer  r  r2   r2   r3   r    s   r  c                 C   sF   d|   v rdS t }z|| }W n
 ty   Y dS w |jduS )z?
    Validate whether or not the key is OpenSSH-formatted.
    z
FN)rp  r   AuthKeyLineParserparse	TypeErrorkeytype)rc  parseraklr2   r2   r3   rd    s   
rd  c                 C   s`   dD ]+}g }t d|D ]}| | t| }tj|r&||tj|f q|r-|  S qg S )N)z-partpr   rK   )r}  r   r   r   rE  r  realpath)rV  maxnumsufffoundpnumppathr2   r2   r3   _partitions_on_device  s   r  c                 C   s*   t jddd}td| tj| |v S )Nz	TYPE=ntfsT)no_cachezntfs_devices found = %s)r   find_devs_withry   rz   r   r   r  )rV  ntfs_devicesr2   r2   r3   _has_ntfs_filesystem  s   r  c                 C   s  |rdd ttf }d|fS tj| sdd|  fS td| tj|  t	| }t
|dkr6dd|  fS t
|dkrNd	| d
 dd |D f }d|fS t
|dkr[|d \}}n|d \}}t|spd||| f }d|fS tdd }d||| f }tjddtdy}ztj||dddidd}	W n@ tjy }
 z3d|_dt|
v rd|d fW  Y d}
~
W  d   S d|d||
f  fW  Y d}
~
W  d   S d}
~
ww |	dkrd|	 |_tdd tt d|d |	  fW  d   S W d   n	1 sw   Y  d|d! fS )"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 checksrL   Fzdevice %s does not existzResolving realpath of %s -> %sr   zdevice %s was not partitionedrH   z&device %s had 3 or more partitions: %sr~   c                 S   r^  )rK   r2   )rp   r  r2   r2   r3   rr   @  s    z*can_dev_be_reformatted.<locals>.<listcomp>rK   z5partition %s (%s) on device %s was not ntfs formattedc                    s&   t dg t fddt| D S )Nzdataloss_warning_readme.txtc                    s   g | ]
}|   vr|qS r2   )rk   )rp   fignoredr2   r3   rr   S  s    z?can_dev_be_reformatted.<locals>.count_files.<locals>.<listcomp>)setrQ   r   listdir)mpr2   r  r3   count_filesP  s   
z+can_dev_be_reformatted.<locals>.count_filesz1partition %s (%s) on device %s was ntfs formattedzmount-ntfs-and-countr   ntfsLANGC)r   update_env_for_mount	log_errorzcannot mount ntfszunknown filesystem type 'ntfs'Tz^ but this system cannot mount NTFS, assuming there are no important files. Formatting allowed.Nz but mount of %s failed: %szmounted 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.)rj   r   r  r   r   rE  ry   rz   r  r  rQ   r  r!   r   r   r    r   r  r  r   r   r{   )rV  r  r,  
partitions	cand_part	cand_pathr  bmsgevt
file_countr3  r2   r2   r3   can_dev_be_reformatted  s   


%r  Fr  rV  r  r  c           
      C   s  t j|std| tjd d S td| tjd d}d }|r%d\}}nt||\}}td|| |s7d S dD ]E}t j| dd	| }d
||f }t j|rxzt | td| W q9 t	yw }	 zt
d||	 W Y d }	~	q9d }	~	ww td| q9d S )Nz,Ephemeral resource disk '%s' does not exist.rw   z$Ephemeral resource disk '%s' exists.F)TzFirst instance boot.zreformattable=%s: %s)r   mountssemconfig_zMarker "%s" for module "%s"z%s removed.z%s: remove failed! (%s)z%s did not exist.)r   r   rE  r)   ry   rz   r  rj   unlinkFileNotFoundErrorr{   )
r  rV  r  r  resultr,  modsempathr  r3  r2   r2   r3   r    s>   

r  c                 C   sj   dd }| sd S |si }t | | | D ]\}}tj| |}d|v r*|||}t j||dd qd S )Nc                 S   sb   zt | }| D ]}d|jv r|jtkrt|_q
t |W S  ty0   t	d| |  Y S w )z>Azure provides the UserPassword in plain text. So we redact itUserPasswordz#failed to redact userpassword in %s)
ET
fromstringitertagtextDEF_PASSWD_REDACTIONtostringr  ry   critical)cntfnamer   elemr2   r2   r3   _redact_password  s   


z%write_files.<locals>._redact_passwordr  i  )filenamecontentmode)r   
ensure_dirr[   r   r   rj   r  )datadirr   rK  r  r   r  r  r2   r2   r3   rT    s   
rT  c                 C   s   t | }i }i }|jpd}|jr|j|d< |jr|j|d< |jdur*|j |d< n|jr1d|d< i }|jr;|j|d< |jrNd|d	< t|jkrNt	|j|d
< |rVd|i|d< |j
|d< td|j
 tjd |j|d< td|j tjd |||fS )zParse OVF XML contents.

    :return: Tuple of metadata, configuration, userdata dicts.

    :raises NonAzureDataSource: if XML is not in Azure's format.
    :raises BrokenAzureDataSource: if XML is unparseable or invalid.
    r   r   r  N
ssh_pwauthTr   Flock_passwdhashed_passwdr   r   r  zPreprovisionedVm: %srw   r  zPreprovisionedVMType: %s)r   
parse_textcustom_datar  public_keysdisable_ssh_password_authpasswordr  r  encrypt_passpreprovisioned_vmr)   ry   r  preprovisioned_vm_type)r2  ovf_envr)  r   r  defuserr2   r2   r3   r    s@   
	








r  c                 C   s   t | S rh  )r/   )r$  r2   r2   r3   r%    s   r%  c                 C   s`   zt | }|d 	 W d   W dS 1 sw   Y  W dS  ty/   td|  Y dS w )z;Return boolean indicating path to cdrom device has content.i   NTzcdrom (%s) is not configuredF)openreadIOErrorry   rz   )	cdrom_devfpr2   r2   r3   _check_freebsd_cdrom  s   

$r/  c                 C   s*   | du rdS t j| ddd}t| S )zIReturn content random seed file if available, otherwise,
    return None.NTF)quietdecode)r   ro  r  	b64encoder1  )sourcer   r2   r2   r3   r     s   
r   c                 c   sZ    | V  t V  t rd}t|r|V  ndD ]}td| E d H  q|r+|V  d S d S )Nz/dev/cd0)iso9660r   zTYPE=%s)DEFAULT_PROVISIONING_ISO_DEVr   r
  r/  r  )r   	cache_dirr-  fstyper2   r2   r3   r	  #  s   
r	  c                 C   sr   t j| d}t j|stdt|d}| }W d    n1 s%w   Y  t|\}}}|||d|ifS )Nr  zNo ovf-env file foundrb)r   r   rj   r  r   r*  r+  r  )
source_dirovf_filer.  r2  r)  r  r   r2   r2   r3   r  2  s   
r  network_metadatac              	   C   sj  di d}t | d D ]\}}d}dj|d}d|d d	 i}d
|dd}dD ]Y}||i dg }	|	s=td|| q'd
}|dkrFd}
nd}
|	rRd
|d< ||d< |	dd D ]'}|| d d d|
}|d }|dssg |d< |d dj||d qXq'|r|rt|d }|d| i|d t	|}|r||d d < ||d! |< qtd"||| q|S )#zConvert imds network metadata dictionary to network v2 configuration.

    :param: network_metadata: Dict of "network" key from instance metdata.

    :return: Dictionary containing network version 2 standard configuration.
    rH   )version	ethernetsr   Fzeth{idx})idxzroute-metricrK   r   T)dhcp4zdhcp4-overridesdhcp6)ipv4ipv6	ipAddresszNo %s addresses found for: %rrA  24128r@  zdhcp6-overridesNsubnetr   prefixprivateIpAddress	addressesz{ip}/{prefix})iprG  r  
macaddress)matchzset-namerL  driverr=  z<No configuration for: %s (dev_config=%r) (has_ip_address=%r))
	enumerater   rO  ry   rz   r  rm   r  rk   r}   )r;  	netconfigr>  intfhas_ip_addressnicnamedhcp_override
dev_config	addr_typerI  default_prefixaddr	netPrefix	privateIprc   rM  r2   r2   r3   r  @  sb   


r  c                  C   s   t jdd} | du ri S | S )ztGenerate fallback network config.

    @return: Dictionary containing network version 2 standard configuration.
    T)config_driverN)r   generate_fallback_configri  r2   r2   r3   r    s   r  c                 C   sh   | st } d}| D ])}tj|r1|s tdtjjtj	jg d}tj
|r,t| qt| qdS )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_SCRIPTSr   r   rE  ry   r  r   r  r  BOOT_LEGACYisdirr   del_dirr  )r   loggedr   r2   r2   r3   rP    s    
rP  c                 C   s   t | tS rh  )r   list_from_dependsdatasources)dependsr2   r2   r3   get_datasource_list  r   rd  rh  )r,   )r  	functoolsr   os.pathrN   r  xml.etree.ElementTreeetreeElementTreer  enumr   pathlibr   r   r   typingr   r   r   r	   	cloudinitr
   loggingr   r   r   r   r   cloudinit.eventr   r   cloudinit.net.dhcpr   r   r   cloudinit.net.ephemeralr   cloudinit.reportingr   cloudinit.sources.azurer   r   r   r   cloudinit.sources.helpersr   cloudinit.sources.helpers.azurer   r   r   r   r    r!   r"   r#   r$   r%   r&   r'   r(   r)   r*   cloudinit.url_helperr+   cryptpartialrand_strr/   __annotations__r0   AttributeErrorpasslibhashsha512_crypt	getLoggerr=   ry   DS_NAMErS  rQ  
DEFAULT_FSAGENT_SEED_DIRr5  r7   rE   r   r\  rX   r\   rb   rm   rt   r}   r   r   r   r   r   r
  res_diskrz   r   rR  r   r  DEF_EPHEMERAL_LABELr  r   r   r  r  r  r  rd  r  r  r  r  r  rT  r  r%  r/  r   r	  r  r  r  r  rP  DataSourceAzureNetDEP_FILESYSTEMrb  rd  r2   r2   r2   r3   <module>   s  
D

	
+




         %



k+
1


G&
