HEX
Server: Apache/2.4.52 (Ubuntu)
System: Linux ip-10-0-8-47 6.8.0-1021-aws #23~22.04.1-Ubuntu SMP Tue Dec 10 16:31:58 UTC 2024 aarch64
User: ubuntu (1000)
PHP: 8.1.2-1ubuntu2.22
Disabled: NONE
Upload Files
File: //lib/python3/dist-packages/cloudinit/sources/helpers/__pycache__/azure.cpython-310.pyc
o

�Ad(��@s�ddlZddlZddlZddlZddlZddlZddlZddlZddlZddl	Z	ddl
mZddlmZddl
mZddlmZmZddlmZmZmZmZmZddlmZddlmZdd	lmZmZmZmZm Z m!Z!m"Z"dd
l#m$Z$ddl%m&Z&e�'e(�Z)dZ*d
Z+dZ,dZ-dZ.dZ/dZ0e$j1dddd�Z2dZ3ed�Z4dede4fdede4ffdd�Z5dd�Z6e5d d!��Z7e5d"d#��Z8dd$�d%e9de$j:fd&d'�Z;d(d)�Z<e5e&d*fd+d,��Z=e5d-d.��Z>ed/d0��Z?d1d2�Z@e5dd3d4d5�d6e9d7eAd8eeBd9eCd:eCde jDfd;d<��ZEd=e9d>e9d?e9deBfd@dA�ZFGdBdC�dC�ZGGdDdE�dEeH�ZIGdFdG�dG�ZJGdHdI�dI�ZKGdJdK�dK�ZLGdLdM�dM�ZMe5		d_dNe9dOeee9dPee9fdQdR��ZNe5dNe9fdSdT��ZOdUdV�ZPGdWdX�dXeH�ZQGdYdZ�dZeH�ZRGd[d\�d\ejS�ZTGd]d^�d^�ZUdS)`�N)�contextmanager)�datetime)�ENOENT)�sleep�time)�Callable�List�Optional�TypeVar�Union)�ElementTree)�escape)�distros�dmi�subp�
temp_utils�
url_helper�util�version)�events)�CFG_BUILTINz
168.63.129.16�boot-telemetryzsystem-info�
diagnostic�
compressedi�z'/run/cloud-init/log_pushed_to_kvp_indexzazure-dsz initialize reporter for azure dsT)�name�description�reporting_enabledz�The VM encountered an error during deployment. Please visit https://aka.ms/linuxprovisioningerror for more information on remediation.�T�func.�returncs�fdd�}|S)NcsFtj�j�jtd���|i|��Wd�S1swYdS)N�rr�parent)r�ReportEventStack�__name__�azure_ds_reporter)�args�kwargs�r��A/usr/lib/python3/dist-packages/cloudinit/sources/helpers/azure.py�impl9s�$�z)azure_ds_telemetry_reporter.<locals>.implr()rr*r(r'r)�azure_ds_telemetry_reporter8sr+cCs\||krdSddd�}|�d�}d�||d�||d�||d�|d|d	g�}||kS)z�
    Azure stores the instance ID with an incorrect byte ordering for the
    first parts. This corrects the byte order such that it is consistent with
    that returned by the metadata service.
    F�cSs(dd�t�|d�D�}|��d�|�S)NcSsg|]}|�qSr(r()�.0�byter(r(r)�
<listcomp>Nsz<is_byte_swapped.<locals>.swap_bytestring.<locals>.<listcomp>r,�)�textwrap�wrap�reverse�join)�s�width�ddr(r(r)�swap_bytestringMs
z(is_byte_swapped.<locals>.swap_bytestring�-r���N)r,)�splitr4)�previous_id�
current_idr8�parts�
swapped_idr(r(r)�is_byte_swappedDs




��
rBc
Cs�t��std��t�d�z
tt��tt���}Wnt	y+}ztd�|�d}~wwz*t
j
gd�dd�\}}d}|rGd|vrG|�d�d	}|sMtd
��|t|�d}Wn&t
jyj}ztd|�|�d}~wt	y|}ztd
|�|�d}~wwz*t
j
gd�dd�\}}d}|r�d|vr�|�d�d	}|s�td��|t|�d}Wn&t
jy�}ztd|�|�d}~wt	y�}ztd|�|�d}~wwt
�tddt�|���dt�|���dt�|���dft
j�}t
�|�|S)z[Report timestamps related to kernel initialization and systemd
    activation of cloud-initz1distro not using systemd, skipping boot telemetryzCollecting boot telemetryz*Failed to determine kernel start timestampN)�	systemctl�show�-p�UserspaceTimestampMonotonicT)�capture�=r:z8Failed to parse UserspaceTimestampMonotonic from systemdi@Bz-Failed to get UserspaceTimestampMonotonic: %sz<Failed to parse UserspaceTimestampMonotonic from systemd: %s)rCrDzcloud-init-localrE�InactiveExitTimestampMonotonicz;Failed to parse InactiveExitTimestampMonotonic from systemdz0Failed to get InactiveExitTimestampMonotonic: %sz?Failed to parse InactiveExitTimestampMonotonic from systemd: %srz5kernel_start=%s user_start=%s cloudinit_activation=%s�Z)r�uses_systemd�RuntimeError�LOG�debug�floatrr�uptime�
