HEX
Server: Apache
System: Linux scp1.abinfocom.com 5.4.0-216-generic #236-Ubuntu SMP Fri Apr 11 19:53:21 UTC 2025 x86_64
User: confeduphaar (1010)
PHP: 8.1.33
Disabled: exec,passthru,shell_exec,system
Upload Files
File: //usr/lib/python3/dist-packages/cloudinit/sources/helpers/__pycache__/azure.cpython-38.pyc
U

Ӈg���	@srddlZddlZddlZddlZddlZddlZddlZddlmZddl	m	Z	m
Z
ddlmZmZddl
mZmZmZmZmZddlmZddlmZddlmZmZmZmZmZmZdd	lm Z dd
l!m"Z"e�#e$�Z%dZ&dZ'd
Z(dZ)dZ*e j+dddd�Z,ed�Z-ede-fede-fd�dd�Z.e.dd��Z/e.dd��Z0dd�e1e j2d�dd �Z3d!d"�Z4e.d#d$��Z5ed%d&��Z6e.dd'd(d)�e1e7ee8e9e9ej:d*�d+d,��Z;e1e1e1e8d-�d.d/�Z<Gd0d1�d1�Z=Gd2d3�d3e>�Z?Gd4d5�d5�Z@Gd6d7�d7�ZAGd8d9�d9�ZBGd:d;�d;�ZCe.dIe1ejDeee1ee1d<�d=d>��ZEe.e1d?d@�dAdB��ZFdCdD�ZGGdEdF�dFe>�ZHGdGdH�dH�ZIdS)J�N)�contextmanager)�datetime�timezone)�sleep�time)�Callable�List�Optional�TypeVar�Union)�ElementTree)�escape)�distros�subp�
temp_utils�
url_helper�util�version)�events)�errorsz
168.63.129.16�boot-telemetryzsystem-infoZ
diagnosticZ
compressedzazure-dsz initialize reporter for azure dsT)�name�descriptionZreporting_enabled�T.)�func�returncs�fdd�}|S)Nc
s6tj�j�jtd���||�W5QR�SQRXdS)N�rr�parent)r�ReportEventStack�__name__�azure_ds_reporter)�args�kwargs�r��A/usr/lib/python3/dist-packages/cloudinit/sources/helpers/azure.py�impl*s�z)azure_ds_telemetry_reporter.<locals>.implr$)rr&r$r#r%�azure_ds_telemetry_reporter)sr'cCs8t��std��t�d�ztt��tt���}Wn,t	k
r`}ztd�|�W5d}~XYnXzXt
j
ddddgd	d
�\}}d}|r�d|kr�|�d�d}|s�td
��|t|�d}Wnbt
jk
r�}ztd|�|�W5d}~XYn2t	k
�r}ztd|�|�W5d}~XYnXz`t
j
dddddgd	d
�\}}d}|�r^d|k�r^|�d�d}|�sltd��|t|�d}Wndt
jk
�r�}ztd|�|�W5d}~XYn2t	k
�r�}ztd|�|�W5d}~XYnXt
�tddt�|tj���t�|tj���t�|tj���ft
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 timestampNZ	systemctlZshowz-pZUserspaceTimestampMonotonicT)�capture�=�z8Failed to parse UserspaceTimestampMonotonic from systemdi@Bz-Failed to get UserspaceTimestampMonotonic: %sz<Failed to parse UserspaceTimestampMonotonic from systemd: %szcloud-init-localZInactiveExitTimestampMonotonicz;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)rZuses_systemd�RuntimeError�LOG�debug�floatrrZuptime�
ValueErrorr�splitZProcessExecutionErrorr�ReportingEvent�BOOT_EVENT_TYPErZ
fromtimestamprZutcZ	isoformat�DEFAULT_EVENT_ORIGIN�report_event)Zkernel_start�e�out�_ZtsmZ
user_startZcloudinit_activation�evtr$r$r%�get_boot_telemetry5s�

�
�������

����������
r9c
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�releaseZvariantZdistrr*��python)	rZsystem_inforr1�SYSTEMINFO_EVENT_TYPErZversion_stringr3r4)�infor8r$r$r%�get_system_info�s$