ValueErrorrr=�ProcessExecutionErrorr�ReportingEvent�BOOT_EVENT_TYPEr�utcfromtimestamp�	isoformat�DEFAULT_EVENT_ORIGIN�report_event)�kernel_start�e�out�_�tsm�
user_start�cloudinit_activation�evtr(r(r)�get_boot_telemetry`s�

��
���������
�
������������
rac
Csbt��}t�tddt��|d|d|dd|dd|dd|d	ftj�}t�|�|S)
z%Collect and report system informationzsystem informationztcloudinit_version=%s, kernel_version=%s, variant=%s, distro_name=%s, distro_version=%s, flavor=%s, python_version=%s�release�variant�distrr:r,�python)	r�system_inforrS�SYSTEMINFO_EVENT_TYPEr�version_stringrWrX)�infor`r(r(r)�get_system_info�s$


���
rj��logger_func�msgcCs6t|�r||�t�td|tj�}tj|dhd�|S)zReport a diagnostic eventzdiagnostic message�log��excluded_handler_types)�callablerrS�DIAGNOSTIC_EVENT_TYPErWrX)rmrlr`r(r(r)�report_diagnostic_event�s�rscCsNt�t�|��}d|�d�d�}t�t|t�	|�tj
�}tj|hd�d�|S)zReport a compressed eventzgz+b64�ascii)�encoding�data>rn�print�webhookro)�base64�encodebytes�zlib�compress�decoderrS�COMPRESSED_EVENT_TYPE�json�dumpsrWrX)�
event_name�
event_content�compressed_data�
event_datar`r(r(r)�report_compressed_event�s���r��def_log_filec
CsVt�}t�d�zNt|d��?}|�dtj�t|��t	|�}t
d�|��||�tjd�|�|tj�t
d|���t�tt|����Wd�n1sPwYWntys}zt
dt|�tjd�WYd}~nd}~wwt�d	�ztjd
gddd
�\}}t
d
|�WdSty�}zt
dt|�tjd�WYd}~dSd}~ww)azPush a portion of cloud-init.log file or the whole file to KVP
    based on the file size.
    The first time this function is called after VM boot, It will push the last
    n bytes of the log file such that n < MAX_LOG_TO_KVP_LENGTH
    If called again on the same boot, it continues from where it left off.
    In addition to cloud-init.log, dmesg log will also be collected.z"Dumping cloud-init.log file to KVP�rbrzMDumping last {0} bytes of cloud-init.log file to KVP starting from index: {1}rkzcloud-init.logNz#Exception when dumping log file: %szDumping dmesg log to KVP�dmesgFT)r}rGz$Exception when dumping dmesg log: %s)�%get_last_log_byte_pushed_to_kvp_indexrMrN�open�seek�os�SEEK_END�max�tell�MAX_LOG_TO_KVP_LENGTHrs�format�SEEK_SETr��readr�
write_file�LOG_PUSHED_TO_KVP_INDEX_FILE�str�	Exception�repr�warningr)�	file_name�start_index�f�
seek_index�exr[r\r(r(r)�push_log_to_kvp�sD	
���
���

���r�c
Cszttd��}t|���Wd�WS1swYWdStyI}z|jtkr>tdt|�t	j
d�WYd}~dSWYd}~dSd}~wtyf}ztdt|�t	j
d�WYd}~dSd}~wty�}ztdt|�t	j
d�WYd}~dSd}~ww)N�rz0Reading LOG_PUSHED_TO_KVP_INDEX_FILE failed: %s.rkz2Invalid value in LOG_PUSHED_TO_KVP_INDEX_FILE: %s.z2Failed to get the last log byte pushed to KVP: %s.r)
r�r��intr��IOError�errnorrsr�rMr�rQr�)r�rZr(r(r)r�s<
$��

�
���
�	��
���r�c	cs@�t��}t�tj�|��zdVWt�|�dSt�|�w�N)r��getcwd�chdir�path�
expanduser)�newdir�prevdirr(r(r)�cd7s�r�cCsx|�dd�}t|�dkr2d}|�d�D]}t|�dkrd|}||7}qt�dt|�dd�d��}n|�d	�}t�|�S)
N�\r0r<�:r:�0z>L��utf-8)	�replace�lenr=�struct�packr��encode�socket�	inet_ntoa)�fallback_lease_value�unescaped_value�
hex_string�hex_pair�packed_bytesr(r(r)�get_ip_from_lease_valueAs


r���)rv�retry_sleep�timeout_minutes�url�headersrvr�r�c	
Cs�|dt�}d}d}|sT|d7}ztj|||dd�}Wn7tjyM}z$td||||j|jftjd�t�||ksBd	t	|�vrC�WYd}~nd}~wwt
|�|r
td
||ftjd�|S)z�Readurl wrapper for querying wireserver.

    :param retry_sleep: Time to sleep before retrying.
    :param timeout_minutes: Retry up to specified number of minutes.
    :raises UrlError: on error fetching data.
    �<rNr:)r�r�)r�rv�timeoutzdFailed HTTP request with Azure endpoint %s during attempt %d with exception: %s (code=%r headers=%r)rkzNetwork is unreachablez@Successful HTTP request with Azure endpoint %s after %d attempts)rr�readurl�UrlErrorrs�coder�rMrNr�r)	r�r�rvr�r�r��attempt�responserZr(r(r)�http_with_retriesOsD���
�
�������r��username�hostname�
disableSshPwdcCs$t�d�}|j|||d�}|�d�S)Na.        <ns0:Environment xmlns:ns0="http://schemas.dmtf.org/ovf/environment/1"
         xmlns:ns1="http://schemas.microsoft.com/windowsazure"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
          <ns1:ProvisioningSection>
            <ns1:Version>1.0</ns1:Version>
            <ns1:LinuxProvisioningConfigurationSet>
              <ns1:ConfigurationSetType>LinuxProvisioningConfiguration
              </ns1:ConfigurationSetType>
              <ns1:UserName>{username}</ns1:UserName>
              <ns1:DisableSshPasswordAuthentication>{disableSshPwd}
              </ns1:DisableSshPasswordAuthentication>
              <ns1:HostName>{hostname}</ns1:HostName>
            </ns1:LinuxProvisioningConfigurationSet>
          </ns1:ProvisioningSection>
          <ns1:PlatformSettingsSection>
            <ns1:Version>1.0</ns1:Version>
            <ns1:PlatformSettings>
              <ns1:ProvisionGuestAgent>true</ns1:ProvisionGuestAgent>
            </ns1:PlatformSettings>
          </ns1:PlatformSettingsSection>
        </ns0:Environment>
        )r�r�r�r�)r1�dedentr�r�)r�r�r��OVF_ENV_TEMPLATE�retr(r(r)�build_minimal_ovf�s��
r�c@sLeZdZddd�Zdd�Zddejfdd	�Z	
ddee	dejfdd
�Z
d
S)�AzureEndpointHttpClient�WALinuxAgentz
2012-11-30)zx-ms-agent-namezx-ms-versioncCsd|d�|_dS)N�DES_EDE3_CBC)zx-ms-cipher-namez!x-ms-guest-agent-public-x509-cert)�extra_secure_headers)�self�certificater(r(r)�__init__�s�z AzureEndpointHttpClient.__init__FrcCs,|j}|r|j��}|�|j�t||d�S)N)r�)r��copy�updater�r�)r�r��securer�r(r(r)�get�s

zAzureEndpointHttpClient.getNrvcCs0|j}|dur|j��}|�|�t|||d�S)N)rvr�)r�r�r�r�)r�r�rv�
extra_headersr�r(r(r)�post�s


zAzureEndpointHttpClient.post)F�NN)r#�
__module__�__qualname__r�r�r�UrlResponser�r	�bytesr�r(r(r(r)r��s����r�c@seZdZdZdS)�InvalidGoalStateXMLExceptionz9Raised when GoalState XML is invalid or has missing data.N)r#r�r��__doc__r(r(r(r)r��sr�c	@s:eZdZ	ddeeefdededdfdd�Zd	d
�Z	dS)�	GoalStateT�unparsed_xml�azure_endpoint_client�need_certificaterNc
Cs ||_zt�|�|_Wntjy"}z
td|tjd��d}~ww|�d�|_	|�d�|_
|�d�|_dD]}t||�durOd|}t|tjd�t
|��q7d|_|�d	�}|dur�|r�tjd
dtd��|jj|d
d�j|_|jdurzt
d��Wd�dS1s�wYdSdSdS)ahParses a GoalState XML string and returns a GoalState object.

        @param unparsed_xml: string representing a GoalState XML.
        @param azure_endpoint_client: instance of AzureEndpointHttpClient.
        @param need_certificate: switch to know if certificates is needed.
        @return: GoalState object representing the GoalState XML string.
        z!Failed to parse GoalState XML: %srkNz./Container/ContainerIdz4./Container/RoleInstanceList/RoleInstance/InstanceIdz