���
r?��logger_func)�msgrcCs6t|�r||�t�td|tj�}tj|dhd�|S)zReport a diagnostic eventzdiagnostic message�log�Zexcluded_handler_types)�callablerr1�DIAGNOSTIC_EVENT_TYPEr3r4)rBrAr8r$r$r%�report_diagnostic_event�s�rGcCsPt�t�|��}d|�d�d�}t�t|t�	|�tj
�}tj|dddhd�|S)zReport a compressed eventzgz+b64�ascii)�encoding�datarC�printZwebhookrD)�base64Zencodebytes�zlib�compress�decoderr1�COMPRESSED_EVENT_TYPE�json�dumpsr3r4)Z
event_nameZ
event_contentZcompressed_dataZ
event_datar8r$r$r%�report_compressed_event�s���rSc
Cslt�d�z$tjdgddd�\}}td|�Wn8tk
rf}ztdt|�tjd�W5d}~XYnXdS)	zReport dmesg to KVP.zDumping dmesg log to KVPZdmesgFT)rOr(z$Exception when dumping dmesg log: %sr@N)r,r-rrS�	ExceptionrG�repr�warning)r6r7�exr$r$r%�report_dmesg_to_kvp�s

�rXc	cs6t��}t�tj�|��z
dVW5t�|�XdS�N)�os�getcwd�chdir�path�
expanduser)ZnewdirZprevdirr$r$r%�cd�s

r_��)rJ�retry_sleep�timeout_minutes)�url�headersrJrbrcrc	
Cs�|dt�}d}d}|s�|d7}ztj|||dd�}Wq�Wn`tjk
r�}z@td||||j|jftjd�t�||ks�d	t	|�kr��W5d}~XYnXt
|�qtd
||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`rf)rerJ�timeoutzdFailed HTTP request with Azure endpoint %s during attempt %d with exception: %s (code=%r headers=%r)r@zNetwork is unreachablez@Successful HTTP request with Azure endpoint %s after %d attempts)rrZreadurlZUrlErrorrG�coderer,r-�strr)	rdrerJrbrcrgZattempt�responser5r$r$r%�http_with_retries�sB���
�
�
��rk)�username�hostname�
disableSshPwdrcCs$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>
        )rlrmrn�utf-8)�textwrap�dedent�format�encode)rlrmrnZOVF_ENV_TEMPLATEZretr$r$r%�build_minimal_ovfs��rtc@sHeZdZddd�Zdd�Zdejd�dd	�Zdee	ejd�dd
�Z
d
S)�AzureEndpointHttpClientZWALinuxAgentz
2012-11-30)zx-ms-agent-namezx-ms-versioncCsd|d�|_dS)NZDES_EDE3_CBC)zx-ms-cipher-namez!x-ms-guest-agent-public-x509-cert)�extra_secure_headers)�self�certificater$r$r%�__init__Ds�z AzureEndpointHttpClient.__init__F�rcCs,|j}|r |j��}|�|j�t||d�S)N)re)re�copy�updatervrk)rwrd�securerer$r$r%�getJs

zAzureEndpointHttpClient.getN)rJrcCs0|j}|dk	r"|j��}|�|�t|||d�S)N)rJre)rer{r|rk)rwrdrJ�
extra_headersrer$r$r%�postQs