./Incarnation)�container_id�instance_id�incarnationzMissing %s in GoalState XMLzD./Container/RoleInstanceList/RoleInstance/Configuration/Certificateszget-certificates-xmlzget certificates xmlr T)r�z/Azure endpoint returned empty certificates xml.)r�r�
fromstring�root�
ParseErrorrsrMr��_text_from_xpathr�r�r��getattrr��certificates_xmlrr"r$r��contents)r�r�r�r�rZ�attrrmr�r(r(r)r��sX
���������
��"��zGoalState.__init__cCs|j�|�}|dur
|jSdSr�)r��find�text)r��xpath�elementr(r(r)r�szGoalState._text_from_xpath)T)
r#r�r�rr�r�r��boolr�r�r(r(r(r)r��s�
���
�7r�c@s�eZdZddd�Zdd�Zdd�Zedd	��Zejd
d	��Ze	dd��Z
ee	d
d���Ze	dd��Z
e	dd��Ze	dd��Ze	dd��ZdS)�OpenSSLManagerzTransportPrivate.pemzTransportCert.pem)�private_keyr�cCst��|_d|_|��dSr�)r�mkdtemp�tmpdir�_certificate�generate_certificate�r�r(r(r)r�s
zOpenSSLManager.__init__cCst�|j�dSr�)r�del_dirr�rr(r(r)�clean_upszOpenSSLManager.clean_upcCs|jSr��r�rr(r(r)r�szOpenSSLManager.certificatecCs
||_dSr�r)r��valuer(r(r)r�s
cCs�t�d�|jdurt�d�dSt|j��:t�ddddddd	d
ddd
|jdd|jdg�d}t|jd�D]}d|vrE||��7}q9||_Wd�n1sSwYt�d�dS)Nz7Generating certificate for communication with fabric...zCertificate already generated.�openssl�reqz-x509z-nodesz-subjz/CN=LinuxTransportz-days�32768z-newkeyzrsa:2048z-keyoutr�z-outr�r0�CERTIFICATEzNew certificate generated.)	rMrNr�r�r�r�certificate_namesr��rstrip)r�r��liner(r(r)r s<


����z#OpenSSLManager.generate_certificatecCs"ddd|g}tj||d�\}}|S)Nr�x509z-noout�rv)r)�action�cert�cmd�resultr\r(r(r)�_run_x509_action@szOpenSSLManager._run_x509_actioncCs*|�d|�}gd�}tj||d�\}}|S)Nz-pubkey)z
ssh-keygenz-iz-m�PKCS8z-fz
/dev/stdinr)rr)r�r��pub_key�
keygen_cmd�ssh_keyr\r(r(r)�_get_ssh_key_from_certGsz%OpenSSLManager._get_ssh_key_from_certcCs6|�d|�}|�d�}||dd��d�}d�|�S)aopenssl x509 formats fingerprints as so:
        'SHA1 Fingerprint=07:3E:19:D1:4D:1C:79:92:24:C6:A0:FD:8D:DA:        B6:A8:BF:27:D4:73
'

        Azure control plane passes that fingerprint as so:
        '073E19D14D1C799224C6A0FD8DDAB6A8BF27D473'
        z-fingerprintrHr:���r�r0)rr�r=r4)r�r��raw_fp�eq�octetsr(r(r)�_get_fingerprint_from_certNs	

z)OpenSSLManager._get_fingerprint_from_certcCs�t�|��d�}|j}ddddd|�d�g}t|j��tjdjd
i|j	��d	d
�
|�d�\}}Wd�|S1s;wY|S)z�Decrypt the certificates XML document using the our private key;
        return the list of certs and private keys contained in the doc.
        z.//DatasMIME-Version: 1.0s<Content-Disposition: attachment; filename="Certificates.p7m"s?Content-Type: application/x-pkcs7-mime; name="Certificates.p7m"s!Content-Transfer-Encoding: base64�r�zuopenssl cms -decrypt -in /dev/stdin -inkey {private_key} -recip {certificate} | openssl pkcs12 -nodes -password pass:T�
)�shellrvNr()rr�r�r�r�r�r�rr�r
r4)r�r��tag�certificates_content�linesr[r\r(r(r)�_decrypt_certs_from_xml\s.����
��z&OpenSSLManager._decrypt_certs_from_xmlc	Csv|�|�}g}i}|��D]+}|�|�t�d|�rg}q
t�d|�r8d�|�}|�|�}|�|�}|||<g}q
|S)z�Given the Certificates XML document, return a dictionary of
        fingerprints and associated SSH keys derived from the certs.z[-]+END .*?KEY[-]+$z[-]+END .*?CERTIFICATE[-]+$�
)r$�
splitlines�append�re�matchr4rr)	r�r�r[�current�keysrr�r�fingerprintr(r(r)�parse_certificatesus




�z!OpenSSLManager.parse_certificatesN)r#r�r�r
r�r�propertyr��setterr+r�staticmethodrrrr$r-r(r(r(r)r�	s.�





r�c@s�eZdZe�d�Ze�d�ZdZdZdZ	dZ
deded	e
d
dfdd
�Zeddd��Zede
d
dfdd��Z		dde
de
de
de
d
ef
dd�Zeded
dfdd��ZdS)�GoalStateHealthReportera�        <?xml version="1.0" encoding="utf-8"?>
        <Health xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xmlns:xsd="http://www.w3.org/2001/XMLSchema">
          <GoalStateIncarnation>{incarnation}</GoalStateIncarnation>
          <Container>
            <ContainerId>{container_id}</ContainerId>
            <RoleInstanceList>
              <Role>
                <InstanceId>{instance_id}</InstanceId>
                <Health>
                  <State>{health_status}</State>
                  {health_detail_subsection}
                </Health>
              </Role>
            </RoleInstanceList>
          </Container>
        </Health>
        z�        <Details>
          <SubStatus>{health_substatus}</SubStatus>
          <Description>{health_description}</Description>
        </Details>
        �Ready�NotReady�ProvisioningFailedi�
goal_stater��endpointrNcCs||_||_||_dS)a?Creates instance that will report provisioning status to an endpoint

        @param goal_state: An instance of class GoalState that contains
            goal state info such as incarnation, container id, and instance id.
            These 3 values are needed when reporting the provisioning status
            to Azure
        @param azure_endpoint_client: Instance of class AzureEndpointHttpClient
        @param endpoint: Endpoint (string) where the provisioning status report
            will be sent to
        @return: Instance of class GoalStateHealthReporter
        N)�_goal_state�_azure_endpoint_client�	_endpoint)r�r5r�r6r(r(r)r��s
z GoalStateHealthReporter.__init__c
Csv|j|jj|jj|jj|jd�}t�d�z|j|d�Wnt	y3}z
t
d|tjd��d}~wwt�d�dS)N)r�r�r��statusz Reporting ready to Azure fabric.��documentz#exception while reporting ready: %srkzReported ready to Azure fabric.)
�build_reportr7r�r�r��PROVISIONING_SUCCESS_STATUSrMrN�_post_health_reportr�rs�errorri)r�r<rZr(r(r)�send_ready_signal�s$�
���z)GoalStateHealthReporter.send_ready_signalrc
Csv|j|jj|jj|jj|j|j|d�}z|j|d�Wnty3}zd|}t	|t
jd��d}~wwt
�d�dS)N)r�r�r�r:�	substatusrr;z%exception while reporting failure: %srkz!Reported failure to Azure fabric.)
r=r7r�r�r��PROVISIONING_NOT_READY_STATUS�PROVISIONING_FAILURE_SUBSTATUSr?r�rsrMr@r�)r�rr<rZrmr(r(r)�send_failure_signal�s"���z+GoalStateHealthReporter.send_failure_signalr�r�r�r:c	Csbd}|dur|jjt|�t|d|j��d�}|jjtt|��t|�t|�t|�|d�}|�d�S)Nr0)�health_substatus�health_description)r�r�r��
health_status�health_detail_subsectionr�)�%HEALTH_DETAIL_SUBSECTION_XML_TEMPLATEr�r
�"HEALTH_REPORT_DESCRIPTION_TRIM_LEN�HEALTH_REPORT_XML_TEMPLATEr�r�)	r�r�r�r�r:rBr�
health_detail�
health_reportr(r(r)r=�s 	��
�
z$GoalStateHealthReporter.build_reportr<cCsHt�td�t�d�d�|j�}|jj||ddid�t�d�dS)Nrz&Sending health report to Azure fabric.zhttp://{}/machine?comp=healthzContent-Typeztext/xml; charset=utf-8)rvr�z/Successfully sent health report to Azure fabric)r�rrMrNr�r9r8r�)r�r<r�r(r(r)r?	s
�z+GoalStateHealthReporter._post_health_report�rNr�)r#r�r�r1r�rLrJr>rCrDrKr�r�r�r�r+rArEr�r=r?r(r(r(r)r1�sN��	���
������
�r1c@s�eZdZdefdd�Zdd�Zeddd	��Ze	ddee	efd
d��Z
ededdfd
d��Zedede
fdd��Zedefdd��Zedeeefdede
fdd��Zede
dedefdd��Zedededefdd��ZdS) �WALinuxAgentShimr6cCs||_d|_d|_dSr�)r6�openssl_managerr�)r�r6r(r(r)r�,s
zWALinuxAgentShim.__init__cCs|jdur|j��dSdSr�)rQrrr(r(r)r1s
�zWALinuxAgentShim.clean_uprNc
CsXzt�d�t�d|g�WdSty+}ztd|tjd�WYd}~dSd}~ww)NzEjecting the provisioning iso�ejectz(Failed ejecting the provisioning iso: %srk)rMrNrr�rs)r��iso_devrZr(r(r)�	eject_iso5s
���zWALinuxAgentShim.eject_isocCs�d}|jdur|durt�|_|jj}|jdurt|�|_|j|dud�}d}|dur1|�||�}t||j|j�}|durB|�	|�|�
�|S)a�Gets the VM's GoalState from Azure, uses the GoalState information
        to report ready/send the ready signal/provisioning complete signal to
        Azure, and then uses pubkey_info to filter and obtain the user's
        pubkeys from the GoalState.

        @param pubkey_info: List of pubkey values and fingerprints which are
            used to filter and obtain the user's pubkey values from the
            GoalState.
        @return: The list of user's authorized pubkey values.
        N�r�)rQr�r�r�r��_fetch_goal_state_from_azure�_get_user_pubkeysr1r6rTrA)r��pubkey_inforS�http_client_certificater5�ssh_keys�health_reporterr(r(r)�"register_with_azure_and_fetch_data@s*
��
�
z3WALinuxAgentShim.register_with_azure_and_fetch_datarcCs@|jdur
td�|_|jdd�}t||j|j�}|j|d�dS)z�Gets the VM's GoalState from Azure, uses the GoalState information
        to report failure/send provisioning failure signal to Azure.

        @param: user visible error description of provisioning failure.
        NFrU�r)r�r�rVr1r6rE)r�rr5r[r(r(r)�&register_with_azure_and_report_failurefs


�z7WALinuxAgentShim.register_with_azure_and_report_failurer�cCs|��}|�||�S)aFetches the GoalState XML from the Azure endpoint, parses the XML,
        and returns a GoalState object.

        @param need_certificate: switch to know if certificates is needed.
        @return: GoalState object representing the GoalState XML
        )�"_get_raw_goal_state_xml_from_azure�_parse_raw_goal_state_xml)r�r��unparsed_goal_state_xmlr(r(r)rVus
�z-WALinuxAgentShim._fetch_goal_state_from_azurec
Cs�t�d�d�|j�}z tjddtd��|j�|�}Wd�n1s%wYWnt	yA}z
t
d|tjd��d}~wwt�d	�|j
S)
z�Fetches the GoalState XML from the Azure endpoint and returns
        the XML as a string.

        @return: GoalState XML string
        zRegistering with Azure...z!http://{}/machine/?comp=goalstatezgoalstate-retrievalzretrieve goalstater Nz9failed to register with Azure and fetch GoalState XML: %srkz#Successfully fetched GoalState XML.)rMrir�r6rr"r$r�r�r�rsr�rNr�)r�r�r�rZr(r(r)r_�s.
�������
z3WALinuxAgentShim._get_raw_goal_state_xml_from_azurerac
Cstz	t||j|�}Wnty}z
td|tjd��d}~wwd�d|jd|jd|j	g�}t|tj
d�|S)aParses a GoalState XML string and returns a GoalState object.

        @param unparsed_goal_state_xml: GoalState XML string
        @param need_certificate: switch to know if certificates is needed.
        @return: GoalState object representing the GoalState XML
        z"Error processing GoalState XML: %srkNz, zGoalState XML container id: %szGoalState XML instance id: %szGoalState XML incarnation: %s)r�r�r�rsrMr�r4r�r�r�rN)r�rar�r5rZrmr(r(r)r`�s,������z*WALinuxAgentShim._parse_raw_goal_state_xmlr5rXcCsHg}|jdur"|dur"|jdur"t�d�|j�|j�}|�||�}|S)a�Gets and filters the VM admin user's authorized pubkeys.

        The admin user in this case is the username specified as "admin"
        when deploying VMs on Azure.
        See https://docs.microsoft.com/en-us/cli/azure/vm#az-vm-create.
        cloud-init expects a straightforward array of keys to be dropped
        into the admin user's authorized_keys file. Azure control plane exposes
        multiple public keys to the VM via wireserver. Select just the
        admin user's key(s) and return them, ignoring any other certs.

        @param goal_state: GoalState object. The GoalState object contains
            a certificate XML, which contains both the VM user's authorized
            pubkeys and other non-user pubkeys, which are used for
            MSI and protected extension handling.
        @param pubkey_info: List of VM user pubkey dicts that were previously
            obtained from provisioning data.
            Each pubkey dict in this list can either have the format
            pubkey['value'] or pubkey['fingerprint'].
            Each pubkey['fingerprint'] in the list is used to filter
            and obtain the actual pubkey value from the GoalState
            certificates XML.
            Each pubkey['value'] requires no further processing and is
            immediately added to the return list.
        @return: A list of the VM user's authorized pubkey values.
        Nz/Certificate XML found; parsing out public keys.)r�rQrMrNr-�_filter_pubkeys)r�r5rXrZ�keys_by_fingerprintr(r(r)rW�s���
�z"WALinuxAgentShim._get_user_pubkeysrccCs|g}|D]7}d|vr|dr|�|d�qd|vr5|dr5|d}||vr.|�||�qt�d|�qt�d|�q|S)a8Filter and return only the user's actual pubkeys.

        @param keys_by_fingerprint: pubkey fingerprint -> pubkey value dict
            that was obtained from GoalState Certificates XML. May contain
            non-user pubkeys.
        @param pubkey_info: List of VM user pubkeys. Pubkey values are added
            to the return list without further processing. Pubkey fingerprints
            are used to filter and obtain the actual pubkey values from
            keys_by_fingerprint.
        @return: A list of the VM user's authorized pubkey values.
        rr,zIovf-env.xml specified PublicKey fingerprint %s not found in goalstate XMLzFovf-env.xml specified PublicKey with neither value nor fingerprint: %s)r'rMr�)rcrXr+�pubkeyr,r(r(r)rb�s"
��z WALinuxAgentShim._filter_pubkeysrOr�)r#r�r�r�r�rr+rTr	rr\r^r�r�rVr�r_rr`�listrWr0�dictrbr(r(r(r)rP+sL
�
�%��
���!���)rPr6rXrScCs.t|d�}z|j||d�W|��S|��w)N�r6)rXrS)rPr\r)r6rXrS�shimr(r(r)�get_metadata_from_fabrics
�ricCs4t|d�}t}z
|j|d�W|��dS|��w)Nrgr])rP�+DEFAULT_REPORT_FAILURE_USER_VISIBLE_MESSAGEr^r)r6rhrr(r(r)�report_failure_to_fabrics

rkcCs(td|tjd�td|tjd�dS)Nzdhclient output stream: %srkzdhclient error stream: %s)rsrMrN)r[�errr(r(r)�dhcp_log_cb)s
�

�rmc@�eZdZdS)�BrokenAzureDataSourceN�r#r�r�r(r(r(r)ro2�roc@rn)�NonAzureDataSourceNrpr(r(r(r)rr6rqrrc@s&eZdZdZededfdd��ZdS)�ChassisAssetTagz 7783-7084-3265-9085-8269-3286-77rcCsZt�d�}z||�}Wntytd|tjd�YdSwtd||jftjd�|S)z�Check platform environment to report if this datasource may run.

        :returns: ChassisAssetTag if matching tag found, else None.
        zchassis-asset-tagzNon-Azure chassis asset tag: %rrkNz Azure chassis asset tag: %r (%s))r�
read_dmi_datarQrsrMrNr)�cls�	asset_tagr!r(r(r)�query_system=s
���zChassisAssetTag.query_systemN)r#r�r��AZURE_CLOUD�classmethodr	rwr(r(r(r)rs:srsc@s�eZdZddd�Zddddddddd�deedeed	eed
eedeedeee	d
edeeddfdd�Z
defdd�Zededdfdd��Z
	d'dededefdd�Z			d(dedededefdd �Zd!d"�Zd#d$�Zd%d&�ZdS))�	OvfEnvXmlz)http://schemas.dmtf.org/ovf/environment/1z)http://schemas.microsoft.com/windowsazure)�ovf�waNF�r��passwordr��custom_data�disable_ssh_password_auth�public_keys�preprovisioned_vm�preprovisioned_vm_typer�r~r�rr�r�r�r�rc	Cs8||_||_||_||_||_|pg|_||_||_dSr�r})	r�r�r~r�rr�r�r�r�r(r(r)r�Zs

zOvfEnvXml.__init__cCs|j|jkSr�)�__dict__)r��otherr(r(r)�__eq__oszOvfEnvXml.__eq__�ovf_env_xmlc
Cspzt�|�}Wntjy}z	d|}t|�|�d}~ww|�d|j�s)td��t�}|�|�|�	|�|S)z�Parser for ovf-env.xml data.

        :raises NonAzureDataSource: if XML is not in Azure's format.
        :raises BrokenAzureDataSource: if XML is unparseable or invalid.
        zInvalid ovf-env.xml: %sNz./wa:ProvisioningSectionz=Ignoring non-Azure ovf-env.xml: ProvisioningSection not found)
rr�r�ror��
NAMESPACESrrrz�&_parse_linux_configuration_set_section� _parse_platform_settings_section)rur�r�rZ�	error_str�instancer(r(r)�
parse_textrs
���

zOvfEnvXml.parse_textr|r�required�	namespacecCsl|�d||ftj�}t|�dkr"d|}t�|�|r t|��dSt|�dkr2td|t|�f��|dS)Nz./%s:%sr�#No ovf-env.xml configuration for %rr:�:Multiple configuration matches in ovf-exml.xml for %r (%d))�findallrzr�r�rMrNro)r��noderr�r��matchesrmr(r(r)�_find�s �

��zOvfEnvXml._find�
decode_base64�
parse_boolc
Cs�|�d|tj�}t|�dkr d|}t�|�|rt|��|St|�dkr0td|t|�f��|dj}	|	dur;|}	|rK|	durKt�	d�
|	����}	|rRt�
|	�}	|	S)Nz./wa:rr�r:r�r0)r�rzr�r�rMrNror�ry�	b64decoder4r=r�translate_bool)
r�r�rr�r�r��defaultr�rmrr(r(r)�_parse_property�s*	

��

zOvfEnvXml._parse_propertycCs�|j|ddd�}|j|ddd�}|j|dddd�|_|j|ddd�|_|j|d	dd�|_|j|d
dd�|_|j|dddd�|_|�|�dS)
N�ProvisioningSectionT�r��!LinuxProvisioningConfigurationSet�
CustomDataF)r�r��UserName�UserPassword�HostName� DisableSshPasswordAuthentication)r�r�)r�r�rr�r~r�r��_parse_ssh_section)r�r��provisioning_section�
config_setr(r(r)r��s<�������z0OvfEnvXml._parse_linux_configuration_set_sectioncCsL|j|ddd�}|j|ddd�}|j|ddddd�|_|j|ddd�|_dS)	N�PlatformSettingsSectionTr��PlatformSettings�PreprovisionedVmF)r�r�r��PreprovisionedVMType)r�r�r�r�)r�r��platform_settings_section�platform_settingsr(r(r)r��s$����z*OvfEnvXml._parse_platform_settings_sectionc	Cs�g|_|j|ddd�}|durdS|j|ddd�}|durdS|�dtj�D]'}|j|ddd�}|j|ddd�}|j|dd	dd
�}|||d�}|j�|�q&dS)N�SSHFr��
PublicKeysz./wa:PublicKey�Fingerprint�Path�Valuer0)r�r�)r,r�r)r�r�r�rzr�r�r')	r�r��ssh_section�public_keys_section�
public_keyr,r�rrr(r(r)r��s2������zOvfEnvXml._parse_ssh_section)r|)FFN)r#r�r�r�r	r�r�r�rrfr�r�ryr�r�r�r�r�r�r(r(r(r)rzTsr�������
�	�
�
����
�����
�$"rzr�)Vry�enumr�loggingr�r(r�r�r1r{�
contextlibrrr�rrr�typingrrr	r
r�	xml.etreer�xml.sax.saxutilsr
�	cloudinitrrrrrrr�cloudinit.reportingr�cloudinit.settingsr�	getLoggerr#rM�DEFAULT_WIRESERVER_ENDPOINTrTrgrrr~r�r�r"r$rjrr+rBrarjr�rSrsr�r�r�r�r�rfr�r�r�r�r�r�r�r�r�r�r1rPrirkrmrorr�Enumrsrzr(r(r(r)�<module>s�$
��"
S
��
�(

	�������6���
�"?"f��
��