zAzureEndpointHttpClient.post)F)NN)r�
__module__�__qualname__reryr�UrlResponser~r	�bytesr�r$r$r$r%ru>s���ruc@seZdZdZdS)�InvalidGoalStateXMLExceptionz9Raised when GoalState XML is invalid or has missing data.N)rr�r��__doc__r$r$r$r%r�[sr�c@s2eZdZdeeefeedd�dd�Zdd�Z	dS)	�	GoalStateTN)�unparsed_xml�azure_endpoint_client�need_certificaterc
Cs||_zt�|�|_Wn8tjk
rN}ztd|tjd��W5d}~XYnX|�d�|_	|�d�|_
|�d�|_dD]0}t||�dkrxd|}t|tjd�t
|��qxd|_|�d	�}|dk	�r|�rtjd
dtd��.|jj|d
d�j|_|jdk�rt
d��W5QRXdS)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: %sr@Nz./Container/ContainerIdz4./Container/RoleInstanceList/RoleInstance/InstanceIdz
./Incarnation)�container_id�instance_id�incarnationzMissing %s in GoalState XMLzD./Container/RoleInstanceList/RoleInstance/Configuration/Certificateszget-certificates-xmlzget certificates xmlrT)r}z/Azure endpoint returned empty certificates xml.)r��ET�
fromstring�root�
ParseErrorrGr,rV�_text_from_xpathr�r�r��getattrr��certificates_xmlrrr r~�contents)rwr�r�r�r5�attrrBrdr$r$r%ry`sJ
��
���
�zGoalState.__init__cCs|j�|�}|dk	r|jSdSrY)r��find�text)rwZxpath�elementr$r$r%r��szGoalState._text_from_xpath)T)
rr�r�rrir�ru�boolryr�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_keyrxcCst��|_d|_|��dSrY)rZmkdtemp�tmpdir�_certificate�generate_certificate�rwr$r$r%ry�s
zOpenSSLManager.__init__cCst�|j�dSrY)rZdel_dirr�r�r$r$r%�clean_up�szOpenSSLManager.clean_upcCs|jSrY�r�r�r$r$r%rx�szOpenSSLManager.certificatecCs
||_dSrYr�)rw�valuer$r$r%rx�scCs�t�d�|jdk	r"t�d�dSt|j��pt�ddddddd	d
ddd
|jdd|jdg�d}t�|jd��	�D]}d|krx||�
�7}qx||_W5QRXt�d�dS)Nz7Generating certificate for communication with fabric...zCertificate already generated.�opensslZreqz-x509z-nodesz-subjz/CN=LinuxTransportz-daysZ32768z-newkeyzrsa:2048z-keyoutr�z-outrx�ZCERTIFICATEzNew certificate generated.)r,r-rxr_r�r�certificate_namesrZload_text_file�
splitlines�rstrip)rwrx�liner$r$r%r��s<


���z#OpenSSLManager.generate_certificatecCs"ddd|g}tj||d�\}}|S)Nr�Zx509z-noout�rJ)r)�actionZcert�cmd�resultr7r$r$r%�_run_x509_action�szOpenSSLManager._run_x509_actioncCs2|�d|�}ddddddg}tj||d�\}}|S)	Nz-pubkeyz
ssh-keygenz-iz-mZPKCS8z-fz
/dev/stdinr�)r�r)rwrxZpub_keyZ
keygen_cmd�ssh_keyr7r$r$r%�_get_ssh_key_from_cert�s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\n'

        Azure control plane passes that fingerprint as so:
        '073E19D14D1C799224C6A0FD8DDAB6A8BF27D473'
        z-fingerprintr)r*����:r�)r�r�r0�join)rwrxZraw_fp�eqZoctetsr$r$r%�_get_fingerprint_from_cert�s	
z)OpenSSLManager._get_fingerprint_from_certc	Csjt�|��d�}|j}ddddd|�d�g}t|j��*tjdjf|j	�d	d
�
|�d�\}}W5QRX|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�rozuopenssl cms -decrypt -in /dev/stdin -inkey {private_key} -recip {certificate} | openssl pkcs12 -nodes -password pass:T�
)�shellrJ)r�r�r�r�rsr_r�rrrr�r�)rwr��tagZcertificates_content�linesr6r7r$r$r%�_decrypt_certs_from_xml�s$���z&OpenSSLManager._decrypt_certs_from_xmlc	Csv|�|�}g}i}|��D]V}|�|�t�d|�r:g}qt�d|�rd�|�}|�|�}|�|�}|||<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�r��append�re�matchr�r�r�)	rwr�r6Zcurrent�keysr�rxr��fingerprintr$r$r%�parse_certificatess




z!OpenSSLManager.parse_certificatesN)rr�r�r�ryr��propertyrx�setterr'r��staticmethodr�r�r�r�r�r$r$r$r%r��s,�


!



r�c@s�eZdZe�d�Ze�d�ZdZdZdZ	dZ
eee
dd�d	d
�Zedd�dd
��Zee
dd�dd��Zde
e
e
e
ed�dd�Zeedd�dd��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>
        ZReadyZNotReadyZProvisioningFailediN)�
goal_stater��endpointrcCs||_||_||_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)rwr�r�r�r$r$r%ryFsz GoalStateHealthReporter.__init__rzc
Cs�|j|jj|jj|jj|jd�}t�d�z|j|d�Wn6t	k
rp}zt
d|tjd��W5d}~XYnXt�d�dS)N)r�r�r��statusz Reporting ready to Azure fabric.��documentz#exception while reporting ready: %sr@zReported ready to Azure fabric.)
�build_reportr�r�r�r��PROVISIONING_SUCCESS_STATUSr,r-�_post_health_reportrTrG�errorr>)rwr�r5r$r$r%�send_ready_signal[s �
�z)GoalStateHealthReporter.send_ready_signal�rrc
Cs�|j|jj|jj|jj|j|j|d�}z|j|d�Wn:tk
rp}zd|}t	|t
jd��W5d}~XYnXt
�d�dS)N)r�r�r�r��	substatusrr�z%exception while reporting failure: %sr@z!Reported failure to Azure fabric.)
r�r�r�r�r��PROVISIONING_NOT_READY_STATUS�PROVISIONING_FAILURE_SUBSTATUSr�rTrGr,r�rV)rwrr�r5rBr$r$r%�send_failure_signalos�z+GoalStateHealthReporter.send_failure_signal)r�r�r�r�rc	Csbd}|dk	r.|jjt|�t|d|j��d�}|jjtt|��t|�t|�t|�|d�}|�d�S)Nr�)Zhealth_substatusZhealth_description)r�r�r�Z
health_statusZhealth_detail_subsectionro)�%HEALTH_DETAIL_SUBSECTION_XML_TEMPLATErrr
�"HEALTH_REPORT_DESCRIPTION_TRIM_LEN�HEALTH_REPORT_XML_TEMPLATErirs)	rwr�r�r�r�r�rZ
health_detailZ
health_reportr$r$r%r��s 	��
�z$GoalStateHealthReporter.build_report)r�rcCsBtd�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)rJrz/Successfully sent health report to Azure fabric)rr,r-rrr�r�r�)rwr�rdr$r$r%r��s
�z+GoalStateHealthReporter._post_health_report)NN)rr�r�rprqr�r�r�r�r�r�r�ruriryr'r�r�r�r�r�r$r$r$r%r� s<��	���r�c@s�eZdZed�dd�Zdd�Zeejdd�dd	��Z	edeje
eed�d
d��Zeedd�d
d��Z
eeed�dd��Zeed�dd��Zeeeefeed�dd��Zeeeed�dd��Zeeeed�dd��ZdS)�WALinuxAgentShim�r�cCs||_d|_d|_dSrY)r��openssl_managerr�)rwr�r$r$r%ry�szWALinuxAgentShim.__init__cCs|jdk	r|j��dSrY)r�r�r�r$r$r%r��s
zWALinuxAgentShim.clean_upN)�distrorc
CsRt�d�z|�|�Wn4tk
rL}ztd|tjd�W5d}~XYnXdS)NzEjecting the provisioning isoz(Failed ejecting the provisioning iso: %sr@)r,r-Zeject_mediarTrGr�)rw�iso_devr�r5r$r$r%�	eject_iso�s
�zWALinuxAgentShim.eject_isocCs�d}|jdkr&|dk	r&t�|_|jj}|jdkr:t|�|_|j|dk	d�}d}|dk	rb|�||�}t||j|j�}|dk	r�|j	||d�|�
�|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�)r�)r�r�rxr�ru�_fetch_goal_state_from_azure�_get_user_pubkeysr�r�r�r�)rwr��pubkey_infor�Zhttp_client_certificater��ssh_keys�health_reporterr$r$r%�"register_with_azure_and_fetch_data�s.
���z3WALinuxAgentShim.register_with_azure_and_fetch_datar�cCs@|jdkrtd�|_|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.
        NFr��r)r�rur�r�r�r�)rwrr�r�r$r$r%�&register_with_azure_and_report_failure�s

�z7WALinuxAgentShim.register_with_azure_and_report_failure)r�rcCs|��}|�||�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)rwr��unparsed_goal_state_xmlr$r$r%r�s

�z-WALinuxAgentShim._fetch_goal_state_from_azurerzc
Cs�t�d�d�|j�}z,tjddtd��|j�|�}W5QRXWn6t	k
rx}zt
d|tjd��W5d}~XYnXt�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 goalstaterz9failed to register with Azure and fetch GoalState XML: %sr@Nz#Successfully fetched GoalState XML.)r,r>rrr�rrr r�r~rTrGrVr-r�)rwrdrjr5r$r$r%r�s&
���
z3WALinuxAgentShim._get_raw_goal_state_xml_from_azure)r�r�rc
Cs~zt||j|�}Wn6tk
rH}ztd|tjd��W5d}~XYnXd�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: %sr@Nz, zGoalState XML container id: %szGoalState XML instance id: %szGoalState XML incarnation: %s)r�r�rTrGr,rVr�r�r�r�r-)rwr�r�r�r5rBr$r$r%r�2s(����z*WALinuxAgentShim._parse_raw_goal_state_xml)r�r�rcCsHg}|jdk	rD|dk	rD|jdk	rDt�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�r�r,r-r��_filter_pubkeys)rwr�r�r��keys_by_fingerprintr$r$r%r�Ts���
�z"WALinuxAgentShim._get_user_pubkeys)r�r�rcCs|g}|D]n}d|kr,|dr,|�|d�qd|krj|drj|d}||kr\|�||�qvt�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.
        r�r�zIovf-env.xml specified PublicKey fingerprint %s not found in goalstate XMLzFovf-env.xml specified PublicKey with neither value nor fingerprint: %s)r�r,rV)r�r�r�Zpubkeyr�r$r$r%r�~s"
��z WALinuxAgentShim._filter_pubkeys)NN)rr�r�riryr�r'r�Distror�r	rr�r�r�r�r�r�r�rr��listr�r��dictr�r$r$r$r%r��s>
�
�%�
�!�)r�)r�r�r�r�cCs.t|d�}z|j|||d�W�S|��XdS)Nr�)r�r�r�)r�r�r�)r�r�r�r��shimr$r$r%�get_metadata_from_fabric�s
�
r�zerrors.ReportableError)r�r�cCs2t|d�}|��}z|j|d�W5|��XdS)Nr�r�)r�Zas_encoded_reportr�r�)r�r�r�rr$r$r%�report_failure_to_fabric�s

r�cCs(td|tjd�td|tjd�dS)Nzdhclient output stream: %sr@zdhclient error stream: %s)rGr,r-)r6�errr$r$r%�dhcp_log_cb�s��r�c@seZdZdS)�NonAzureDataSourceN)rr�r�r$r$r$r%r��sr�c@s�eZdZddd�Zdddddddddd�	eeeeeeeeeeeee	eeeedd�
dd	�Z
ed
�dd�Zeedd
�dd��Z
deeed�dd�Zdeeeed�dd�Zdd�Zdd�Zdd�ZdS)�	OvfEnvXmlz)http://schemas.dmtf.org/ovf/environment/1z)http://schemas.microsoft.com/windowsazure)Zovf�waNF�	rl�passwordrm�custom_data�disable_ssh_password_auth�public_keys�preprovisioned_vm�preprovisioned_vm_type�provision_guest_proxy_agent)
rlr�rmr�r�r�rrrrc	
Cs>||_||_||_||_||_|p$g|_||_||_|	|_dSrYr�)
rwrlr�rmr�r�r�rrrr$r$r%ry�s

zOvfEnvXml.__init__rzcCs|j|jkSrY)�__dict__)rw�otherr$r$r%�__eq__�szOvfEnvXml.__eq__)�ovf_env_xmlrc
Cszzt�|�}Wn2tjk
r@}ztj|d�|�W5d}~XYnX|�d|j�dkr\td��t�}|�	|�|�
|�|S)z�Parser for ovf-env.xml data.

        :raises NonAzureDataSource: if XML is not in Azure's format.
        :raises errors.ReportableErrorOvfParsingException: if XML is
                unparsable or invalid.
        )Z	exceptionNz./wa:ProvisioningSectionz=Ignoring non-Azure ovf-env.xml: ProvisioningSection not found)r�r�r�rZ"ReportableErrorOvfParsingExceptionr��
NAMESPACESr�r��&_parse_linux_configuration_set_section� _parse_platform_settings_section)�clsrr�r5�instancer$r$r%�
parse_text�s �

zOvfEnvXml.parse_textr�)r�required�	namespacecCsp|�d||ftj�}t|�dkrFd|}t�|�|rBt�|��dSt|�dkrht�d|t|�f��|dS)Nz./%s:%sr�missing configuration for %rr*�*multiple configuration matches for %r (%d))�findallr�r�lenr,r-r�!ReportableErrorOvfInvalidMetadata)rw�noderr
r�matchesrBr$r$r%�_finds"
�


��zOvfEnvXml._find)rr
�
decode_base64�
parse_boolc
Cs�|�d|tj�}t|�dkrBd|}t�|�|r>t�|��|St|�dkrdt�d|t|�f��|dj}	|	dkrz|}	|r�|	dk	r�t	�
d�|	����}	|r�t
�|	�}	|	S)Nz./wa:rrr*rr�)rr�rrr,r-rrr�rLZ	b64decoder�r0rZtranslate_bool)
rwrrr
rr�defaultrrBr�r$r$r%�_parse_propertys*	


��

zOvfEnvXml._parse_propertycCs�|j|ddd�}|j|ddd�}|j|dddd�|_|j|ddd�|_|j|d	dd�|_|j|d
dd�|_|j|dddd�|_|�|�dS)
NZProvisioningSectionT�r
Z!LinuxProvisioningConfigurationSetZ
CustomDataF)rr
ZUserNameZUserPasswordZHostNameZ DisableSshPasswordAuthentication)rr
)rrr�rlr�rmr��_parse_ssh_section)rwr�Zprovisioning_section�
config_setr$r$r%r?sL�������z0OvfEnvXml._parse_linux_configuration_set_sectioncCsb|j|ddd�}|j|ddd�}|j|ddddd�|_|j|ddd�|_|j|d	dddd�|_dS)
NZPlatformSettingsSectionTrZPlatformSettingsZPreprovisionedVmF)rrr
ZPreprovisionedVMTypeZProvisionGuestProxyAgent)rrrrr)rwr�Zplatform_settings_sectionZplatform_settingsr$r$r%r	as:�����z*OvfEnvXml._parse_platform_settings_sectionc	Cs�g|_|j|ddd�}|dkr"dS|j|ddd�}|dkr>dS|�dtj�D]N}|j|ddd�}|j|ddd�}|j|dd	dd
�}|||d�}|j�|�qLdS)NZSSHFrZ
PublicKeysz./wa:PublicKeyZFingerprint�PathZValuer�)rr
)r�r]r�)r�rrr�rrr�)	rwrZssh_sectionZpublic_keys_sectionZ
public_keyr�r]r�r�r$r$r%r}s@�����zOvfEnvXml._parse_ssh_section)r�)FFN)rr�r�rr	rir�r�rr�ryr�classmethodrrrrr	rr$r$r$r%r��sZ��
�����$"r�)NN)JrLrQZloggingrZr�rprM�
contextlibrrrrr�typingrrr	r
rZ	xml.etreerr�Zxml.sax.saxutilsr
Z	cloudinitrrrrrrZcloudinit.reportingrZcloudinit.sources.azurerZ	getLoggerrr,ZDEFAULT_WIRESERVER_ENDPOINTr2r=rFrPrr rr'r9r?rir1rGrSrXr_r�r��intr�rkrtrurTr�r�r�r�r�r�r�r�r�r�r�r$r$r$r%�<module>s� 
� 
U
��


	��7�"?f�
